forked from mattbaird/turnpike
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
599 lines (538 loc) · 14.9 KB
/
server.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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
// Copyright (c) 2013 Joshua Elliott
// Released under the MIT License
// http://opensource.org/licenses/MIT
package turnpike
import (
"encoding/json"
"fmt"
"github.com/nu7hatch/gouuid"
cmap "github.com/streamrail/concurrent-map"
"golang.org/x/net/websocket"
"io"
"log"
"net"
"net/http"
"strings"
"sync"
"time"
)
var (
// The amount of messages to buffer before sending to client.
serverBacklog = 20
)
const (
clientConnTimeout = 6
clientMaxFailures = 3
)
// Server represents a WAMP server that handles RPC and pub/sub.
type Server struct {
// Client ID -> send channel
clients cmap.ConcurrentMap
// Client ID -> prefix mapping
prefixes map[string]prefixMap
// Proc URI -> handler
rpcHandlers map[string]RPCHandler
subHandlers map[string]SubHandler
pubHandlers map[string]PubHandler
// Topic URI -> subscribed clients
subscriptions map[string]listenerMap
subLock *sync.Mutex
sessionOpenCallback func(string)
websocket.Server
}
// Using a handle func pattern so we can adapt the calls and do things like retry
type RPCHandler interface {
// RPCHandler is an interface that handlers to RPC calls should implement.
// The first parameter is the call ID, the second is the proc URI. Last comes
// all optional arguments to the RPC call. The return can be of any type that
// can be marshaled to JSON, or a error (preferably RPCError but any error works.)
// NOTE: this may be broken in v2 if multiple-return is implemented
HandleRPC(clientID string, topicURI string, args ...interface{}) (interface{}, error)
}
type HandlerFunc func(clientID string, topicURI string, args ...interface{}) (interface{}, error)
func (f HandlerFunc) HandleRPC(clientID string, topicURI string, args ...interface{}) (interface{}, error) {
return f(clientID, topicURI, args...)
}
// RPCError represents a call error and is the recommended way to return an
// error from a RPC handler.
type RPCError struct {
URI string
Description string
Details interface{}
}
// Error returns an error description.
func (e RPCError) Error() string {
return fmt.Sprintf("turnpike: RPC error with URI %s: %s", e.URI, e.Description)
}
// SubHandler is an interface that handlers for subscriptions should implement to
// control with subscriptions are valid. A subscription is allowed by returning
// true or denied by returning false.
type SubHandler func(clientID string, topicURI string) bool
// PubHandler is an interface that handlers for publishes should implement to
// get notified on a client publish with the possibility to modify the event.
// The event that will be published should be returned.
type PubHandler func(topicURI string, event interface{}) interface{}
// NewServer creates a new WAMP server.
func NewServer(isDebug bool) *Server {
debug = isDebug
s := &Server{
clients: cmap.New(),
prefixes: make(map[string]prefixMap),
rpcHandlers: make(map[string]RPCHandler),
subHandlers: make(map[string]SubHandler),
pubHandlers: make(map[string]PubHandler),
subscriptions: make(map[string]listenerMap),
subLock: new(sync.Mutex),
}
s.Server = websocket.Server{
Handshake: checkWAMPHandshake,
Handler: websocket.Handler(s.HandleWebsocket),
}
return s
}
// SetSessionOpenCallback adds a callback function that is run when a new session begins.
// The callback function must accept a string argument that is the session ID.
func (t *Server) SetSessionOpenCallback(f func(string)) {
t.sessionOpenCallback = f
}
// RegisterRPC adds a handler for the RPC named uri.
func (t *Server) RegisterRPCFunc(uri string, f RPCHandler) {
if f != nil {
t.rpcHandlers[uri] = f
}
}
func (t *Server) RegisterRPC(uri string, f func(clientID string, topicURI string, args ...interface{}) (interface{}, error)) {
if f != nil {
t.rpcHandlers[uri] = HandlerFunc(f)
}
}
// UnregisterRPC removes a handler for the RPC named uri.
func (t *Server) UnregisterRPC(uri string) {
delete(t.rpcHandlers, uri)
}
// RegisterSubHandler adds a handler called when a client subscribes to URI.
// The subscription can be canceled in the handler by returning false, or
// approved by returning true.
func (t *Server) RegisterSubHandler(uri string, f SubHandler) {
if f != nil {
t.subHandlers[uri] = f
}
}
// UnregisterSubHandler removes a subscription handler for the URI.
func (t *Server) UnregisterSubHandler(uri string) {
delete(t.subHandlers, uri)
}
// RegisterPubHandler adds a handler called when a client publishes to URI.
// The event can be modified in the handler and the returned event is what is
// published to the other clients.
func (t *Server) RegisterPubHandler(uri string, f PubHandler) {
if f != nil {
t.pubHandlers[uri] = f
}
}
// UnregisterPubHandler removes a publish handler for the URI.
func (t *Server) UnregisterPubHandler(uri string) {
delete(t.pubHandlers, uri)
}
// SendEvent sends an event with topic directly (not via Client.Publish())
func (t *Server) SendEvent(topic string, event interface{}, excludeMe bool, excludeList []string, eligibleList []string) {
t.handlePublish(topic, publishMsg{
TopicURI: topic,
Event: event,
ExcludeMe: excludeMe,
ExcludeList: excludeList,
EligibleList: eligibleList,
})
}
// ConnectedClients returns a slice of the ids of all connected clients
func (t *Server) ConnectedClients() []string {
clientIDs := []string{}
for val := range t.clients.Iter() {
clientIDs = append(clientIDs, val.Key)
}
return clientIDs
}
func (t *Server) SubscribedTopicUris() []string {
topicUris := []string{}
for topic := range t.subscriptions {
topicUris = append(topicUris, topic)
}
return topicUris
}
// HandleWebsocket implements the go.net/websocket.Handler interface.
func (t *Server) HandleWebsocket(conn *websocket.Conn) {
defer conn.Close()
if debug {
log.Print("turnpike: received websocket connection")
}
tid, err := uuid.NewV4()
if err != nil {
if debug {
log.Print("turnpike: could not create unique id, refusing client connection")
}
return
}
id := tid.String()
if debug {
log.Printf("turnpike: client connected: %s", id)
}
arr, err := createWelcome(id, turnpikeServerIdent)
if err != nil {
if debug {
log.Print("turnpike: error encoding welcome message")
}
return
}
if debug {
log.Printf("turnpike: sending welcome message: %s", arr)
}
err = websocket.Message.Send(conn, string(arr))
if err != nil {
if debug {
log.Printf("turnpike: error sending welcome message, aborting connection: %s", err)
}
return
}
// this should be put into a more persistent store
c := make(chan string, serverBacklog)
t.clients.Set(id, c)
if t.sessionOpenCallback != nil {
t.sessionOpenCallback(id)
}
failures := 0
go func() {
for msg := range c {
if debug {
log.Printf("turnpike: sending message: %s", msg)
}
conn.SetWriteDeadline(time.Now().Add(clientConnTimeout * time.Second))
err := websocket.Message.Send(conn, msg)
if err != nil {
if nErr, ok := err.(net.Error); ok && (nErr.Timeout() || nErr.Temporary()) {
log.Printf("Network error: %s", nErr)
failures++
if failures > clientMaxFailures {
break
}
} else {
if debug {
log.Printf("turnpike: error sending message: %s", err)
}
break
}
}
}
if debug {
log.Printf("Client %s disconnected", id)
}
conn.Close()
}()
for {
var rec string
err := websocket.Message.Receive(conn, &rec)
if err != nil {
if err != io.EOF {
if strings.EqualFold(err.Error(), "not implemented") {
// pongFrame from IE is fucking broken.
//https://github.com/golang/go/issues/6377
if debug {
log.Printf("turnpike: IE Pongframe Issue - ignoring: [%v]", err)
}
continue
} else {
if debug {
log.Printf("turnpike: error receiving message, aborting connection: [%v]", err)
}
break
}
}
break
}
if debug {
log.Printf("turnpike: message received: %s", rec)
}
data := []byte(rec)
switch typ := parseMessageType(rec); typ {
case msgPrefix:
var msg prefixMsg
err := json.Unmarshal(data, &msg)
if err != nil {
if debug {
log.Printf("turnpike: error unmarshalling prefix message: %s", err)
}
continue
}
go t.handlePrefix(id, msg)
case msgCall:
var msg callMsg
err := json.Unmarshal(data, &msg)
if err != nil {
if debug {
log.Printf("turnpike: error unmarshalling call message: %s", err)
}
continue
}
go t.handleCall(id, msg)
case msgSubscribe:
var msg subscribeMsg
err := json.Unmarshal(data, &msg)
if err != nil {
if debug {
log.Printf("turnpike: error unmarshalling subscribe message: %s", err)
}
continue
}
go t.handleSubscribe(id, msg)
case msgUnsubscribe:
var msg unsubscribeMsg
err := json.Unmarshal(data, &msg)
if err != nil {
if debug {
log.Printf("turnpike: error unmarshalling unsubscribe message: %s", err)
}
continue
}
go t.handleUnsubscribe(id, msg)
case msgPublish:
var msg publishMsg
err := json.Unmarshal(data, &msg)
if err != nil {
if debug {
log.Printf("turnpike: error unmarshalling publish message: %s", err)
}
continue
}
go t.handlePublish(id, msg)
case msgWelcome, msgCallResult, msgCallError, msgEvent:
if debug {
log.Printf("turnpike: server -> client message received, ignored: %s", messageTypeString(typ))
}
default:
if debug {
log.Printf("turnpike: invalid message format, message dropped: %s", data)
}
}
}
t.clients.Remove(id)
close(c)
}
func (t *Server) handlePrefix(id string, msg prefixMsg) {
if debug {
log.Print("turnpike: handling prefix message")
}
if _, ok := t.prefixes[id]; !ok {
t.prefixes[id] = make(prefixMap)
}
if err := t.prefixes[id].registerPrefix(msg.Prefix, msg.URI); err != nil {
if debug {
log.Printf("turnpike: error registering prefix: %s", err)
}
}
if debug {
log.Printf("turnpike: client %s registered prefix '%s' for URI: %s", id, msg.Prefix, msg.URI)
}
}
func (t *Server) handleCall(id string, msg callMsg) {
if debug {
log.Printf("turnpike: handling call message %s", msg.ProcURI)
}
var out string
var err error
if rpcHandlerInterface, ok := t.rpcHandlers[msg.ProcURI]; ok && rpcHandlerInterface != nil {
if debug {
log.Printf("turnpike: rpcHandlerInterface:%v (%v)", msg.ProcURI, msg.CallArgs)
}
var res interface{}
res, err = rpcHandlerInterface.HandleRPC(id, msg.ProcURI, msg.CallArgs...)
if err != nil {
if debug {
log.Printf("turnpike: rpcHandlerInterface error:%v", err)
}
var errorURI, desc string
var details interface{}
if er, ok := err.(RPCError); ok {
errorURI = er.URI
desc = er.Description
details = er.Details
} else {
errorURI = msg.ProcURI + "#generic-error"
desc = err.Error()
}
if details != nil {
out, err = createCallError(msg.CallID, errorURI, desc, details)
} else {
out, err = createCallError(msg.CallID, errorURI, desc)
}
} else {
if debug {
log.Printf("turnpike: createCallResult error:%v", msg.CallID)
}
out, err = createCallResult(msg.CallID, res)
}
} else {
if debug {
log.Printf("turnpike: RPC call not registered: %s", msg.ProcURI)
}
if debug {
log.Printf("turnpike: createCallError error:%v", msg.ProcURI)
}
out, err = createCallError(msg.CallID, "error:notimplemented", "RPC call '%s' not implemented", msg.ProcURI)
}
if err != nil {
// whatever, let the client hang...
if debug {
log.Printf("turnpike: error creating callError message: %s", err)
}
return
}
if client, ok := t.clients.Get(id); ok {
if debug {
log.Printf("turnpike: client <- out (%v)", out)
}
client.(chan string) <- out
}
}
func (t *Server) handleSubscribe(id string, msg subscribeMsg) {
if debug {
log.Print("turnpike: handling subscribe message")
}
uri := checkCurie(t.prefixes[id], msg.TopicURI)
h := t.getSubHandler(uri)
if h != nil && !h(id, uri) {
if debug {
log.Printf("turnpike: client %s denied subscription of topic: %s", id, uri)
}
return
}
t.subLock.Lock()
defer t.subLock.Unlock()
if _, ok := t.subscriptions[uri]; !ok {
t.subscriptions[uri] = make(map[string]bool)
}
t.subscriptions[uri].add(id)
if debug {
log.Printf("turnpike: client %s subscribed to topic: %s", id, uri)
}
}
func (t *Server) handleUnsubscribe(id string, msg unsubscribeMsg) {
if debug {
log.Print("turnpike: handling unsubscribe message")
}
t.subLock.Lock()
uri := checkCurie(t.prefixes[id], msg.TopicURI)
if lm, ok := t.subscriptions[uri]; ok {
lm.remove(id)
}
t.subLock.Unlock()
if debug {
log.Printf("turnpike: client %s unsubscribed from topic: %s", id, uri)
}
}
func (t *Server) handlePublish(id string, msg publishMsg) {
if debug {
log.Printf("turnpike: msg.Event = %v", msg.Event)
log.Printf("turnpike: msg.ExcludeMe = %v", msg.ExcludeMe)
log.Printf("turnpike: msg.ExcludeList = %v", msg.ExcludeList)
log.Printf("turnpike: msg.EligibleList = %v", msg.EligibleList)
}
uri := checkCurie(t.prefixes[id], msg.TopicURI)
h := t.getPubHandler(uri)
event := msg.Event
if h != nil {
event = h(uri, event)
}
lm, ok := t.subscriptions[uri]
if !ok {
return
}
out, err := createEvent(uri, event)
if err != nil {
if debug {
log.Printf("turnpike: error creating event message: %s", err)
}
return
}
var sendTo []string
if len(msg.ExcludeList) > 0 || len(msg.EligibleList) > 0 {
// this is super ugly, but I couldn't think of a better way...
for tid := range lm {
include := true
for _, _tid := range msg.ExcludeList {
if tid == _tid {
include = false
break
}
}
if include {
sendTo = append(sendTo, tid)
}
}
for _, tid := range msg.EligibleList {
include := true
for _, _tid := range sendTo {
if _tid == tid {
include = false
break
}
}
if include {
sendTo = append(sendTo, tid)
}
}
} else {
for tid := range lm {
if tid == id && msg.ExcludeMe {
continue
}
sendTo = append(sendTo, tid)
}
}
for _, tid := range sendTo {
// we're not locking anything, so we need
// to make sure the client didn't disconnect in the
// last few nanoseconds...
if client, ok := t.clients.Get(tid); ok {
if len(client.(chan string)) == cap(client.(chan string)) {
<-client.(chan string)
}
client.(chan string) <- string(out)
}
}
}
func (t *Server) getSubHandler(uri string) SubHandler {
for i := len(uri); i >= 0; i-- {
u := uri[:i]
if h, ok := t.subHandlers[u]; ok {
return h
}
}
return nil
}
func (t *Server) getPubHandler(uri string) PubHandler {
for i := len(uri); i >= 0; i-- {
u := uri[:i]
if h, ok := t.pubHandlers[u]; ok {
return h
}
}
return nil
}
type listenerMap map[string]bool
func (lm listenerMap) add(id string) {
lm[id] = true
}
func (lm listenerMap) contains(id string) bool {
return lm[id]
}
func (lm listenerMap) remove(id string) {
delete(lm, id)
}
func checkWAMPHandshake(config *websocket.Config, req *http.Request) error {
for _, protocol := range config.Protocol {
if protocol == "wamp" {
config.Protocol = []string{protocol}
return nil
}
}
return websocket.ErrBadWebSocketProtocol
}