/
socket.go
221 lines (188 loc) Β· 4.61 KB
/
socket.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
package api
import (
"context"
"encoding/json"
"io"
"net/http"
"strings"
"sync"
"time"
"github.com/asim/turbo/event"
"github.com/asim/turbo/log"
"github.com/gorilla/websocket"
)
const (
// Time allowed to write a message to the client.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the client.
pongWait = 60 * time.Second
// Send pings to client with this period. Must be less than pongWait.
pingPeriod = 15 * time.Second
// Maximum message size allowed from client.
maxMessageSize = 512
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
// check if the request is for websockets
func isWebSocket(r *http.Request) bool {
contains := func(key, val string) bool {
vv := strings.Split(r.Header.Get(key), ",")
for _, v := range vv {
if val == strings.ToLower(strings.TrimSpace(v)) {
return true
}
}
return false
}
if contains("Connection", "upgrade") && contains("Upgrade", "websocket") {
return true
}
return false
}
// serve an actual websocket
func serveWebSocket(w http.ResponseWriter, r *http.Request, sub *event.Subscriber) {
var rspHdr http.Header
// we use Sec-Websocket-Protocol to pass auth headers so just accept anything here
if prots := r.Header.Values("Sec-WebSocket-Protocol"); len(prots) > 0 {
rspHdr = http.Header{}
for _, p := range prots {
rspHdr.Add("Sec-WebSocket-Protocol", p)
}
}
// upgrade the connection
conn, err := upgrader.Upgrade(w, r, rspHdr)
if err != nil {
http.Error(w, err.Error(), 500)
return
}
// assume text types
msgType := websocket.TextMessage
// create a stream
s := stream{
ctx: r.Context(),
conn: conn,
sub: sub,
messageType: msgType,
}
// start processing the stream
s.run()
}
type stream struct {
// message type requested (binary or text)
messageType int
// request context
ctx context.Context
// the websocket connection.
conn *websocket.Conn
// the downstream connection.
sub *event.Subscriber
}
func (s *stream) run() {
defer func() {
s.conn.Close()
}()
// for our messages from sub
msgs := make(chan interface{}, 100)
// to cancel everything
stopCtx, cancel := context.WithCancel(context.Background())
// wait for things to exist
wg := sync.WaitGroup{}
wg.Add(3)
// establish the loops
go s.rspToBufLoop(cancel, &wg, stopCtx, msgs)
go s.bufToClientLoop(cancel, &wg, stopCtx, msgs)
go s.clientToServerLoop(cancel, &wg, stopCtx)
wg.Wait()
}
func (s *stream) clientToServerLoop(cancel context.CancelFunc, wg *sync.WaitGroup, stopCtx context.Context) {
defer func() {
s.sub.Close()
cancel()
wg.Done()
}()
s.conn.SetReadLimit(maxMessageSize)
s.conn.SetReadDeadline(time.Now().Add(pongWait))
s.conn.SetPongHandler(func(string) error { s.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
select {
case <-stopCtx.Done():
return
default:
}
_, msg, err := s.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
log.Print(err)
}
return
}
// TODO: pass on client to server messages
log.Print("Got msg", msg)
}
}
func (s *stream) rspToBufLoop(cancel context.CancelFunc, wg *sync.WaitGroup, stopCtx context.Context, msgs chan interface{}) {
defer func() {
cancel()
wg.Done()
}()
for {
var msg json.RawMessage
if err := s.sub.Next(stopCtx, &msg); err == io.EOF {
return
} else if err != nil {
b, _ := json.Marshal(err)
s.conn.WriteMessage(s.messageType, b)
s.conn.WriteMessage(websocket.CloseAbnormalClosure, []byte{})
return
}
select {
case msgs <- &msg:
case <-stopCtx.Done():
default:
}
}
}
func (s *stream) bufToClientLoop(cancel context.CancelFunc, wg *sync.WaitGroup, stopCtx context.Context, msgs chan interface{}) {
defer func() {
s.conn.Close()
cancel()
wg.Done()
}()
ticker := time.NewTicker(pingPeriod)
defer ticker.Stop()
for {
select {
case <-stopCtx.Done():
return
case <-s.ctx.Done():
return
case <-s.sub.Exit:
s.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
case <-ticker.C:
s.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := s.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
case msg := <-msgs:
// read response body
s.conn.SetWriteDeadline(time.Now().Add(writeWait))
w, err := s.conn.NextWriter(s.messageType)
if err != nil {
return
}
b, _ := json.Marshal(msg)
if _, err := w.Write(b); err != nil {
return
}
if err := w.Close(); err != nil {
return
}
}
}
}