-
-
Notifications
You must be signed in to change notification settings - Fork 178
/
ws.go
246 lines (205 loc) · 5.01 KB
/
ws.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
package serv
import (
"bytes"
"context"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/dosco/graphjin/core"
"github.com/dosco/graphjin/serv/internal/auth"
ws "github.com/gorilla/websocket"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
type gqlWsReq struct {
ID string `json:"id"`
Type string `json:"type"`
Payload gqlReq `json:"payload"`
}
type gqlWsResp struct {
ID string `json:"id"`
Type string `json:"type"`
Payload struct {
Data json.RawMessage `json:"data,omitempty"`
Errors []core.Error `json:"errors,omitempty"`
} `json:"payload"`
}
type wsConnInit struct {
Type string `json:"type,omitempty"`
Payload map[string]interface{} `json:"payload,omitempty"`
}
var upgrader = ws.Upgrader{
EnableCompression: true,
ReadBufferSize: 1024,
WriteBufferSize: 1024,
HandshakeTimeout: 10 * time.Second,
Subprotocols: []string{"graphql-ws", "graphql-transport-ws"},
CheckOrigin: func(r *http.Request) bool { return true },
}
var initMsg *ws.PreparedMessage
func init() {
msg, err := json.Marshal(gqlWsReq{ID: "1", Type: "connection_ack"})
if err != nil {
panic(err)
}
initMsg, err = ws.NewPreparedMessage(ws.TextMessage, msg)
if err != nil {
panic(err)
}
}
func (s *Service) apiV1Ws(w http.ResponseWriter, r *http.Request) {
var m *core.Member
var run bool
ctx := r.Context()
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
renderErr(w, err)
return
}
defer conn.Close()
conn.SetReadLimit(2048)
var msg gqlWsReq
var b []byte
done := make(chan bool)
for {
if _, b, err = conn.ReadMessage(); err != nil {
s.zlog.Error("Websockets", []zapcore.Field{zap.Error(err)}...)
break
}
if err = json.Unmarshal(b, &msg); err != nil {
s.zlog.Error("Websockets", []zapcore.Field{zap.Error(err)}...)
continue
}
switch msg.Type {
case "connection_init":
var initReq wsConnInit
d := json.NewDecoder(bytes.NewReader(b))
d.UseNumber()
if err = d.Decode(&initReq); err != nil {
s.zlog.Error("Websockets", []zapcore.Field{zap.Error(err)}...)
break
}
hfn := func(writer http.ResponseWriter, request *http.Request) {
ctx = request.Context()
err = conn.WritePreparedMessage(initMsg)
}
handler, _ := auth.WithAuth(http.HandlerFunc(hfn), &s.conf.Auth)
if err != nil {
break
}
for k, v := range initReq.Payload {
switch v1 := v.(type) {
case string:
r.Header.Set(k, v1)
case json.Number:
r.Header.Set(k, v1.String())
}
}
handler.ServeHTTP(w, r)
case "start", "subscribe":
if run {
continue
}
if s.conf.Serv.Auth.SubsCredsInVars {
type authHeaders struct {
UserIDProvider string `json:"X-User-ID-Provider"`
UserRole string `json:"X-User-Role"`
UserID interface{} `json:"X-User-ID"`
}
var x authHeaders
if err = json.Unmarshal(msg.Payload.Vars, &x); err == nil {
if x.UserIDProvider != "" {
ctx = context.WithValue(ctx, core.UserIDProviderKey, x.UserIDProvider)
}
if x.UserRole != "" {
ctx = context.WithValue(ctx, core.UserRoleKey, x.UserRole)
}
if x.UserID != nil {
ctx = context.WithValue(ctx, core.UserIDKey, x.UserID)
}
}
}
m, err = s.gj.Subscribe(ctx, msg.Payload.Query, msg.Payload.Vars, nil)
if err == nil {
go s.waitForData(done, conn, m, msg)
run = true
}
case "stop":
m.Unsubscribe()
done <- true
run = false
case "connection_terminate":
m.Unsubscribe()
done <- true
return
default:
fields := []zapcore.Field{
zap.String("msg_type", msg.Type),
zap.Error(errors.New("unknown message type")),
}
s.zlog.Error("Subscription Error", fields...)
}
if err != nil {
err = sendError(conn, err, msg.ID)
break
}
}
if err != nil {
s.zlog.Error("Subscription Error", []zapcore.Field{zap.Error(err)}...)
}
m.Unsubscribe()
done <- true
}
func (s *Service) waitForData(done chan bool, conn *ws.Conn, m *core.Member, req gqlWsReq) {
var buf bytes.Buffer
var ptype string
var err error
if req.Type == "subscribe" {
ptype = "next"
} else {
ptype = "data"
}
enc := json.NewEncoder(&buf)
for {
select {
case v := <-m.Result:
res := gqlWsResp{ID: req.ID, Type: ptype}
res.Payload.Data = v.Data
if len(v.Errors) != 0 {
res.Payload.Errors = v.Errors
}
if err = enc.Encode(res); err != nil {
continue
}
msg := buf.Bytes()
buf.Reset()
if err = conn.WriteMessage(ws.TextMessage, msg); err != nil {
continue
}
case v := <-done:
if v {
return
}
}
if err != nil {
err = sendError(conn, err, req.ID)
break
}
}
if err != nil && isDev() {
s.zlog.Error("Websockets", []zapcore.Field{zap.Error(err)}...)
}
}
func sendError(conn *ws.Conn, err error, id string) error {
res := gqlWsResp{ID: id, Type: "error"}
res.Payload.Errors = []core.Error{{Message: err.Error()}}
msg, err := json.Marshal(res)
if err != nil {
return err
}
if err := conn.WriteMessage(ws.TextMessage, msg); err != nil {
return err
}
return nil
}