forked from wundergraph/graphql-go-tools
-
Notifications
You must be signed in to change notification settings - Fork 4
/
graphql_ws_handler.go
253 lines (232 loc) · 6.41 KB
/
graphql_ws_handler.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
package graphql_datasource
import (
"context"
"encoding/json"
"errors"
"fmt"
"strconv"
"time"
"github.com/buger/jsonparser"
"github.com/jensneuse/abstractlogger"
"nhooyr.io/websocket"
)
// gqlWSConnectionHandler is responsible for handling a connection to an origin
// it is responsible for managing all subscriptions using the underlying WebSocket connection
// if all Subscriptions are complete or cancelled/unsubscribed the handler will terminate
type gqlWSConnectionHandler struct {
conn *websocket.Conn
ctx context.Context
log abstractlogger.Logger
subscribeCh chan Subscription
nextSubscriptionID int
subscriptions map[string]Subscription
readTimeout time.Duration
}
func newGQLWSConnectionHandler(ctx context.Context, conn *websocket.Conn, readTimeout time.Duration, log abstractlogger.Logger) *gqlWSConnectionHandler {
return &gqlWSConnectionHandler{
conn: conn,
ctx: ctx,
log: log,
subscribeCh: make(chan Subscription),
nextSubscriptionID: 0,
subscriptions: map[string]Subscription{},
readTimeout: readTimeout,
}
}
func (h *gqlWSConnectionHandler) SubscribeCH() chan<- Subscription {
return h.subscribeCh
}
// StartBlocking starts the single threaded event loop of the handler
// if the global context returns or the websocket connection is terminated, it will stop
func (h *gqlWSConnectionHandler) StartBlocking(sub Subscription) {
readCtx, cancel := context.WithCancel(h.ctx)
defer func() {
h.unsubscribeAllAndCloseConn()
cancel()
}()
h.subscribe(sub)
dataCh := make(chan []byte)
errCh := make(chan error)
go h.readBlocking(readCtx, dataCh, errCh)
for {
err := h.ctx.Err()
if err != nil {
if !errors.Is(err, context.Canceled) {
h.log.Error("gqlWSConnectionHandler.StartBlocking", abstractlogger.Error(err))
}
h.broadcastErrorMessage(err)
return
}
hasActiveSubscriptions := h.checkActiveSubscriptions()
if !hasActiveSubscriptions {
return
}
select {
case <-time.After(h.readTimeout):
continue
case sub = <-h.subscribeCh:
h.subscribe(sub)
case err = <-errCh:
if !errors.Is(err, context.Canceled) {
h.log.Error("gqlWSConnectionHandler.StartBlocking", abstractlogger.Error(err))
}
h.broadcastErrorMessage(err)
return
case data := <-dataCh:
messageType, err := jsonparser.GetString(data, "type")
if err != nil {
continue
}
switch messageType {
case messageTypeData:
h.handleMessageTypeData(data)
case messageTypeComplete:
h.handleMessageTypeComplete(data)
case messageTypeConnectionError:
h.handleMessageTypeConnectionError()
return
case messageTypeError:
h.handleMessageTypeError(data)
continue
default:
continue
}
}
}
}
// readBlocking is a dedicated loop running in a separate goroutine
// because the library "nhooyr.io/websocket" doesn't allow reading with a context with Timeout
// we'll block forever on reading until the context of the gqlWSConnectionHandler stops
func (h *gqlWSConnectionHandler) readBlocking(ctx context.Context, dataCh chan []byte, errCh chan error) {
for {
msgType, data, err := h.conn.Read(ctx)
if ctx.Err() != nil {
errCh <- ctx.Err()
return
}
if err != nil {
errCh <- err
return
}
if msgType != websocket.MessageText {
continue
}
select {
case dataCh <- data:
case <-ctx.Done():
return
}
}
}
func (h *gqlWSConnectionHandler) unsubscribeAllAndCloseConn() {
for id := range h.subscriptions {
h.unsubscribe(id)
}
_ = h.conn.Close(websocket.StatusNormalClosure, "")
}
// subscribe adds a new Subscription to the gqlWSConnectionHandler and sends the startMessage to the origin
func (h *gqlWSConnectionHandler) subscribe(sub Subscription) {
graphQLBody, err := json.Marshal(sub.options.Body)
if err != nil {
return
}
h.nextSubscriptionID++
subscriptionID := strconv.Itoa(h.nextSubscriptionID)
startRequest := fmt.Sprintf(startMessage, subscriptionID, string(graphQLBody))
err = h.conn.Write(h.ctx, websocket.MessageText, []byte(startRequest))
if err != nil {
return
}
h.subscriptions[subscriptionID] = sub
}
func (h *gqlWSConnectionHandler) handleMessageTypeData(data []byte) {
id, err := jsonparser.GetString(data, "id")
if err != nil {
return
}
sub, ok := h.subscriptions[id]
if !ok {
return
}
payload, _, _, err := jsonparser.Get(data, "payload")
if err != nil {
return
}
sub.updater.Update(payload)
}
func (h *gqlWSConnectionHandler) handleMessageTypeConnectionError() {
for _, sub := range h.subscriptions {
sub.updater.Update([]byte(connectionError))
}
}
func (h *gqlWSConnectionHandler) broadcastErrorMessage(err error) {
errMsg := fmt.Sprintf(errorMessageTemplate, err)
for _, sub := range h.subscriptions {
sub.updater.Update([]byte(errMsg))
}
}
func (h *gqlWSConnectionHandler) handleMessageTypeComplete(data []byte) {
id, err := jsonparser.GetString(data, "id")
if err != nil {
return
}
sub, ok := h.subscriptions[id]
if !ok {
return
}
sub.updater.Done()
delete(h.subscriptions, id)
}
func (h *gqlWSConnectionHandler) handleMessageTypeError(data []byte) {
id, err := jsonparser.GetString(data, "id")
if err != nil {
return
}
sub, ok := h.subscriptions[id]
if !ok {
return
}
value, valueType, _, err := jsonparser.Get(data, "payload")
if err != nil {
sub.updater.Update([]byte(internalError))
return
}
switch valueType {
case jsonparser.Array:
response := []byte(`{}`)
response, err = jsonparser.Set(response, value, "errors")
if err != nil {
sub.updater.Update([]byte(internalError))
return
}
sub.updater.Update(response)
case jsonparser.Object:
response := []byte(`{"errors":[]}`)
response, err = jsonparser.Set(response, value, "errors", "[0]")
if err != nil {
sub.updater.Update([]byte(internalError))
return
}
sub.updater.Update(response)
default:
sub.updater.Update([]byte(internalError))
}
}
func (h *gqlWSConnectionHandler) unsubscribe(subscriptionID string) {
sub, ok := h.subscriptions[subscriptionID]
if !ok {
return
}
sub.updater.Done()
delete(h.subscriptions, subscriptionID)
stopRequest := fmt.Sprintf(stopMessage, subscriptionID)
_ = h.conn.Write(h.ctx, websocket.MessageText, []byte(stopRequest))
}
func (h *gqlWSConnectionHandler) checkActiveSubscriptions() (hasActiveSubscriptions bool) {
for id, sub := range h.subscriptions {
if sub.ctx.Err() != nil {
h.unsubscribe(id)
}
}
return len(h.subscriptions) != 0
}