-
Notifications
You must be signed in to change notification settings - Fork 0
/
realtime_handler.go
245 lines (217 loc) · 5.1 KB
/
realtime_handler.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
//go:generate go-bindata -pkg realtime -o realtime_embed.go realtime.js
package realtime
import (
"fmt"
"net/http"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
)
var proto = "v1"
type Config struct {
Throttle time.Duration
CheckOrigin bool
}
type Handler struct {
config Config
upgrader websocket.Upgrader
ws http.Handler
mut sync.Mutex //protects object and user maps
objs map[key]*Object
users map[string]*User
watchingUsers bool
userEvents chan *User
}
func NewHandler() *Handler {
return NewHandlerConfig(Config{})
}
func NewHandlerConfig(c Config) *Handler {
if c.Throttle < 15*time.Millisecond {
//15ms is approximately highest resolution on the JS eventloop
c.Throttle = 200 * time.Millisecond
}
r := &Handler{config: c}
r.upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
if !c.CheckOrigin {
r.upgrader.CheckOrigin = func(r *http.Request) bool {
return true
}
}
r.objs = map[key]*Object{}
r.users = map[string]*User{}
r.userEvents = make(chan *User)
//continually batches and sends updates
go r.flusher()
return r
}
func (r *Handler) UserEvents() <-chan *User {
if r.watchingUsers {
panic("Already watching user changes")
}
r.watchingUsers = true
return r.userEvents
}
func (r *Handler) flusher() {
//loops at Throttle speed
for {
//compute updates for each object for each subscriber
//and append each update to the users pending updates
for _, o := range r.objs {
o.computeUpdate()
}
//send all pending updates
r.mut.Lock()
for _, u := range r.users {
u.sendPending()
}
r.mut.Unlock()
time.Sleep(r.config.Throttle)
}
}
type addable interface {
add(key string, val interface{}) (*Object, error)
}
func (r *Handler) MustAdd(k string, v interface{}) {
if err := r.Add(k, v); err != nil {
panic(err)
}
}
func (r *Handler) Add(k string, v interface{}) error {
r.mut.Lock()
defer r.mut.Unlock()
t := reflect.TypeOf(v)
if t.Kind() != reflect.Ptr {
return fmt.Errorf("Cannot add '%s' - it is not a pointer type", k)
}
if _, ok := r.objs[key(k)]; ok {
return fmt.Errorf("Cannot add '%s' - already exists", k)
}
//access v.object via interfaces:
a, ok := v.(addable)
if !ok {
return fmt.Errorf("Cannot add '%s' - does not embed realtime.Object", k)
}
//pass v into v.object and get v.object back out
o, err := a.add(k, v)
if err != nil {
return fmt.Errorf("Cannot add '%s' %s", k, err)
}
r.objs[key(k)] = o
return nil
}
func (r *Handler) UpdateAll() {
r.mut.Lock()
for _, obj := range r.objs {
obj.checked = false
}
r.mut.Unlock()
}
func (r *Handler) Update(k string) {
r.mut.Lock()
if obj, ok := r.objs[key(k)]; ok {
obj.checked = false
}
r.mut.Unlock()
}
func (r *Handler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
if req.Header.Get("Upgrade") == "websocket" {
conn, err := r.upgrader.Upgrade(w, req, nil)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
r.serveWS(conn)
} else if strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
JS.ServeHTTP(w, req) //gziped realtime.js script file
} else {
http.NotFound(w, req)
}
}
func (r *Handler) serveWS(conn *websocket.Conn) {
handshake := struct {
Protocol string
ObjectVersions objectVersions
}{}
//first message is the rt handshake
if err := conn.ReadJSON(&handshake); err != nil {
conn.WriteMessage(websocket.TextMessage, []byte("Invalid rt handshake"))
conn.Close()
return
}
if handshake.Protocol != proto {
conn.WriteMessage(websocket.TextMessage, []byte("Invalid rt protocol version"))
conn.Close()
return
}
//ready
u := &User{
ID: conn.RemoteAddr().String(),
Connected: true,
uptime: time.Now(),
conn: conn,
versions: handshake.ObjectVersions,
pending: []*update{},
}
//add user and subscribe to each obj
r.mut.Lock()
for k := range u.versions {
if _, ok := r.objs[k]; !ok {
conn.WriteMessage(websocket.TextMessage, []byte("missing object: "+k))
r.mut.Unlock()
return
}
}
r.users[u.ID] = u
if r.watchingUsers {
r.userEvents <- u
}
for k := range u.versions {
obj := r.objs[k]
obj.subscribers[u.ID] = u
//create initial update
u.pending = append(u.pending, &update{
Key: k, Version: obj.version, Data: obj.bytes,
})
obj.Update()
}
r.mut.Unlock()
//loop here during connection
for {
//msgType, msgBytes, err
_, _, err := conn.ReadMessage()
if err != nil {
break
}
//TODO(jpillora): allow changing of subscriptions
}
conn.Close() //ensure closed
u.Connected = false
//remove user and unsubscribe to each obj
r.mut.Lock()
delete(r.users, u.ID)
if r.watchingUsers {
r.userEvents <- u
}
for k := range u.versions {
obj := r.objs[k]
delete(obj.subscribers, u.ID)
}
r.mut.Unlock()
//disconnected
}
//embedded JS file
var JSBytes = _realtimeJs
type jsServe []byte
var JS = jsServe(JSBytes)
func (j jsServe) ServeHTTP(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Content-Type", "text/javascript")
w.Header().Set("Content-Length", strconv.Itoa(len(JSBytes)))
w.Write(JSBytes)
}