-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathwebsocket.go
494 lines (423 loc) · 12.4 KB
/
websocket.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
package fir
import (
"bytes"
"context"
"fmt"
"net/http"
"strings"
"time"
"github.com/goccy/go-json"
"github.com/gorilla/websocket"
"github.com/livefir/fir/internal/dom"
"github.com/livefir/fir/internal/logger"
"github.com/livefir/fir/pubsub"
"github.com/minio/sha256-simd"
)
const (
// Time allowed to write a message to the peer.
writeWait = 20 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 55 * time.Second
// Send pings to peer with this period. Must be less than pongWait.
pingPeriod = (pongWait * 9) / 10
// Maximum message size allowed from peer.
maxMessageSize = 1024
EventSocketConnected = "fir_socket_connected"
EventSocketDisconnected = "fir_socket_disconnected"
)
type SocketStatus struct {
Connected bool
User string
}
// RedirectUnauthorisedWebSocket sends a 4001 close message to the client
// It sends the redirect url in the close message payload
// If the request is not a websocket request or has error upgrading and writing the close message, it returns false
// redirect url must be less than 123 bytes
func RedirectUnauthorisedWebSocket(w http.ResponseWriter, r *http.Request, redirect string) bool {
if len(redirect) > 123 {
panic("redirect url is too long: max size 123 bytes")
}
if !websocket.IsWebSocketUpgrade(r) {
return false
}
upgrader := websocket.Upgrader{}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
logger.Errorf("upgrade err: %v", err)
return false
}
err = conn.WriteControl(
websocket.CloseMessage,
websocket.FormatCloseMessage(4001, redirect), time.Now().Add(writeWait))
if err != nil {
logger.Errorf("write control err: %v", err)
return false
}
defer conn.Close()
return true
}
func onWebsocket(w http.ResponseWriter, r *http.Request, cntrl *controller) {
cookie, err := r.Cookie(cntrl.cookieName)
if err != nil {
logger.Errorf("cookie err: %v", err)
RedirectUnauthorisedWebSocket(w, r, "/")
return
}
if cookie.Value == "" {
logger.Errorf("cookie err: empty")
RedirectUnauthorisedWebSocket(w, r, "/")
return
}
sessionID, routeID, err := decodeSession(*cntrl.secureCookie, cntrl.cookieName, cookie.Value)
if err != nil {
logger.Errorf("decode session err: %v", err)
RedirectUnauthorisedWebSocket(w, r, "/")
return
}
if sessionID == "" {
logger.Errorf("err: sessionID is empty, routeID is: %s", routeID)
RedirectUnauthorisedWebSocket(w, r, "/")
return
}
if routeID == "" {
logger.Errorf("routeID: is empty")
RedirectUnauthorisedWebSocket(w, r, "/")
return
}
user := getUserFromRequestContext(r)
connectedUser := user
if user == "" {
connectedUser = sessionID
}
if cntrl.onSocketConnect != nil {
err := cntrl.onSocketConnect(connectedUser)
if err != nil {
return
}
}
if cntrl.onSocketDisconnect != nil {
defer cntrl.onSocketDisconnect(connectedUser)
}
send := make(chan []byte, 100)
ctx := context.Background()
for _, route := range cntrl.routes {
routeChannel := route.channelFunc(r, route.id)
if routeChannel == nil {
logger.Errorf("error: channel is empty")
http.Error(w, "channel is empty", http.StatusUnauthorized)
return
}
// subscribers: subscribe to pubsub events
subscription, err := route.pubsub.Subscribe(ctx, *routeChannel)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer subscription.Close()
go func() {
for pubsubEvent := range subscription.C() {
routeCtx := RouteContext{
request: r,
response: w,
route: route,
}
go renderAndWriteEventWS(send, *routeChannel, routeCtx, pubsubEvent)
}
}()
// eventSenders: handle server events
go func() {
for event := range route.eventSender {
eventCtx := RouteContext{
event: event,
request: r,
response: w,
route: route,
}
withEventLogger := logger.Logger().
With(
"route_id", route.id,
"event_id", event.ID,
"session_id", sessionID,
)
withEventLogger.Info("received server event")
onEventFunc, ok := route.onEvents[strings.ToLower(event.ID)]
if !ok {
logger.Errorf("err: event %v, event.id not found", event)
continue
}
// update request context with user
eventCtx.request = eventCtx.request.WithContext(context.WithValue(context.Background(), UserKey, user))
channel := *route.channelFunc(eventCtx.request, route.id)
errorEvent := handleOnEventResult(onEventFunc(eventCtx), eventCtx, publishEvents(ctx, eventCtx, channel))
if errorEvent != nil {
renderAndWriteEventWS(send, channel, eventCtx, *errorEvent)
}
}
}()
if route.developmentMode {
// subscriber for reload operations in development mode. see watch.go
reloadSubscriber, err := route.pubsub.Subscribe(ctx, devReloadChannel)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer reloadSubscriber.Close()
go func() {
for pubsubEvent := range reloadSubscriber.C() {
go writeEvent(send, pubsubEvent)
}
}()
}
}
conn, err := cntrl.websocketUpgrader.Upgrade(w, r, nil)
if err != nil {
logger.Errorf("upgrade err: %v", err)
return
}
conn.SetReadLimit(maxMessageSize)
// disabled compression since its too noisy: https://github.com/gorilla/websocket/issues/859
//conn.EnableWriteCompression(true)
//conn.SetCompressionLevel(4)
conn.SetReadDeadline(time.Now().Add(pongWait))
conn.SetPongHandler(func(string) error {
//logger.Infof("pong from %v", conn.RemoteAddr())
conn.SetReadDeadline(time.Now().Add(pongWait))
return nil
})
// workaround for noisy logs due to close handler printing a useless error
// https://github.com/gorilla/websocket/issues/880
conn.SetCloseHandler(func(code int, text string) error {
message := websocket.FormatCloseMessage(code, "")
conn.WriteControl(websocket.CloseMessage, message, time.Now().Add(writeWait))
return nil
})
for _, route := range cntrl.routes {
if route.onEvents[EventSocketConnected] == nil {
continue
}
connectedParams := SocketStatus{
Connected: true,
User: connectedUser,
}
paramBytes, err := json.Marshal(connectedParams)
if err != nil {
logger.Errorf("error: marshaling connectedParams %+v, err %v", connectedParams, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
connectedEvent := Event{
ID: EventSocketConnected,
SessionID: &sessionID,
Params: paramBytes,
Timestamp: time.Now().UTC().UnixMilli(),
}
go func(ev Event) {
for {
select {
case route.eventSender <- ev:
return
default:
time.Sleep(10 * time.Millisecond)
}
}
}(connectedEvent)
}
writePumpDone := make(chan struct{})
go writePump(conn, writePumpDone, send)
sid := ""
lastEvent := Event{
SessionID: &sid,
}
loop:
for {
_, message, err := conn.ReadMessage()
if err != nil {
if !websocket.IsCloseError(err, websocket.CloseNormalClosure) && websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway) {
logger.Errorf("read: %v, %v", conn.RemoteAddr().String(), err)
}
break loop
}
// start := time.Now()
var event Event
err = json.NewDecoder(bytes.NewReader(message)).Decode(&event)
if err != nil {
logger.Errorf("err: %v, parsing event, msg %s ", err, string(message))
continue
}
if event.ID == "" {
logger.Errorf("err: event %v, field event.id is required", event)
continue
}
// logger.Infof("received event: %+v took %v ", event, time.Since(start))
if event.ID == "heartbeat" && conn != nil {
// err := conn.WriteMessage(websocket.TextMessage, []byte(`{"event_id":"heartbeat_ack"}`))
// if err != nil {
// logger.Errorf("write heartbeat err: %v, ", err)
// break loop
// }
go func() {
send <- []byte(`{"event_id":"heartbeat_ack"}`)
}()
// logger.Errorf("wrote heartbeat: %+v took %v ", event, time.Since(start))
continue
}
if event.SessionID == nil {
logger.Errorf("err: event %v, field session.ID is required, closing connection", event)
break loop
}
if lastEvent.ID == event.ID && *lastEvent.SessionID == *event.SessionID && lastEvent.ElementKey == event.ElementKey {
lastEventTime := toUnixTime(lastEvent.Timestamp)
eventTime := toUnixTime(event.Timestamp)
if lastEventTime.Add(cntrl.dropDuplicateInterval).After(eventTime) {
if eqBytesHash(lastEvent.Params, event.Params) {
logger.Errorf("err: dropped duplicate event in last 250ms, event %v ", event)
continue
}
}
}
lastEvent = event
eventSessionID, eventRouteID, err := decodeSession(*cntrl.secureCookie, cntrl.cookieName, *event.SessionID)
if err != nil {
logger.Errorf("err: %v, decoding session, closing connection", err)
break loop
}
if eventSessionID != sessionID || eventRouteID != routeID {
logger.Errorf("err: event %v, unauthorised session", event)
break loop
}
eventRoute := cntrl.routes[eventRouteID]
eventCtx := RouteContext{
event: event,
request: r,
response: w,
route: eventRoute,
}
withEventLogger := logger.Logger().
With(
"route_id", eventRoute.id,
"event_id", event.ID,
"session_id", eventSessionID,
"element_key", event.ElementKey,
)
withEventLogger.Debug("received user event")
onEventFunc, ok := eventRoute.onEvents[strings.ToLower(event.ID)]
if !ok {
logger.Errorf("err: event %v, event.id not found", event)
continue
}
go func() {
channel := *eventRoute.channelFunc(eventCtx.request, eventRoute.id)
// errors are only sent to current local connection and not published
errorEvent := handleOnEventResult(onEventFunc(eventCtx), eventCtx, publishEvents(ctx, eventCtx, channel))
if errorEvent != nil {
renderAndWriteEventWS(send, channel, eventCtx, *errorEvent)
}
}()
}
close(writePumpDone)
conn.Close()
for _, route := range cntrl.routes {
if route.onEvents[EventSocketDisconnected] == nil {
continue
}
connectedParams := SocketStatus{
Connected: false,
User: connectedUser,
}
paramBytes, err := json.Marshal(connectedParams)
if err != nil {
logger.Errorf("error: marshaling connectedParams %+v, err %v", connectedParams, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
route.eventSender <- Event{
ID: EventSocketDisconnected,
SessionID: &sessionID,
Params: paramBytes,
Timestamp: time.Now().UTC().UnixMilli(),
}
}
}
func renderAndWriteEventWS(send chan []byte, channel string, ctx RouteContext, pubsubEvent pubsub.Event) error {
events := renderDOMEvents(ctx, pubsubEvent)
eventsData, err := json.Marshal(events)
if err != nil {
logger.Errorf("error: marshaling events %+v, err %v", events, err)
return err
}
if len(eventsData) == 0 {
err := fmt.Errorf("error: message is empty, channel %s, events %+v", channel, pubsubEvent)
logger.Errorf("%v", err)
return err
}
send <- eventsData
return err
}
func writeEvent(send chan []byte, pubsubEvent pubsub.Event) error {
domEvent := dom.Event{
Type: pubsubEvent.ID,
}
eventsData, err := json.Marshal([]dom.Event{domEvent})
if err != nil {
logger.Errorf("error: marshaling dom event %+v, err %v", domEvent, err)
return err
}
send <- eventsData
return err
}
func writeConn(conn *websocket.Conn, mt int, payload []byte) error {
return conn.WriteMessage(mt, payload)
}
func writePump(conn *websocket.Conn, closeWritePump chan struct{}, send chan []byte) {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
conn.Close()
}()
loop:
for {
select {
case message, ok := <-send:
conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
err := writeConn(conn, websocket.CloseMessage, []byte{})
if err != nil {
logger.Errorf("write close err: %v", err)
}
return
}
w, err := conn.NextWriter(websocket.TextMessage)
if err != nil {
logger.Errorf("next writer err: %v", err)
return
}
_, err = w.Write(message)
if err != nil {
logger.Errorf("write err: %v", err)
return
}
if err := w.Close(); err != nil {
logger.Errorf("close err: %v", err)
return
}
case <-closeWritePump:
break loop
case <-ticker.C:
//logger.Infof("ping to client: %v", conn.RemoteAddr())
conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := writeConn(conn, websocket.PingMessage, []byte{}); err != nil {
logger.Errorf("ping err: %v", err)
return
}
}
}
}
func eqBytesHash(a, b []byte) bool {
w := sha256.New()
w.Write(a)
aHash := w.Sum(nil)
w.Reset()
w.Write(b)
bHash := w.Sum(nil)
return bytes.Equal(aHash, bHash)
}