forked from perkeep/perkeep
/
websocket.go
286 lines (257 loc) · 6.97 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
/*
Copyright 2013 The Camlistore Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package search
import (
"bytes"
"encoding/json"
"log"
"net/http"
"sync"
"time"
"camlistore.org/third_party/github.com/gorilla/websocket"
)
const (
// Time allowed to write a message to the peer.
writeWait = 10 * time.Second
// Time allowed to read the next pong message from the peer.
pongWait = 60 * 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 = 10 << 10
)
type wsHub struct {
sh *Handler
register chan *wsConn
unregister chan *wsConn
watchReq chan watchReq
newBlobRecv chan string // new blob received. string is camliType.
updatedResults chan *watchedQuery
statusUpdate chan json.RawMessage
// Owned by func run:
conns map[*wsConn]bool
}
func newWebsocketHub(sh *Handler) *wsHub {
return &wsHub{
sh: sh,
register: make(chan *wsConn, buffered),
unregister: make(chan *wsConn, buffered),
conns: make(map[*wsConn]bool),
watchReq: make(chan watchReq, buffered),
newBlobRecv: make(chan string, buffered),
updatedResults: make(chan *watchedQuery, buffered),
statusUpdate: make(chan json.RawMessage, buffered),
}
}
func (h *wsHub) run() {
var lastStatusMsg []byte
for {
select {
case st := <-h.statusUpdate:
const prefix = `{"tag":"_status","status":`
lastStatusMsg = make([]byte, 0, len(prefix)+len(st)+1)
lastStatusMsg = append(lastStatusMsg, prefix...)
lastStatusMsg = append(lastStatusMsg, st...)
lastStatusMsg = append(lastStatusMsg, '}')
for c := range h.conns {
c.send <- lastStatusMsg
}
case c := <-h.register:
h.conns[c] = true
c.send <- lastStatusMsg
case c := <-h.unregister:
delete(h.conns, c)
close(c.send)
case camliType := <-h.newBlobRecv:
if camliType == "" {
// TODO: something smarter. some
// queries might care about all blobs.
// But for now only re-kick off
// queries if schema blobs arrive. We
// should track per-WatchdQuery which
// blob types the search cares about.
continue
}
// New blob was received. Kick off standing search queries to see if any changed.
for conn := range h.conns {
for _, wq := range conn.queries {
go h.doSearch(wq)
}
}
case wr := <-h.watchReq:
// Unsubscribe
if wr.q == nil {
delete(wr.conn.queries, wr.tag)
log.Printf("Removed subscription for %v, %q", wr.conn, wr.tag)
continue
}
// Very similar type, but semantically
// different, so separate for now:
wq := &watchedQuery{
conn: wr.conn,
tag: wr.tag,
q: wr.q,
}
wr.conn.queries[wr.tag] = wq
log.Printf("Added/updated search subscription for tag %q", wr.tag)
go h.doSearch(wq)
case wq := <-h.updatedResults:
if !h.conns[wq.conn] || wq.conn.queries[wq.tag] == nil {
// Client has since disconnected or unsubscribed.
continue
}
wq.mu.Lock()
lastres := wq.lastres
wq.mu.Unlock()
resb, err := json.Marshal(wsUpdateMessage{
Tag: wq.tag,
Result: lastres,
})
if err != nil {
panic(err)
}
wq.conn.send <- resb
}
}
}
func (h *wsHub) doSearch(wq *watchedQuery) {
// Make our own copy, in case
q := new(SearchQuery)
*q = *wq.q // shallow copy, since Query will mutate its internal state fields
if q.Describe != nil {
q.Describe = new(DescribeRequest)
*q.Describe = *wq.q.Describe
}
res, err := h.sh.Query(q)
if err != nil {
log.Printf("Query error: %v", err)
return
}
resj, _ := json.Marshal(res)
wq.mu.Lock()
eq := bytes.Equal(wq.lastresj, resj)
wq.lastres = res
wq.lastresj = resj
wq.mu.Unlock()
if eq {
// No change in search. Ignore.
return
}
h.updatedResults <- wq
}
type wsConn struct {
ws *websocket.Conn
send chan []byte // Buffered channel of outbound messages.
sh *Handler
queries map[string]*watchedQuery // tag -> subscription
}
type watchedQuery struct {
conn *wsConn
tag string
q *SearchQuery
mu sync.Mutex // guards lastRes
lastres *SearchResult
lastresj []byte // as JSON
}
// watchReq is a (un)subscribe request.
type watchReq struct {
conn *wsConn
tag string // required
q *SearchQuery // if nil, subscribe
}
// Client->Server subscription message.
type wsClientMessage struct {
// Tag is required.
Tag string `json:"tag"`
// Query is required to subscribe. If absent, it means unsubscribe.
Query *SearchQuery `json:"query,omitempty"`
}
type wsUpdateMessage struct {
Tag string `json:"tag"`
Result *SearchResult `json:"result,omitempty"`
}
// readPump pumps messages from the websocket connection to the hub.
func (c *wsConn) readPump() {
defer func() {
c.sh.wsHub.unregister <- c
c.ws.Close()
}()
c.ws.SetReadLimit(maxMessageSize)
c.ws.SetReadDeadline(time.Now().Add(pongWait))
c.ws.SetPongHandler(func(string) error { c.ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
_, message, err := c.ws.ReadMessage()
if err != nil {
break
}
log.Printf("Got websocket message %#q", message)
cm := new(wsClientMessage)
if err := json.Unmarshal(message, cm); err != nil {
log.Printf("Ignoring bogus websocket message. Err: %v", err)
continue
}
c.sh.wsHub.watchReq <- watchReq{
conn: c,
tag: cm.Tag,
q: cm.Query,
}
}
}
// write writes a message with the given message type and payload.
func (c *wsConn) write(mt int, payload []byte) error {
c.ws.SetWriteDeadline(time.Now().Add(writeWait))
return c.ws.WriteMessage(mt, payload)
}
// writePump pumps messages from the hub to the websocket connection.
func (c *wsConn) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.ws.Close()
}()
for {
select {
case message, ok := <-c.send:
if !ok {
c.write(websocket.CloseMessage, []byte{})
return
}
if err := c.write(websocket.TextMessage, message); err != nil {
return
}
case <-ticker.C:
if err := c.write(websocket.PingMessage, []byte{}); err != nil {
return
}
}
}
}
func (sh *Handler) serveWebSocket(rw http.ResponseWriter, req *http.Request) {
ws, err := websocket.Upgrade(rw, req, nil, 1024, 1024)
if _, ok := err.(websocket.HandshakeError); ok {
http.Error(rw, "Not a websocket handshake", 400)
return
} else if err != nil {
log.Println(err)
return
}
c := &wsConn{
ws: ws,
send: make(chan []byte, 256),
sh: sh,
queries: make(map[string]*watchedQuery),
}
sh.wsHub.register <- c
go c.writePump()
c.readPump()
}