-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.go
242 lines (208 loc) · 5.18 KB
/
server.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
package gws
import (
"context"
"errors"
"net/http"
"time"
"nhooyr.io/websocket"
)
// ErrStreamClosed is returned by Send if the stream
// is closed before Send is called.
//
var ErrStreamClosed = errors.New("gws: stream is closed")
// Handler is for handling incoming GraphQL queries. All other
// "GraphQL over Websocket" protocol messages are automatically
// handled internally.
//
// All resolvers errors should be included in *Response and
// any validation error should be returned as error.
//
type Handler interface {
ServeGraphQL(*Stream, *Request) error
}
// HandlerFunc is an adapter to allow the use of ordinary functions as Request handlers.
type HandlerFunc func(*Stream, *Request) error
// ServeGraphQL implements the Handler interface.
func (f HandlerFunc) ServeGraphQL(s *Stream, req *Request) error {
return f(s, req)
}
// Stream is used for streaming responses back to the client.
type Stream struct {
conn *Conn
id opID
done chan struct{}
}
// Send sends a response to the client. It is safe for concurrent use.
func (s *Stream) Send(ctx context.Context, resp *Response) error {
select {
case <-s.done:
return ErrStreamClosed
default:
}
err := s.conn.write(ctx, operationMessage{ID: s.id, Type: gqlData, Payload: resp})
return err
}
// Close notifies the client that no more results will be sent
// and closes the stream. It also frees any resources associated
// with the stream, thus meaning Close should always be called to
// prevent any leaks.
//
func (s *Stream) Close() error {
select {
case <-s.done:
return ErrStreamClosed
default:
}
close(s.done)
return s.conn.write(context.TODO(), operationMessage{ID: s.id, Type: gqlComplete})
}
type options struct {
origins []string
mode CompressionMode
threshold int
typ MessageType
keepAlive bool
period time.Duration
}
// ServerOption allows the user to configure the handler.
type ServerOption interface {
SetServer(*options)
}
type soptFn func(*options)
func (f soptFn) SetServer(opts *options) { f(opts) }
// WithOrigins lists the host patterns for authorized origins.
// The request host is always authorized. Use this to allow
// cross origin WebSockets.
//
func WithOrigins(origins ...string) ServerOption {
return soptFn(func(opts *options) {
opts.origins = origins
})
}
// WithKeepAlive configures the server to send a GQL_CONNECTION_ACK
// message periodically to keep the client connection alive.
//
func WithKeepAlive(period time.Duration) ServerOption {
return soptFn(func(opts *options) {
opts.keepAlive = true
opts.period = period
})
}
type handler struct {
Handler
wcOptions *websocket.AcceptOptions
mtyp MessageType
keepAlive bool
period time.Duration
}
// NewHandler configures an http.Handler, which will upgrade
// incoming connections to WebSocket and serve the "graphql-ws" subprotocol.
//
func NewHandler(h Handler, opts ...ServerOption) http.Handler {
sopts := &options{
typ: MessageBinary,
}
for _, opt := range opts {
opt.SetServer(sopts)
}
return &handler{
Handler: h,
keepAlive: sopts.keepAlive,
period: sopts.period,
mtyp: sopts.typ,
wcOptions: &websocket.AcceptOptions{
Subprotocols: []string{"graphql-ws"},
OriginPatterns: sopts.origins,
CompressionMode: websocket.CompressionMode(sopts.mode),
CompressionThreshold: sopts.threshold,
},
}
}
func (h *handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
wc, err := websocket.Accept(w, req, h.wcOptions)
if err != nil {
// TODO: Handle error
return
}
conn := newConn(wc, h.mtyp)
ctx, cancel := context.WithCancel(req.Context())
defer cancel()
defer wc.CloseRead(ctx)
streams := make(map[opID]*Stream)
defer func() {
for _, s := range streams {
s.Close()
}
}()
// Handle messages
msg := new(operationMessage)
for {
b, err := conn.read(ctx)
if err != nil {
// TODO
return
}
err = msg.UnmarshalJSON(b)
if err != nil {
conn.write(ctx, operationMessage{
Type: gqlError,
Payload: &ServerError{Msg: "received malformed message"},
})
continue
}
switch msg.Type {
case gqlConnectionInit:
// TODO(zaba505): handle these errors errors
conn.write(ctx, operationMessage{Type: gqlConnectionAck})
if !h.keepAlive {
break
}
conn.write(ctx, operationMessage{Type: gqlConnectionKeepAlive})
go func() {
for {
timer := time.NewTimer(h.period)
select {
case <-timer.C:
conn.write(ctx, operationMessage{Type: gqlConnectionKeepAlive})
case <-ctx.Done():
timer.Stop()
return
}
}
}()
break
case gqlStart:
s := &Stream{
id: msg.ID,
conn: conn,
done: make(chan struct{}, 1),
}
streams[msg.ID] = s
go handleRequest(s, h, msg.ID, msg.Payload.(*Request))
break
case gqlStop:
s, ok := streams[msg.ID]
if !ok {
break
}
delete(streams, msg.ID)
s.Close()
case gqlConnectionTerminate:
return
default:
// TODO: Handle
break
}
}
}
func handleRequest(s *Stream, h Handler, id opID, req *Request) {
err := h.ServeGraphQL(s, req)
if err != nil {
s.conn.write(context.TODO(), operationMessage{
ID: id,
Type: gqlError,
Payload: &ServerError{Msg: err.Error()},
})
return
}
}