forked from shurcooL/graphql
-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathsubscription.go
1487 lines (1208 loc) · 44.7 KB
/
subscription.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 graphql
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/coder/websocket"
"github.com/coder/websocket/wsjson"
"github.com/google/uuid"
)
// SubscriptionProtocolType represents the protocol specification enum of the subscription
type SubscriptionProtocolType string
// internal subscription status
type SubscriptionStatus int32
const (
// internal state machine status
scStatusInitializing int32 = 0
scStatusRunning int32 = 1
scStatusClosing int32 = 2
// SubscriptionWaiting the subscription hasn't been registered to the server
SubscriptionWaiting SubscriptionStatus = 0
// SubscriptionRunning the subscription is up and running
SubscriptionRunning SubscriptionStatus = 1
// SubscriptionUnsubscribed the subscription was manually unsubscribed by the user
SubscriptionUnsubscribed SubscriptionStatus = 2
// SubscriptionsTransportWS the enum implements the subscription transport that follows Apollo's subscriptions-transport-ws protocol specification
// https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md
SubscriptionsTransportWS SubscriptionProtocolType = "subscriptions-transport-ws"
// GraphQLWS enum implements GraphQL over WebSocket Protocol (graphql-ws)
// https://github.com/enisdenjo/graphql-ws/blob/master/PROTOCOL.md
GraphQLWS SubscriptionProtocolType = "graphql-ws"
// Receiving a message of a type or format which is not specified in this document
// The <error-message> can be vaguely descriptive on why the received message is invalid.
StatusInvalidMessage websocket.StatusCode = 4400
// if the connection is not acknowledged, the socket will be closed immediately with the event 4401: Unauthorized
StatusUnauthorized websocket.StatusCode = 4401
// if the connection is unauthorized and be rejected by the server.
StatusForbidden websocket.StatusCode = 4403
// Connection initialisation timeout
StatusConnectionInitialisationTimeout websocket.StatusCode = 4408
// Subscriber for <generated-id> already exists
StatusSubscriberAlreadyExists websocket.StatusCode = 4409
// Too many initialisation requests
StatusTooManyInitialisationRequests websocket.StatusCode = 4429
)
// OperationMessageType represents a subscription message enum type
type OperationMessageType string
const (
// Unknown operation type, for logging only
GQLUnknown OperationMessageType = "unknown"
// Internal status, for logging only
GQLInternal OperationMessageType = "internal"
// @deprecated: use GQLUnknown instead
GQL_UNKNOWN = GQLUnknown
// @deprecated: use GQLInternal instead
GQL_INTERNAL = GQLInternal
)
var (
// ErrSubscriptionStopped a special error which forces the subscription stop.
ErrSubscriptionStopped = errors.New("subscription stopped")
// ErrSubscriptionNotExists an error denoting that subscription does not exist.
ErrSubscriptionNotExists = errors.New("subscription does not exist")
// ErrWebsocketConnectionIdleTimeout indicates that the websocket connection has not received any new messages for a long interval.
ErrWebsocketConnectionIdleTimeout = errors.New("websocket connection idle timeout")
// errRestartSubscriptionClient an error to ask the subscription client to restart.
errRestartSubscriptionClient = errors.New("restart subscription client")
)
// OperationMessage represents a subscription operation message
type OperationMessage struct {
ID string `json:"id,omitempty"`
Type OperationMessageType `json:"type"`
Payload json.RawMessage `json:"payload,omitempty"`
}
// String overrides the default Stringer to return json string for debugging
func (om OperationMessage) String() string {
bs, _ := json.Marshal(om)
return string(bs)
}
// WebsocketHandler abstracts WebSocket connection functions
// ReadJSON and WriteJSON data of a frame from the WebSocket connection.
// Close the WebSocket connection.
type WebsocketConn interface {
ReadJSON(v interface{}) error
WriteJSON(v interface{}) error
Ping() error
Close() error
// SetReadLimit sets the maximum size in bytes for a message read from the peer. If a
// message exceeds the limit, the connection sends a close message to the peer
// and returns ErrReadLimit to the application.
SetReadLimit(limit int64)
// GetCloseStatus tries to get WebSocket close status from error
// return -1 if the error is unknown
// https://www.iana.org/assignments/websocket/websocket.xhtml
GetCloseStatus(error) int32
}
// SubscriptionProtocol abstracts the life-cycle of subscription protocol implementation for a specific transport protocol
type SubscriptionProtocol interface {
// GetSubprotocols returns subprotocol names of the subscription transport
// The graphql server depends on the Sec-WebSocket-Protocol header to return the correct message specification
GetSubprotocols() []string
// ConnectionInit sends a initial request to establish a connection within the existing socket
ConnectionInit(ctx *SubscriptionContext, connectionParams map[string]interface{}) error
// Subscribe requests an graphql operation specified in the payload message
Subscribe(ctx *SubscriptionContext, sub Subscription) error
// Unsubscribe sends a request to stop listening and complete the subscription
Unsubscribe(ctx *SubscriptionContext, sub Subscription) error
// OnMessage listens ongoing messages from server
OnMessage(ctx *SubscriptionContext, subscription Subscription, message OperationMessage) error
// Close terminates all subscriptions of the current websocket
Close(ctx *SubscriptionContext) error
}
// SubscriptionContext represents a shared context for protocol implementations with the websocket connection inside
type SubscriptionContext struct {
context.Context
client *SubscriptionClient
websocketConn WebsocketConn
connectionInitAt time.Time
lastReceivedMessageAt time.Time
acknowledged bool
closed bool
cancel context.CancelFunc
subscriptions map[string]Subscription
mutex sync.Mutex
}
// Log prints condition logging with message type filters
func (sc *SubscriptionContext) Log(message interface{}, source string, opType OperationMessageType) {
sc.client.printLog(message, source, opType)
}
// OnConnectionAlive executes the OnConnectionAlive callback if exists.
func (sc *SubscriptionContext) OnConnectionAlive() {
if sc.client != nil && sc.client.onConnectionAlive != nil {
sc.client.onConnectionAlive()
}
}
// OnConnected executes the OnConnected callback if exists.
func (sc *SubscriptionContext) OnConnected() {
if sc.client != nil && sc.client.onConnected != nil {
sc.client.onConnected()
}
}
// OnDisconnected executes the OnDisconnected callback if exists.
func (sc *SubscriptionContext) OnDisconnected() {
if sc.client != nil && sc.client.onDisconnected != nil {
sc.client.onDisconnected()
}
}
// OnSubscriptionComplete executes the OnSubscriptionComplete callback if exists.
func (sc *SubscriptionContext) OnSubscriptionComplete(subscription Subscription) {
if sc.client != nil && sc.client.onSubscriptionComplete != nil {
sc.client.onSubscriptionComplete(subscription)
}
}
// SetCancel set the cancel function of the inner context
func (sc *SubscriptionContext) Cancel() {
sc.mutex.Lock()
defer sc.mutex.Unlock()
if sc.cancel != nil {
sc.cancel()
sc.cancel = nil
}
}
// GetWebsocketConn get the current websocket connection
func (sc *SubscriptionContext) GetWebsocketConn() WebsocketConn {
sc.mutex.Lock()
defer sc.mutex.Unlock()
return sc.websocketConn
}
// SetWebsocketConn set the current websocket connection
func (sc *SubscriptionContext) SetWebsocketConn(conn WebsocketConn) {
sc.mutex.Lock()
defer sc.mutex.Unlock()
sc.websocketConn = conn
}
func (sc *SubscriptionContext) getConnectionInitAt() time.Time {
sc.mutex.Lock()
defer sc.mutex.Unlock()
return sc.connectionInitAt
}
func (sc *SubscriptionContext) setLastReceivedMessageAt(t time.Time) {
sc.mutex.Lock()
defer sc.mutex.Unlock()
sc.lastReceivedMessageAt = t
}
func (sc *SubscriptionContext) getLastReceivedMessageAt() time.Time {
sc.mutex.Lock()
defer sc.mutex.Unlock()
return sc.lastReceivedMessageAt
}
// GetSubscription get the subscription state by id
func (sc *SubscriptionContext) GetSubscription(id string) *Subscription {
sc.mutex.Lock()
defer sc.mutex.Unlock()
if sc.subscriptions == nil {
return nil
}
sub, found := sc.subscriptions[id]
if found {
return &sub
}
for _, s := range sc.subscriptions {
if id == s.id {
return &s
}
}
return nil
}
// GetSubscriptionsLength returns the length of subscriptions by status
func (sc *SubscriptionContext) GetSubscriptionsLength(status []SubscriptionStatus) int {
sc.mutex.Lock()
defer sc.mutex.Unlock()
if len(status) == 0 {
return len(sc.subscriptions)
}
count := 0
for _, sub := range sc.subscriptions {
for _, s := range status {
if sub.status == s {
count++
break
}
}
}
return count
}
// GetSubscription get all available subscriptions in the context
func (sc *SubscriptionContext) GetSubscriptions() map[string]Subscription {
sc.mutex.Lock()
defer sc.mutex.Unlock()
newMap := make(map[string]Subscription)
for k, v := range sc.subscriptions {
newMap[k] = v
}
return newMap
}
// SetSubscription set the input subscription state into the context
// if subscription is nil, removes the subscription from the map
func (sc *SubscriptionContext) SetSubscription(key string, sub *Subscription) {
sc.mutex.Lock()
defer sc.mutex.Unlock()
if sub == nil {
delete(sc.subscriptions, key)
} else {
sc.subscriptions[key] = *sub
}
}
// GetAcknowledge get the acknowledge status
func (sc *SubscriptionContext) GetAcknowledge() bool {
sc.mutex.Lock()
defer sc.mutex.Unlock()
return sc.acknowledged
}
// SetAcknowledge set the acknowledge status
func (sc *SubscriptionContext) SetAcknowledge(value bool) {
sc.mutex.Lock()
defer sc.mutex.Unlock()
sc.acknowledged = value
}
// IsClosed get the closed status
func (sc *SubscriptionContext) IsClosed() bool {
sc.mutex.Lock()
defer sc.mutex.Unlock()
return sc.closed
}
// SetAcknowledge set the acknowledge status
func (sc *SubscriptionContext) SetClosed(value bool) {
sc.mutex.Lock()
defer sc.mutex.Unlock()
sc.closed = value
}
// Close closes the context and the inner websocket connection if exists
func (sc *SubscriptionContext) Close() error {
if sc.IsClosed() {
return nil
}
var err error
sc.SetClosed(true)
if conn := sc.GetWebsocketConn(); conn != nil {
if sc.client.onDisconnected != nil {
sc.client.onDisconnected()
}
err = conn.Close()
}
sc.Cancel()
if errors.Is(err, net.ErrClosed) {
return nil
}
return err
}
// Send emits a message to the graphql server
func (sc *SubscriptionContext) Send(message interface{}, opType OperationMessageType) error {
if conn := sc.GetWebsocketConn(); conn != nil {
sc.Log(message, "client", opType)
return conn.WriteJSON(message)
}
return nil
}
// initializes the websocket connection
func (sc *SubscriptionContext) init(parentContext context.Context) error {
now := time.Now()
for {
ctx, cancel := context.WithCancel(parentContext)
conn, err := sc.client.createConn(ctx, sc.client.url, sc.client.websocketOptions)
if err == nil {
conn.SetReadLimit(sc.client.readLimit)
// send connection init event to the server
connectionParams := sc.client.connectionParams
if sc.client.connectionParamsFn != nil {
connectionParams = sc.client.connectionParamsFn()
}
sc.mutex.Lock()
sc.websocketConn = conn
sc.connectionInitAt = time.Now()
sc.mutex.Unlock()
err = sc.client.protocol.ConnectionInit(sc, connectionParams)
if err == nil {
sc.Context = ctx
sc.cancel = cancel
return nil
}
_ = conn.Close()
}
cancel()
if errors.Is(err, context.Canceled) {
return err
}
if sc.client.retryTimeout > 0 && now.Add(sc.client.retryTimeout).Before(time.Now()) {
sc.OnDisconnected()
return err
}
sc.Log(fmt.Sprintf("%s. retry in %d second...", err.Error(), sc.client.retryDelay/time.Second), "client", GQLInternal)
time.Sleep(sc.client.retryDelay)
}
}
// run the subscription client goroutine session to receive WebSocket messages.
func (sc *SubscriptionContext) run() {
for {
select {
case <-sc.Done():
return
default:
var message OperationMessage
conn := sc.websocketConn
if conn == nil {
return
}
if err := conn.ReadJSON(&message); err != nil {
// manual EOF check
if err == io.EOF || strings.Contains(err.Error(), "EOF") || errors.Is(err, net.ErrClosed) || strings.Contains(err.Error(), "connection reset by peer") {
sc.Log(err.Error(), "client", GQLConnectionError)
sc.client.errorChan <- errRestartSubscriptionClient
return
}
if errors.Is(err, context.Canceled) {
return
}
closeStatus := conn.GetCloseStatus(err)
for _, retryCode := range sc.client.retryStatusCodes {
if (len(retryCode) == 1 && retryCode[0] == closeStatus) ||
(len(retryCode) >= 2 && retryCode[0] <= closeStatus && closeStatus <= retryCode[1]) {
sc.client.errorChan <- errRestartSubscriptionClient
return
}
}
if closeStatus < 0 {
sc.Log(err, "server", GQL_CONNECTION_ERROR)
continue
}
switch websocket.StatusCode(closeStatus) {
case websocket.StatusBadGateway, websocket.StatusNoStatusRcvd, websocket.StatusServiceRestart, websocket.StatusTryAgainLater, websocket.StatusMessageTooBig, websocket.StatusInvalidFramePayloadData:
sc.Log(err, "server", GQL_CONNECTION_ERROR)
sc.client.errorChan <- errRestartSubscriptionClient
case websocket.StatusNormalClosure, websocket.StatusAbnormalClosure:
// close event from websocket client, exiting...
sc.client.close(sc)
default:
// let the user to handle unknown errors manually.
sc.Log(err, "server", GQL_CONNECTION_ERROR)
sc.client.errorChan <- err
}
return
}
sc.setLastReceivedMessageAt(time.Now())
sub := sc.GetSubscription(message.ID)
if sub == nil {
sub = &Subscription{}
}
execMessage := func() {
if err := sc.client.protocol.OnMessage(sc, *sub, message); err != nil {
sc.client.errorChan <- err
}
sc.client.checkSubscriptionStatuses(sc)
}
if sc.client.syncMode {
execMessage()
} else {
go execMessage()
}
}
}
}
// Keep alive subroutine to send ping on specified interval.
// Note that this is the keep-alive implementation of the Websocket protocol, not subscription.
func (sc *SubscriptionContext) startWebsocketKeepAlive(c WebsocketConn, interval time.Duration) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
// Ping the websocket. You might want to handle any potential errors.
err := c.Ping()
if err != nil {
sc.Log("Failed to ping server", "client", GQLInternal)
sc.client.errorChan <- errRestartSubscriptionClient
return
}
case <-sc.Done():
// If the context is cancelled, stop the pinging.
return
}
}
}
// CreateWebSocketConnFunc represents the function interface to create a WebSocket connection.
type CreateWebSocketConnFunc func(ctx context.Context, endpoint string, options WebsocketOptions) (WebsocketConn, error)
type handlerFunc func(data []byte, err error) error
// Subscription stores the subscription declaration and its state
type Subscription struct {
id string
key string
payload GraphQLRequestPayload
handler func(data []byte, err error)
status SubscriptionStatus
}
// GetID returns the subscription ID
func (s Subscription) GetID() string {
return s.id
}
// GetKey returns the unique key of the subscription map
// Key is the immutable id of the subscription that is generated the first time
// It is used for searching because the subscription id is refreshed whenever the client reset
func (s Subscription) GetKey() string {
return s.key
}
// GetPayload returns the graphql request payload
func (s Subscription) GetPayload() GraphQLRequestPayload {
return s.payload
}
// GetHandler a public getter for the subscription handler
func (s Subscription) GetHandler() func(data []byte, err error) {
return s.handler
}
// GetStatus a public getter for the subscription status
func (s Subscription) GetStatus() SubscriptionStatus {
return s.status
}
// SetStatus a public getter for the subscription status
func (s *Subscription) SetStatus(status SubscriptionStatus) {
s.status = status
}
// Clone copies the current subscription with a new state.
// The ID is newly generated to avoid subscription id conflict errors from the server
func (s Subscription) Clone() Subscription {
return Subscription{
id: uuid.NewString(),
key: s.key,
status: SubscriptionWaiting,
payload: s.payload,
handler: s.handler,
}
}
// SubscriptionClient is a GraphQL subscription client.
type SubscriptionClient struct {
url string
currentSession *SubscriptionContext
connectionParams map[string]interface{}
connectionParamsFn func() map[string]interface{}
protocol SubscriptionProtocol
websocketOptions WebsocketOptions
clientStatus int32
createConn CreateWebSocketConnFunc
readLimit int64 // max size of response message. Default 10 MB
retryTimeout time.Duration
connectionInitialisationTimeout time.Duration
websocketConnectionIdleTimeout time.Duration
websocketKeepAliveInterval time.Duration
retryDelay time.Duration
exitWhenNoSubscription bool
syncMode bool
disabledLogTypes []OperationMessageType
log func(args ...interface{})
retryStatusCodes [][]int32
rawSubscriptions map[string]Subscription
// user-defined callback events
onConnected func()
onConnectionAlive func()
onDisconnected func()
onError func(sc *SubscriptionClient, err error) error
onSubscriptionComplete func(sub Subscription)
errorChan chan error
cancel context.CancelFunc
mutex sync.Mutex
}
// NewSubscriptionClient constructs new subscription client
func NewSubscriptionClient(url string) *SubscriptionClient {
protocol := &subscriptionsTransportWS{}
return &SubscriptionClient{
url: url,
readLimit: 10 * 1024 * 1024, // set default limit 10MB
createConn: newWebsocketConn,
retryTimeout: time.Minute,
connectionInitialisationTimeout: time.Minute,
errorChan: make(chan error),
protocol: protocol,
exitWhenNoSubscription: true,
websocketKeepAliveInterval: 0,
retryDelay: 1 * time.Second,
rawSubscriptions: make(map[string]Subscription),
websocketOptions: WebsocketOptions{
Subprotocols: protocol.GetSubprotocols(),
ReadTimeout: time.Minute,
WriteTimeout: time.Minute,
},
}
}
// GetURL returns GraphQL server's URL
func (sc *SubscriptionClient) GetURL() string {
return sc.url
}
// GetTimeout returns write timeout of websocket client.
// Deprecated: use GetWriteTimeout instead.
func (sc *SubscriptionClient) GetTimeout() time.Duration {
return sc.websocketOptions.WriteTimeout
}
// GetWriteTimeout returns write timeout of websocket client.
func (sc *SubscriptionClient) GetWriteTimeout() time.Duration {
return sc.websocketOptions.WriteTimeout
}
// GetReadTimeout returns read timeout of websocket client.
func (sc *SubscriptionClient) GetReadTimeout() time.Duration {
return sc.websocketOptions.ReadTimeout
}
// GetContext returns current context of subscription client.
func (sc *SubscriptionClient) GetContext() context.Context {
currentSession := sc.getCurrentSession()
if currentSession == nil {
return context.Background()
}
return currentSession
}
// GetSubscriptions get the list of active subscriptions
func (sc *SubscriptionClient) GetSubscriptions() map[string]Subscription {
session := sc.getCurrentSession()
if session != nil {
return sc.getCurrentSession().GetSubscriptions()
}
return sc.getRawSubscriptions()
}
// GetSubscription get the subscription state by id
func (sc *SubscriptionClient) GetSubscription(id string) *Subscription {
session := sc.getCurrentSession()
if session != nil {
return sc.getCurrentSession().GetSubscription(id)
}
return sc.getRawSubscription(id)
}
// WithWebSocket replaces customized websocket client constructor
// In default, subscription client uses https://github.com/coder/websocket
func (sc *SubscriptionClient) WithWebSocket(fn CreateWebSocketConnFunc) *SubscriptionClient {
sc.createConn = fn
return sc
}
// WithProtocol changes the subscription protocol implementation by type.
// By default the subscription client uses the subscriptions-transport-ws protocol
func (sc *SubscriptionClient) WithProtocol(protocol SubscriptionProtocolType) *SubscriptionClient {
switch protocol {
case GraphQLWS:
sc.protocol = &graphqlWS{}
case SubscriptionsTransportWS:
sc.protocol = &subscriptionsTransportWS{}
default:
panic(fmt.Sprintf("unknown subscription protocol %s", protocol))
}
sc.websocketOptions.Subprotocols = sc.protocol.GetSubprotocols()
return sc
}
// WithCustomProtocol changes the subscription protocol that implements the SubscriptionProtocol interface.
func (sc *SubscriptionClient) WithCustomProtocol(protocol SubscriptionProtocol) *SubscriptionClient {
sc.protocol = protocol
sc.websocketOptions.Subprotocols = sc.protocol.GetSubprotocols()
return sc
}
// WithWebSocketOptions provides options to the websocket client
func (sc *SubscriptionClient) WithWebSocketOptions(options WebsocketOptions) *SubscriptionClient {
if len(options.Subprotocols) == 0 {
options.Subprotocols = sc.websocketOptions.Subprotocols
}
if options.ReadTimeout == 0 {
options.ReadTimeout = sc.websocketOptions.ReadTimeout
}
if options.WriteTimeout == 0 {
options.WriteTimeout = sc.websocketOptions.WriteTimeout
}
sc.websocketOptions = options
return sc
}
// WithConnectionParams updates connection params for sending to server through GQL_CONNECTION_INIT event
// It's usually used for authentication handshake
func (sc *SubscriptionClient) WithConnectionParams(params map[string]interface{}) *SubscriptionClient {
sc.connectionParams = params
return sc
}
// WithConnectionParamsFn set a function that returns connection params for sending to server through GQL_CONNECTION_INIT event
// It's suitable for short-lived access tokens that need to be refreshed frequently
func (sc *SubscriptionClient) WithConnectionParamsFn(fn func() map[string]interface{}) *SubscriptionClient {
sc.connectionParamsFn = fn
return sc
}
// WithTimeout updates read and write timeout of websocket client.
func (sc *SubscriptionClient) WithTimeout(timeout time.Duration) *SubscriptionClient {
sc.websocketOptions.WriteTimeout = timeout
sc.websocketOptions.ReadTimeout = timeout
return sc
}
// WithReadTimeout updates read timeout of websocket client.
func (sc *SubscriptionClient) WithReadTimeout(timeout time.Duration) *SubscriptionClient {
sc.websocketOptions.ReadTimeout = timeout
return sc
}
// WithWriteTimeout updates write timeout of websocket client.
func (sc *SubscriptionClient) WithWriteTimeout(timeout time.Duration) *SubscriptionClient {
sc.websocketOptions.WriteTimeout = timeout
return sc
}
// WithConnectionInitialisationTimeout updates timeout for the connection initialisation.
func (sc *SubscriptionClient) WithConnectionInitialisationTimeout(timeout time.Duration) *SubscriptionClient {
sc.connectionInitialisationTimeout = timeout
return sc
}
// WithWebsocketConnectionIdleTimeout updates for the websocket connection idle timeout.
func (sc *SubscriptionClient) WithWebsocketConnectionIdleTimeout(timeout time.Duration) *SubscriptionClient {
sc.websocketConnectionIdleTimeout = timeout
return sc
}
// WithRetryTimeout updates reconnecting timeout. When the websocket server was stopped, the client will retry connecting every second until timeout
// The zero value means unlimited timeout
func (sc *SubscriptionClient) WithRetryTimeout(timeout time.Duration) *SubscriptionClient {
sc.retryTimeout = timeout
return sc
}
// WithExitWhenNoSubscription the client should exit when all subscriptions were closed
func (sc *SubscriptionClient) WithExitWhenNoSubscription(value bool) *SubscriptionClient {
sc.exitWhenNoSubscription = value
return sc
}
// WithSyncMode subscription messages are executed in sequence (without goroutine)
func (sc *SubscriptionClient) WithSyncMode(value bool) *SubscriptionClient {
sc.syncMode = value
return sc
}
// WithKeepAlive programs the websocket to ping on the specified interval.
// Deprecated: rename to WithWebSocketKeepAlive to avoid confusing with the keep-alive specification of the subscription protocol.
func (sc *SubscriptionClient) WithKeepAlive(interval time.Duration) *SubscriptionClient {
sc.websocketKeepAliveInterval = interval
return sc
}
// WithWebSocketKeepAlive programs the websocket to ping on the specified interval.
func (sc *SubscriptionClient) WithWebSocketKeepAlive(interval time.Duration) *SubscriptionClient {
sc.websocketKeepAliveInterval = interval
return sc
}
// WithRetryDelay set the delay time before retrying the connection
func (sc *SubscriptionClient) WithRetryDelay(delay time.Duration) *SubscriptionClient {
sc.retryDelay = delay
return sc
}
// WithLog sets logging function to print out received messages. By default, nothing is printed
func (sc *SubscriptionClient) WithLog(logger func(args ...interface{})) *SubscriptionClient {
sc.log = logger
return sc
}
// WithoutLogTypes these operation types won't be printed
func (sc *SubscriptionClient) WithoutLogTypes(types ...OperationMessageType) *SubscriptionClient {
sc.disabledLogTypes = types
return sc
}
// WithReadLimit set max size of response message
func (sc *SubscriptionClient) WithReadLimit(limit int64) *SubscriptionClient {
sc.readLimit = limit
return sc
}
// WithRetryStatusCodes allow retry the subscription connection when receiving one of these codes
// the input parameter can be number string or range, e.g 4000-5000
func (sc *SubscriptionClient) WithRetryStatusCodes(codes ...string) *SubscriptionClient {
statusCodes, err := parseInt32Ranges(codes)
if err != nil {
panic(err)
}
sc.retryStatusCodes = statusCodes
return sc
}
// OnError event is triggered when there is any connection error. This is bottom exception handler level
// If this function is empty, or returns nil, the client restarts the connection
// If returns error, the websocket connection will be terminated
func (sc *SubscriptionClient) OnError(onError func(sc *SubscriptionClient, err error) error) *SubscriptionClient {
sc.onError = onError
return sc
}
// OnConnected event is triggered when the websocket connected to GraphQL server successfully
func (sc *SubscriptionClient) OnConnected(fn func()) *SubscriptionClient {
sc.onConnected = fn
return sc
}
// OnDisconnected event is triggered when the websocket client was disconnected
func (sc *SubscriptionClient) OnDisconnected(fn func()) *SubscriptionClient {
sc.onDisconnected = fn
return sc
}
// OnConnectionAlive event is triggered when the websocket receive a connection alive message (differs per protocol)
func (sc *SubscriptionClient) OnConnectionAlive(fn func()) *SubscriptionClient {
sc.onConnectionAlive = fn
return sc
}
// OnSubscriptionComplete event is triggered when the subscription receives a terminated message from the server
func (sc *SubscriptionClient) OnSubscriptionComplete(fn func(sub Subscription)) *SubscriptionClient {
sc.onSubscriptionComplete = fn
return sc
}
func (sc *SubscriptionClient) getCurrentSession() *SubscriptionContext {
sc.mutex.Lock()
defer sc.mutex.Unlock()
return sc.currentSession
}
func (sc *SubscriptionClient) setCurrentSession(value *SubscriptionContext) {
sc.mutex.Lock()
defer sc.mutex.Unlock()
sc.currentSession = value
}
// get internal client status
func (sc *SubscriptionClient) getClientStatus() int32 {
return atomic.LoadInt32(&sc.clientStatus)
}
// set the running atomic lock status
func (sc *SubscriptionClient) setClientStatus(value int32) {
atomic.StoreInt32(&sc.clientStatus, value)
}
// Subscribe sends start message to server and open a channel to receive data.
// The handler callback function will receive raw message data or error. If the call return error, onError event will be triggered
// The function returns subscription ID and error. You can use subscription ID to unsubscribe the subscription
func (sc *SubscriptionClient) Subscribe(v interface{}, variables map[string]interface{}, handler func(message []byte, err error) error, options ...Option) (string, error) {
return sc.do(v, variables, handler, options...)
}
// NamedSubscribe sends start message to server and open a channel to receive data, with operation name
//
// Deprecated: this is the shortcut of Subscribe method, with NewOperationName option
func (sc *SubscriptionClient) NamedSubscribe(name string, v interface{}, variables map[string]interface{}, handler func(message []byte, err error) error, options ...Option) (string, error) {
return sc.do(v, variables, handler, append(options, OperationName(name))...)
}
// SubscribeRaw sends start message to server and open a channel to receive data, with raw query
// Deprecated: use Exec instead
func (sc *SubscriptionClient) SubscribeRaw(query string, variables map[string]interface{}, handler func(message []byte, err error) error) (string, error) {
return sc.doRaw(query, variables, "", handler)
}
// Exec sends start message to server and open a channel to receive data, with raw query
func (sc *SubscriptionClient) Exec(query string, variables map[string]interface{}, handler func(message []byte, err error) error) (string, error) {
return sc.doRaw(query, variables, "", handler)
}
func (sc *SubscriptionClient) do(v interface{}, variables map[string]interface{}, handler func(message []byte, err error) error, options ...Option) (string, error) {
query, operationName, err := ConstructSubscription(v, variables, options...)
if err != nil {
return "", err
}
return sc.doRaw(query, variables, operationName, handler)
}
func (sc *SubscriptionClient) doRaw(query string, variables map[string]interface{}, operationName string, handler func(message []byte, err error) error) (string, error) {
id := uuid.New().String()
sub := Subscription{
id: id,
key: id,
payload: GraphQLRequestPayload{
Query: query,
Variables: variables,
OperationName: operationName,
},
handler: sc.wrapHandler(handler),
}
sc.mutex.Lock()
sc.rawSubscriptions[id] = sub
currentSession := sc.currentSession
sc.mutex.Unlock()
if currentSession != nil {
currentSession.SetSubscription(id, &sub)
// if the websocket client is running and acknowledged by the server
// start subscription immediately
if sc.getClientStatus() == scStatusRunning && currentSession.GetAcknowledge() {
if err := sc.protocol.Subscribe(currentSession, sub); err != nil {
return id, err
}
}
}
return id, nil
}
func (sc *SubscriptionClient) wrapHandler(fn handlerFunc) func(data []byte, err error) {
return func(data []byte, err error) {
if errValue := fn(data, err); errValue != nil {