forked from h2oai/wave
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
232 lines (197 loc) · 5.48 KB
/
client.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
// Copyright 2020 H2O.ai, Inc.
//
// 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 wave
import (
"bytes"
"encoding/json"
"time"
"github.com/google/uuid"
"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 = 1 * 1024 * 1024 // bytes
)
var (
newline = []byte{'\n'}
notFound = []byte(`{"e":"not_found"}`)
upgrader = websocket.Upgrader{
ReadBufferSize: 1024, // TODO review
WriteBufferSize: 1024, // TODO review
}
)
// Client represent a websocket (UI) client.
type Client struct {
id string // unique id
addr string // remote IP:port, used for logging only
session *Session // end-user session
broker *Broker // broker
conn *websocket.Conn // connection
routes []string // watched routes
data chan []byte // send data
editable bool // allow editing? // TODO move to user; tie to role
}
func newClient(addr string, session *Session, broker *Broker, conn *websocket.Conn, editable bool) *Client {
return &Client{uuid.New().String(), addr, session, broker, conn, nil, make(chan []byte, 256), editable}
}
func (c *Client) listen() {
defer func() {
c.broker.unsubscribe <- c
c.conn.Close()
}()
c.conn.SetReadLimit(maxMessageSize)
c.conn.SetReadDeadline(time.Now().Add(pongWait))
c.conn.SetPongHandler(func(string) error {
c.conn.SetReadDeadline(time.Now().Add(pongWait))
return nil
})
for {
_, msg, err := c.conn.ReadMessage()
if err != nil {
if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
echo(Log{"t": "socket_read", "client": c.addr, "err": err.Error()})
}
break
}
m := parseMsg(msg)
switch m.t {
case patchMsgT:
if c.editable { // allow only if editing is enabled
c.broker.patch(m.addr, m.data)
}
case queryMsgT:
app := c.broker.getApp(m.addr)
if app == nil {
echo(Log{"t": "query", "client": c.addr, "route": m.addr, "error": "service unavailable"})
continue
}
app.forward(c.format(m.data))
case watchMsgT:
c.subscribe(m.addr) // subscribe even if page is currently NA
if app := c.broker.getApp(m.addr); app != nil { // do we have an app handling this route?
switch app.mode {
case unicastMode:
c.subscribe("/" + c.id) // client-level
case multicastMode:
c.subscribe("/" + c.session.subject) // user-level
}
boot := emptyJSON
if len(m.data) > 0 { // location hash
if j, err := json.Marshal(Boot{Hash: string(m.data)}); err == nil {
boot = j
}
}
app.forward(c.format(boot))
continue
}
if headers, err := json.Marshal(OpsD{M: &Meta{Username: c.session.username, Editor: c.editable}}); err == nil {
c.send(headers)
}
if page := c.broker.site.at(m.addr); page != nil { // is page?
if data := page.marshal(); data != nil {
c.send(data)
continue
}
}
c.send(notFound)
}
}
}
func (c *Client) subscribe(route string) {
c.routes = append(c.routes, route)
c.broker.subscribe <- Sub{route, c}
}
func (c *Client) send(data []byte) bool {
select {
case c.data <- data:
return true
default:
return false
}
}
func (c *Client) flush() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case data, ok := <-c.data:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
// broker closed the channel.
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
w, err := c.conn.NextWriter(websocket.TextMessage)
if err != nil {
return
}
w.Write(data)
// push queued messages, if any
n := len(c.data)
for i := 0; i < n; i++ {
w.Write(newline)
w.Write(<-c.data)
}
if err := w.Close(); err != nil {
return
}
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
func (c *Client) quit() {
close(c.data)
}
var (
usernameHeader = []byte("u:")
subjectHeader = []byte("s:")
clientIDHeader = []byte("c:")
accessTokenHeader = []byte("a:")
refreshTokenHeader = []byte("r:")
queryBodySep = []byte("\n\n")
)
func (c *Client) format(data []byte) []byte {
var buf bytes.Buffer
s := c.session
buf.Write(usernameHeader)
buf.WriteString(s.username)
buf.WriteByte('\n')
buf.Write(subjectHeader)
buf.WriteString(s.subject)
buf.WriteByte('\n')
buf.Write(clientIDHeader)
buf.WriteString(c.id)
buf.WriteByte('\n')
buf.Write(accessTokenHeader)
buf.WriteString(s.token.AccessToken)
buf.WriteByte('\n')
buf.Write(refreshTokenHeader)
buf.WriteString(s.token.AccessToken)
buf.Write(queryBodySep)
buf.Write(data)
return buf.Bytes()
}