-
Notifications
You must be signed in to change notification settings - Fork 7
/
session.go
1000 lines (918 loc) · 29.1 KB
/
session.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 2020-present Open Networking Foundation.
//
// 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 rsm
import (
"context"
"github.com/atomix/atomix-go-framework/pkg/atomix/cluster"
"github.com/atomix/atomix-go-framework/pkg/atomix/errors"
"github.com/atomix/atomix-go-framework/pkg/atomix/logging"
"github.com/atomix/atomix-go-framework/pkg/atomix/storage/protocol/rsm"
streams "github.com/atomix/atomix-go-framework/pkg/atomix/stream"
"github.com/google/uuid"
"google.golang.org/grpc"
"io"
"math"
"math/rand"
"sync"
"time"
)
// SessionOption implements a session option
type SessionOption interface {
prepare(options *sessionOptions)
}
// WithSessionTimeout returns a session SessionOption to configure the session timeout
func WithSessionTimeout(timeout time.Duration) SessionOption {
return sessionTimeoutOption{timeout: timeout}
}
type sessionTimeoutOption struct {
timeout time.Duration
}
func (o sessionTimeoutOption) prepare(options *sessionOptions) {
options.timeout = o.timeout
}
type sessionOptions struct {
id string
timeout time.Duration
}
// NewSession creates a new Session for the given partition
// name is the name of the primitive
// handler is the primitive's session handler
func NewSession(partition cluster.Partition, log logging.Logger, opts ...SessionOption) *Session {
options := &sessionOptions{
id: uuid.New().String(),
timeout: 30 * time.Second,
}
for i := range opts {
opts[i].prepare(options)
}
return &Session{
partition: partition,
Timeout: options.timeout,
streams: make(map[uint64]*StreamState),
log: log,
mu: sync.RWMutex{},
ticker: time.NewTicker(options.timeout / 2),
}
}
// Session maintains the session for a primitive
type Session struct {
partition cluster.Partition
Timeout time.Duration
SessionID uint64
lastIndex uint64
requestID uint64
responseID uint64
streams map[uint64]*StreamState
log logging.Logger
conn *grpc.ClientConn
leader *cluster.Replica
mu sync.RWMutex
ticker *time.Ticker
}
// DoCommand submits a command to the service
func (s *Session) DoCommand(ctx context.Context, service rsm.ServiceId, name string, input []byte) ([]byte, error) {
requestContext := s.nextCommandContext()
response, responseStatus, responseContext, err := s.doCommand(ctx, name, input, service, requestContext)
if err != nil {
return nil, err
}
if responseStatus.Code != rsm.SessionResponseCode_OK {
return nil, rsm.GetErrorFromStatus(responseStatus)
}
s.recordCommandResponse(requestContext, responseContext)
return response, nil
}
// doCommand submits a command to the service
func (s *Session) doCommand(ctx context.Context, name string, input []byte, service rsm.ServiceId, command rsm.SessionCommandContext) ([]byte, rsm.SessionResponseStatus, rsm.SessionResponseContext, error) {
request := &rsm.StorageRequest{
PartitionID: uint32(s.partition.ID()),
Request: &rsm.SessionRequest{
Request: &rsm.SessionRequest_Command{
Command: &rsm.SessionCommandRequest{
Context: command,
Command: rsm.ServiceCommandRequest{
Service: service,
Request: &rsm.ServiceCommandRequest_Operation{
Operation: &rsm.ServiceOperationRequest{
Method: name,
Value: input,
},
},
},
},
},
},
}
response, err := s.doRequest(ctx, request)
if err != nil {
return nil, rsm.SessionResponseStatus{}, rsm.SessionResponseContext{}, err
}
return response.Response.GetCommand().Response.GetOperation().Result, response.Response.Status, response.Response.GetCommand().GetContext(), err
}
// DoCommandStream submits a streaming command to the service
func (s *Session) DoCommandStream(ctx context.Context, service rsm.ServiceId, name string, input []byte, outStream streams.WriteStream) error {
streamState, requestContext := s.nextStream()
ch := make(chan streams.Result)
inStream := streams.NewChannelStream(ch)
err := s.doCommandStream(context.Background(), name, input, service, requestContext, inStream)
if err != nil {
return err
}
go func() {
for {
select {
case result, ok := <-ch:
if !ok {
s.deleteStream(streamState.ID)
return
}
if result.Failed() {
s.deleteStream(streamState.ID)
outStream.Error(result.Error)
outStream.Close()
return
}
response := result.Value.(PartitionOutput)
switch response.Type {
case rsm.SessionResponseType_OPEN_STREAM:
if streamState.serialize(response.Context) {
outStream.Send(response.Result)
}
case rsm.SessionResponseType_CLOSE_STREAM:
if streamState.serialize(response.Context) {
outStream.Close()
streamState.Close()
return
}
case rsm.SessionResponseType_RESPONSE:
// Record the response
s.recordCommandResponse(requestContext, response.Context)
// Attempt to serialize the response to the stream and skip the response if serialization failed.
if streamState.serialize(response.Context) {
outStream.Send(response.Result)
}
}
case <-ctx.Done():
s.deleteStream(streamState.ID)
outStream.Error(ctx.Err())
outStream.Close()
return
}
}
}()
return nil
}
// doCommandStream submits a streaming command to the service
func (s *Session) doCommandStream(ctx context.Context, name string, input []byte, service rsm.ServiceId, context rsm.SessionCommandContext, stream streams.WriteStream) error {
request := &rsm.StorageRequest{
PartitionID: uint32(s.partition.ID()),
Request: &rsm.SessionRequest{
Request: &rsm.SessionRequest_Command{
Command: &rsm.SessionCommandRequest{
Context: context,
Command: rsm.ServiceCommandRequest{
Service: service,
Request: &rsm.ServiceCommandRequest_Operation{
Operation: &rsm.ServiceOperationRequest{
Method: name,
Value: input,
},
},
},
},
},
},
}
return s.doStream(ctx, request, streams.NewDecodingStream(stream, func(value interface{}, err error) (interface{}, error) {
if err != nil {
return nil, err
}
response := value.(*rsm.StorageResponse)
commandResponse := response.Response.GetCommand()
var result []byte
if commandResponse.Response.GetOperation() != nil {
result = commandResponse.Response.GetOperation().Result
}
return PartitionOutput{
Type: response.Response.Type,
Status: response.Response.Status,
Context: commandResponse.Context,
Result: streams.Result{
Value: result,
},
}, nil
}), true)
}
// DoQuery submits a query to the service
func (s *Session) DoQuery(ctx context.Context, service rsm.ServiceId, name string, input []byte) ([]byte, error) {
requestContext := s.getQueryContext()
response, responseStatus, responseContext, err := s.doQuery(ctx, name, input, service, requestContext)
if err != nil {
return nil, err
}
if responseStatus.Code != rsm.SessionResponseCode_OK {
return nil, rsm.GetErrorFromStatus(responseStatus)
}
s.recordQueryResponse(requestContext, responseContext)
return response, nil
}
// doQuery submits a query to the service
func (s *Session) doQuery(ctx context.Context, name string, input []byte, service rsm.ServiceId, query rsm.SessionQueryContext) ([]byte, rsm.SessionResponseStatus, rsm.SessionResponseContext, error) {
request := &rsm.StorageRequest{
PartitionID: uint32(s.partition.ID()),
Request: &rsm.SessionRequest{
Request: &rsm.SessionRequest_Query{
Query: &rsm.SessionQueryRequest{
Context: query,
Query: rsm.ServiceQueryRequest{
Service: &service,
Request: &rsm.ServiceQueryRequest_Operation{
Operation: &rsm.ServiceOperationRequest{
Method: name,
Value: input,
},
},
},
},
},
},
}
response, err := s.doRequest(ctx, request)
if err != nil {
return nil, rsm.SessionResponseStatus{}, rsm.SessionResponseContext{}, err
}
return response.Response.GetQuery().Response.GetOperation().Result, response.Response.Status, response.Response.GetQuery().GetContext(), err
}
// DoQueryStream submits a streaming query to the service
func (s *Session) DoQueryStream(ctx context.Context, service rsm.ServiceId, name string, input []byte, outStream streams.WriteStream) error {
requestContext := s.getQueryContext()
ch := make(chan streams.Result)
inStream := streams.NewChannelStream(ch)
err := s.doQueryStream(context.Background(), name, input, service, requestContext, inStream)
if err != nil {
return err
}
go func() {
for {
select {
case result, ok := <-ch:
if !ok {
return
}
if result.Failed() {
outStream.Error(result.Error)
outStream.Close()
return
}
response := result.Value.(PartitionOutput)
switch response.Type {
case rsm.SessionResponseType_OPEN_STREAM:
case rsm.SessionResponseType_CLOSE_STREAM:
outStream.Close()
return
case rsm.SessionResponseType_RESPONSE:
s.recordQueryResponse(requestContext, response.Context)
outStream.Send(response.Result)
}
case <-ctx.Done():
outStream.Error(ctx.Err())
outStream.Close()
return
}
}
}()
return nil
}
// doQueryStream submits a streaming query to the service
func (s *Session) doQueryStream(ctx context.Context, name string, input []byte, service rsm.ServiceId, context rsm.SessionQueryContext, stream streams.WriteStream) error {
request := &rsm.StorageRequest{
PartitionID: uint32(s.partition.ID()),
Request: &rsm.SessionRequest{
Request: &rsm.SessionRequest_Query{
Query: &rsm.SessionQueryRequest{
Context: context,
Query: rsm.ServiceQueryRequest{
Service: &service,
Request: &rsm.ServiceQueryRequest_Operation{
Operation: &rsm.ServiceOperationRequest{
Method: name,
Value: input,
},
},
},
},
},
},
}
return s.doStream(ctx, request, streams.NewDecodingStream(stream, func(value interface{}, err error) (interface{}, error) {
if err != nil {
return nil, err
}
response := value.(*rsm.StorageResponse)
queryResponse := response.Response.GetQuery()
var result []byte
if queryResponse.Response.GetOperation() != nil {
result = queryResponse.Response.GetOperation().Result
}
return PartitionOutput{
Type: response.Response.Type,
Status: response.Response.Status,
Context: queryResponse.Context,
Result: streams.Result{
Value: result,
},
}, nil
}), false)
}
// doMetadata submits a metadata query to the service
func (s *Session) doMetadata(ctx context.Context, serviceType string, namespace string, context rsm.SessionQueryContext) ([]*rsm.ServiceId, rsm.SessionResponseStatus, rsm.SessionResponseContext, error) {
request := &rsm.StorageRequest{
PartitionID: uint32(s.partition.ID()),
Request: &rsm.SessionRequest{
Request: &rsm.SessionRequest_Query{
Query: &rsm.SessionQueryRequest{
Context: context,
Query: rsm.ServiceQueryRequest{
Request: &rsm.ServiceQueryRequest_Metadata{
Metadata: &rsm.ServiceMetadataRequest{
Type: serviceType,
},
},
},
},
},
},
}
response, err := s.doRequest(ctx, request)
if err != nil {
return nil, rsm.SessionResponseStatus{}, rsm.SessionResponseContext{}, err
}
return response.Response.GetQuery().Response.GetMetadata().Services, response.Response.Status, response.Response.GetQuery().Context, nil
}
// DoCreateService creates the service
func (s *Session) DoCreateService(ctx context.Context, service rsm.ServiceId) error {
requestContext := s.nextCommandContext()
responseStatus, responseContext, err := s.doCreateService(ctx, service, requestContext)
if err != nil {
return err
}
if responseStatus.Code != rsm.SessionResponseCode_OK {
return rsm.GetErrorFromStatus(responseStatus)
}
s.recordCommandResponse(requestContext, responseContext)
return nil
}
// doCreateService creates the service
func (s *Session) doCreateService(ctx context.Context, service rsm.ServiceId, context rsm.SessionCommandContext) (rsm.SessionResponseStatus, rsm.SessionResponseContext, error) {
request := &rsm.StorageRequest{
PartitionID: uint32(s.partition.ID()),
Request: &rsm.SessionRequest{
Request: &rsm.SessionRequest_Command{
Command: &rsm.SessionCommandRequest{
Context: context,
Command: rsm.ServiceCommandRequest{
Service: service,
Request: &rsm.ServiceCommandRequest_Create{
Create: &rsm.ServiceCreateRequest{},
},
},
},
},
},
}
response, err := s.doRequest(ctx, request)
if err != nil {
return rsm.SessionResponseStatus{}, rsm.SessionResponseContext{}, err
}
return response.Response.Status, response.Response.GetCommand().Context, nil
}
// DoCloseService closes the service
func (s *Session) DoCloseService(ctx context.Context, service rsm.ServiceId) error {
requestContext := s.nextCommandContext()
responseStatus, responseContext, err := s.doCloseService(ctx, service, requestContext)
if err != nil {
return err
}
if responseStatus.Code != rsm.SessionResponseCode_OK {
return rsm.GetErrorFromStatus(responseStatus)
}
s.recordCommandResponse(requestContext, responseContext)
return nil
}
// doCloseService closes the service
func (s *Session) doCloseService(ctx context.Context, service rsm.ServiceId, context rsm.SessionCommandContext) (rsm.SessionResponseStatus, rsm.SessionResponseContext, error) {
request := &rsm.StorageRequest{
PartitionID: uint32(s.partition.ID()),
Request: &rsm.SessionRequest{
Request: &rsm.SessionRequest_Command{
Command: &rsm.SessionCommandRequest{
Context: context,
Command: rsm.ServiceCommandRequest{
Service: service,
Request: &rsm.ServiceCommandRequest_Close{
Close: &rsm.ServiceCloseRequest{},
},
},
},
},
},
}
response, err := s.doRequest(ctx, request)
if err != nil {
return rsm.SessionResponseStatus{}, rsm.SessionResponseContext{}, err
}
return response.Response.Status, response.Response.GetCommand().Context, nil
}
// DoDeleteService deletes the service
func (s *Session) DoDeleteService(ctx context.Context, service rsm.ServiceId) error {
requestContext := s.nextCommandContext()
responseStatus, responseContext, err := s.doDeleteService(ctx, service, requestContext)
if err != nil {
return err
}
if responseStatus.Code != rsm.SessionResponseCode_OK {
return rsm.GetErrorFromStatus(responseStatus)
}
s.recordCommandResponse(requestContext, responseContext)
return nil
}
// doDeleteService deletes the service
func (s *Session) doDeleteService(ctx context.Context, service rsm.ServiceId, context rsm.SessionCommandContext) (rsm.SessionResponseStatus, rsm.SessionResponseContext, error) {
request := &rsm.StorageRequest{
PartitionID: uint32(s.partition.ID()),
Request: &rsm.SessionRequest{
Request: &rsm.SessionRequest_Command{
Command: &rsm.SessionCommandRequest{
Context: context,
Command: rsm.ServiceCommandRequest{
Service: service,
Request: &rsm.ServiceCommandRequest_Delete{
Delete: &rsm.ServiceDeleteRequest{},
},
},
},
},
},
}
response, err := s.doRequest(ctx, request)
if err != nil {
return rsm.SessionResponseStatus{}, rsm.SessionResponseContext{}, err
}
return response.Response.Status, response.Response.GetCommand().Context, nil
}
// open creates the session and begins keep-alives
func (s *Session) open(ctx context.Context) error {
requestContext, _ := s.getStateContexts()
responseStatus, responseContext, err := s.doOpenSession(ctx, requestContext, &s.Timeout)
if err != nil {
return err
}
if responseStatus.Code != rsm.SessionResponseCode_OK {
return rsm.GetErrorFromStatus(responseStatus)
}
s.mu.Lock()
s.SessionID = responseContext.SessionID
s.lastIndex = responseContext.SessionID
s.mu.Unlock()
go func() {
for range s.ticker.C {
_ = s.keepAlive(context.TODO())
}
}()
return nil
}
// doOpenSession opens a new session
func (s *Session) doOpenSession(ctx context.Context, context rsm.SessionCommandContext, timeout *time.Duration) (rsm.SessionResponseStatus, rsm.SessionResponseContext, error) {
request := &rsm.StorageRequest{
PartitionID: uint32(s.partition.ID()),
Request: &rsm.SessionRequest{
Request: &rsm.SessionRequest_OpenSession{
OpenSession: &rsm.OpenSessionRequest{
Timeout: timeout,
},
},
},
}
response, err := s.doRequest(ctx, request)
if err != nil {
return rsm.SessionResponseStatus{}, rsm.SessionResponseContext{}, err
}
sessionID := response.Response.GetOpenSession().SessionID
return response.Response.Status, rsm.SessionResponseContext{
SessionID: sessionID,
StreamID: sessionID,
Index: sessionID,
}, nil
}
// keepAlive keeps the session alive
func (s *Session) keepAlive(ctx context.Context) error {
requestContext, streamContexts := s.getStateContexts()
responseStatus, responseContext, err := s.doKeepAliveSession(ctx, requestContext, streamContexts)
if err != nil {
return err
}
if responseStatus.Code != rsm.SessionResponseCode_OK {
return rsm.GetErrorFromStatus(responseStatus)
}
s.recordCommandResponse(requestContext, responseContext)
return nil
}
// doKeepAliveSession keeps a session alive
func (s *Session) doKeepAliveSession(ctx context.Context, context rsm.SessionCommandContext, streams []rsm.SessionStreamContext) (rsm.SessionResponseStatus, rsm.SessionResponseContext, error) {
request := &rsm.StorageRequest{
PartitionID: uint32(s.partition.ID()),
Request: &rsm.SessionRequest{
Request: &rsm.SessionRequest_KeepAlive{
KeepAlive: &rsm.KeepAliveRequest{
SessionID: context.SessionID,
CommandSequence: context.SequenceNumber,
Streams: streams,
},
},
},
}
response, err := s.doRequest(ctx, request)
if err != nil {
return rsm.SessionResponseStatus{}, rsm.SessionResponseContext{}, err
}
return response.Response.Status, rsm.SessionResponseContext{SessionID: context.SessionID}, nil
}
// doRequest submits a storage request
func (s *Session) doRequest(ctx context.Context, request *rsm.StorageRequest) (*rsm.StorageResponse, error) {
i := 1
for {
s.log.Debugf("Sending StorageRequest %+v", request)
response, err := s.tryRequest(ctx, request)
if err == nil {
s.log.Debugf("Received StorageResponse %+v", response)
switch response.Response.Status.Code {
case rsm.SessionResponseCode_OK:
return response, err
case rsm.SessionResponseCode_NOT_LEADER:
if response.Response.Status.Leader != "" {
s.reconnect(cluster.ReplicaID(response.Response.Status.Leader))
} else {
select {
case <-time.After(10 * time.Millisecond * time.Duration(math.Min(math.Pow(2, float64(i)), 1000))):
i++
case <-ctx.Done():
return nil, ctx.Err()
}
}
default:
return response, rsm.GetErrorFromStatus(response.Response.Status)
}
} else if err == context.Canceled {
return nil, errors.NewCanceled(err.Error())
} else {
s.log.Warnf("Sending StorageRequest %+v failed: %s", request, err)
select {
case <-time.After(10 * time.Millisecond * time.Duration(math.Min(math.Pow(2, float64(i)), 1000))):
i++
case <-ctx.Done():
return nil, ctx.Err()
}
}
}
}
// tryRequest submits a storage request
func (s *Session) tryRequest(ctx context.Context, request *rsm.StorageRequest) (*rsm.StorageResponse, error) {
conn, err := s.connect()
if err != nil {
return nil, err
}
client := rsm.NewStorageServiceClient(conn)
stream, err := client.Request(ctx, request)
if err != nil {
return nil, err
}
// Wait for the result
response, err := stream.Recv()
if err != nil {
return nil, err
}
return response, nil
}
// doStream submits a streaming request to the service
func (s *Session) doStream(ctx context.Context, request *rsm.StorageRequest, stream streams.WriteStream, idempotent bool) error {
go s.tryStream(ctx, request, stream, idempotent,0, false)
return nil
}
// tryStream submits a stream request to the service recursively
func (s *Session) tryStream(ctx context.Context, request *rsm.StorageRequest, stream streams.WriteStream, idempotent bool, attempts int, open bool) {
conn, err := s.connect()
if err == context.Canceled {
stream.Error(err)
stream.Close()
return
} else if err != nil {
s.log.Warnf("StorageRequest %+v failed", request, err)
if idempotent || !open {
go s.retryStream(ctx, request, stream, idempotent, attempts, open)
} else {
stream.Error(errors.From(err))
stream.Close()
}
return
}
client := rsm.NewStorageServiceClient(conn)
s.log.Debugf("Sending StorageRequest %+v", request)
responseStream, err := client.Request(ctx, request)
if err != nil {
s.log.Warnf("Sending StorageRequest %+v failed: %s", request, err)
stream.Error(err)
stream.Close()
return
}
for {
response, err := responseStream.Recv()
if err == io.EOF {
stream.Close()
return
} else if err == context.Canceled {
stream.Error(err)
stream.Close()
return
} else if err != nil {
s.log.Warnf("StorageRequest %+v failed", request, err)
if idempotent || !open {
go s.retryStream(ctx, request, stream, idempotent, attempts, open)
} else {
stream.Error(errors.From(err))
stream.Close()
}
return
} else {
s.log.Debugf("Received StorageResponse %+v", response)
switch response.Response.Status.Code {
case rsm.SessionResponseCode_OK:
stream.Value(response)
switch response.Response.Type {
case rsm.SessionResponseType_OPEN_STREAM:
if !open {
open = true
}
case rsm.SessionResponseType_CLOSE_STREAM:
stream.Close()
return
}
case rsm.SessionResponseCode_NOT_LEADER:
if response.Response.Status.Leader != "" {
s.log.Debugf("Reconnecting to leader %s", response.Response.Status.Leader)
s.reconnect(cluster.ReplicaID(response.Response.Status.Leader))
}
go s.retryStream(ctx, request, stream, idempotent, attempts, open)
return
default:
stream.Error(rsm.GetErrorFromStatus(response.Response.Status))
stream.Close()
return
}
attempts = 0
}
}
}
func (s *Session) retryStream(ctx context.Context, request *rsm.StorageRequest, stream streams.WriteStream, idempotent bool, attempts int, open bool) {
attempts++
select {
case <-time.After(10 * time.Millisecond * time.Duration(math.Min(math.Pow(2, float64(attempts)), 1000))):
s.tryStream(ctx, request, stream, idempotent, attempts, open)
case <-ctx.Done():
stream.Error(errors.NewTimeout(ctx.Err().Error()))
stream.Close()
}
}
// connect gets the connection to the service
func (s *Session) connect() (*grpc.ClientConn, error) {
s.mu.RLock()
conn := s.conn
s.mu.RUnlock()
if conn != nil {
return conn, nil
}
s.mu.Lock()
defer s.mu.Unlock()
conn = s.conn
if conn != nil {
return conn, nil
}
if s.leader == nil {
replicas := make([]*cluster.Replica, 0)
for _, replica := range s.partition.Replicas() {
replicas = append(replicas, replica)
}
s.leader = replicas[rand.Intn(len(replicas))]
s.conn = nil
}
s.log.Infof("Connecting to partition %d replica %s", s.partition.ID(), s.leader.ID)
conn, err := s.leader.Connect(context.Background(), cluster.WithDialOption(grpc.WithInsecure()))
if err != nil {
s.log.Warnf("Connecting to partition %d replica %s failed", s.partition.ID(), s.leader.ID, err)
return nil, err
}
s.conn = conn
return conn, nil
}
// reconnect the connection to the given leader
func (s *Session) reconnect(replica cluster.ReplicaID) {
if replica == "" {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if s.leader.ID == replica {
return
}
leader, ok := s.partition.Replica(replica)
if !ok {
return
}
s.leader = leader
s.conn = nil
}
// disconnect closes the connections
func (s *Session) disconnect() error {
s.mu.Lock()
s.conn = nil
s.mu.Unlock()
return nil
}
// Close closes the session
func (s *Session) Close() error {
err := s.close(context.TODO())
s.ticker.Stop()
return err
}
// close closes the session
func (s *Session) close(ctx context.Context) error {
requestContext, _ := s.getStateContexts()
responseStatus, responseContext, err := s.doCloseSession(ctx, requestContext)
if err != nil {
return err
}
if responseStatus.Code != rsm.SessionResponseCode_OK {
return rsm.GetErrorFromStatus(responseStatus)
}
s.recordCommandResponse(requestContext, responseContext)
return nil
}
// doCloseSession closes a session
func (s *Session) doCloseSession(ctx context.Context, context rsm.SessionCommandContext) (rsm.SessionResponseStatus, rsm.SessionResponseContext, error) {
request := &rsm.StorageRequest{
PartitionID: uint32(s.partition.ID()),
Request: &rsm.SessionRequest{
Request: &rsm.SessionRequest_CloseSession{
CloseSession: &rsm.CloseSessionRequest{
SessionID: context.SessionID,
},
},
},
}
response, err := s.doRequest(ctx, request)
if err != nil {
return rsm.SessionResponseStatus{}, rsm.SessionResponseContext{}, err
}
return response.Response.Status, rsm.SessionResponseContext{SessionID: context.SessionID}, nil
}
// getStateContexts gets the header for the current state of the session
func (s *Session) getStateContexts() (rsm.SessionCommandContext, []rsm.SessionStreamContext) {
s.mu.RLock()
defer s.mu.RUnlock()
return rsm.SessionCommandContext{
SessionID: s.SessionID,
SequenceNumber: s.responseID,
}, s.getStreamContexts()
}
// getQueryContext gets the current read header
func (s *Session) getQueryContext() rsm.SessionQueryContext {
s.mu.RLock()
defer s.mu.RUnlock()
return rsm.SessionQueryContext{
SessionID: s.SessionID,
LastSequenceNumber: s.responseID,
LastIndex: s.lastIndex,
}
}
// nextCommandContext returns the next write context
func (s *Session) nextCommandContext() rsm.SessionCommandContext {
s.mu.Lock()
defer s.mu.Unlock()
s.requestID = s.requestID + 1
return rsm.SessionCommandContext{
SessionID: s.SessionID,
SequenceNumber: s.requestID,
}
}
// nextStreamHeader returns the next write stream and header
func (s *Session) nextStream() (*StreamState, rsm.SessionCommandContext) {
s.mu.Lock()
defer s.mu.Unlock()
s.requestID = s.requestID + 1
stream := &StreamState{
ID: s.requestID,
session: s,
}
s.streams[s.requestID] = stream
command := rsm.SessionCommandContext{
SessionID: s.SessionID,
SequenceNumber: s.requestID,
}
return stream, command
}
// recordCommandResponse records the index in a response header
func (s *Session) recordCommandResponse(requestContext rsm.SessionCommandContext, responseContext rsm.SessionResponseContext) {
// Use a double-checked lock to avoid locking when multiple responses are received for an index.
s.mu.RLock()
if responseContext.Index > s.lastIndex {
s.mu.RUnlock()
s.mu.Lock()
// If the request ID is greater than the highest response ID, update the response ID.
if requestContext.SequenceNumber > s.responseID {
s.responseID = requestContext.SequenceNumber
}
// If the response index has increased, update the last received index
if responseContext.Index > s.lastIndex {
s.lastIndex = responseContext.Index
}
s.mu.Unlock()
} else {
s.mu.RUnlock()
}
}
// recordQueryResponse records the index in a response header
func (s *Session) recordQueryResponse(requestContext rsm.SessionQueryContext, responseContext rsm.SessionResponseContext) {
// Use a double-checked lock to avoid locking when multiple responses are received for an index.
s.mu.RLock()
if responseContext.Index > s.lastIndex {
s.mu.RUnlock()
s.mu.Lock()
// If the response index has increased, update the last received index
if responseContext.Index > s.lastIndex {
s.lastIndex = responseContext.Index
}
s.mu.Unlock()
} else {
s.mu.RUnlock()
}
}
// deleteStream deletes the given stream from the session
func (s *Session) deleteStream(streamID uint64) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.streams, streamID)
}
// getStreamHeaders returns a slice of headers for all open streams
func (s *Session) getStreamContexts() []rsm.SessionStreamContext {
result := make([]rsm.SessionStreamContext, 0, len(s.streams))
for _, stream := range s.streams {
if stream.ID <= s.responseID {
result = append(result, stream.getHeader())
}
}
return result
}
// StreamState manages the context for a single response stream within a session
type StreamState struct {
ID uint64
session *Session
responseID uint64
mu sync.RWMutex
}
// getHeader returns the current header for the stream
func (s *StreamState) getHeader() rsm.SessionStreamContext {
s.mu.RLock()
defer s.mu.RUnlock()
return rsm.SessionStreamContext{
StreamID: s.ID,
ResponseID: s.responseID,
}
}
// serialize updates the stream response metadata and returns whether the response was received in sequential order
func (s *StreamState) serialize(context rsm.SessionResponseContext) bool {
s.mu.Lock()
defer s.mu.Unlock()
if context.Sequence == s.responseID+1 {
s.responseID++
return true
}
return false
}
// Close closes the stream
func (s *StreamState) Close() {
s.session.deleteStream(s.ID)
}
// SessionOutput is a result for session-supporting servers containing session header information
type SessionOutput struct {
streams.Result
}