forked from jcelliott/turnpike
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
372 lines (341 loc) · 9.73 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
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
// Copyright (c) 2013 Joshua Elliott
// Released under the MIT License
// http://opensource.org/licenses/MIT
package turnpike
import (
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"golang.org/x/net/websocket"
)
const (
wampProtocolId = "wamp"
)
var clientBacklog = 10
// Client represents a WAMP client that handles RPC and pub/sub.
type Client struct {
// SessionId is a ID of the session in UUID4 format received at the start of the session.
SessionId string
// ProtocolVersion is the version of the WAMP protocol received at the start of the session.
ProtocolVersion int
// ServerIdent is the server ID (ie "turnpike, autobahn") received at the start of the session.
ServerIdent string
ws *websocket.Conn
messages chan string
prefixes prefixMap
eventHandlers map[string]EventHandler
calls map[string]chan CallResult
sessionOpenCallback func(string)
}
// CallResult represents either a sucess or a failure after a RPC call.
type CallResult struct {
// Result contains the RPC call result returned by the server.
Result interface{}
// Error is nil on call success otherwise it contains the RPC error.
Error error
}
// EventHandler is an interface for handlers to published events. The topicURI
// is the URI of the event and event is the event centents.
type EventHandler func(topicURI string, event interface{})
// NewClient creates a new WAMP client.
func NewClient() *Client {
return &Client{
messages: make(chan string, clientBacklog),
prefixes: make(prefixMap),
eventHandlers: make(map[string]EventHandler),
calls: make(map[string]chan CallResult),
}
}
// Prefix sets a CURIE prefix at the server for later use when interacting with
// the server. prefix is the first part of a CURIE (ie "calc") and URI is a full
// identifier (ie "http://example.com/simple/calc#") that is mapped to the prefix.
//
// Ref: http://wamp.ws/spec#prefix_message
func (c *Client) Prefix(prefix, URI string) error {
if debug {
log.Print("turnpike: sending prefix")
}
err := c.prefixes.registerPrefix(prefix, URI)
if err != nil {
return fmt.Errorf("turnpike: %s", err)
}
msg, err := createPrefix(prefix, URI)
if err != nil {
return fmt.Errorf("turnpike: %s", err)
}
c.messages <- string(msg)
return nil
}
// Call makes a RPC call on the server identified by procURI (in either full URI
// or CURIE format) with zero or more args. Returns a channel that will receive
// the call result (or error) on completion.
//
// Ref: http://wamp.ws/spec#call_message
func (c *Client) Call(procURI string, args ...interface{}) chan CallResult {
if debug {
log.Print("turnpike: sending call")
}
// Channel size must be 1 to avoid blocking if no one is receiving the channel later.
resultCh := make(chan CallResult, 1)
callId := newId(16)
msg, err := createCall(callId, procURI, args...)
if err != nil {
r := CallResult{
Result: nil,
Error: fmt.Errorf("turnpike: %s", err),
}
resultCh <- r
return resultCh
}
c.calls[callId] = resultCh
c.messages <- string(msg)
return resultCh
}
// Subscribe adds a subscription at the server for events with topicURI lasting
// for the session or until Unsubscribe is called.
//
// Ref: http://wamp.ws/spec#subscribe_message
func (c *Client) Subscribe(topicURI string, f EventHandler) error {
if debug {
log.Print("turnpike: sending subscribe")
}
msg, err := createSubscribe(topicURI)
if err != nil {
return fmt.Errorf("turnpike: %s", err)
}
c.messages <- string(msg)
if f != nil {
c.eventHandlers[topicURI] = f
}
return nil
}
// Unsubscribe removes a previous subscription with topicURI at the server.
//
// Ref: http://wamp.ws/spec#unsubscribe_message
func (c *Client) Unsubscribe(topicURI string) error {
if debug {
log.Print("turnpike: sending unsubscribe")
}
msg, err := createUnsubscribe(topicURI)
if err != nil {
return fmt.Errorf("turnpike: %s", err)
}
c.messages <- string(msg)
delete(c.eventHandlers, topicURI)
return nil
}
// Publish publishes an event to the topicURI that gets sent to all subscribers
// of that topicURI by the server. opts can can be either empty, one boolean
// that can be used to exclude outself from receiving the event or two lists;
// the first a list of clients to exclude and the second a list of clients that
// are eligible to receive the event. Either list can be empty.
//
// Ref: http://wamp.ws/spec#publish_message
func (c *Client) Publish(topicURI string, event interface{}, opts ...interface{}) error {
if debug {
log.Print("turnpike: sending publish")
}
msg, err := createPublish(topicURI, event, opts...)
if err != nil {
return fmt.Errorf("turnpike: %s", err)
}
c.messages <- string(msg)
return nil
}
// PublishExcludeMe is a short hand for Publish(tobicURI, event, true) that will
// not send the event to ourself.
func (c *Client) PublishExcludeMe(topicURI string, event interface{}) error {
return c.Publish(topicURI, event, true)
}
func (c *Client) handleCallResult(msg callResultMsg) {
if debug {
log.Print("turnpike: handling call result message")
}
resultCh, ok := c.calls[msg.CallID]
if !ok {
if debug {
log.Print("turnpike: missing call result handler")
}
return
}
delete(c.calls, msg.CallID)
r := CallResult{
Result: msg.Result,
Error: nil,
}
resultCh <- r
}
func (c *Client) handleCallError(msg callErrorMsg) {
if debug {
log.Print("turnpike: handling call error message")
}
resultCh, ok := c.calls[msg.CallID]
if !ok {
if debug {
log.Print("turnpike: missing call result handler")
}
return
}
delete(c.calls, msg.CallID)
r := CallResult{
Error: RPCError{
URI: msg.ErrorURI,
Description: msg.ErrorDesc,
Details: msg.ErrorDetails,
},
}
resultCh <- r
}
func (c *Client) handleEvent(msg eventMsg) {
if debug {
log.Print("turnpike: handling event message")
}
if f, ok := c.eventHandlers[msg.TopicURI]; ok && f != nil {
f(msg.TopicURI, msg.Event)
} else {
if debug {
log.Printf("turnpike: missing event handler for URI: %s", msg.TopicURI)
}
}
}
func (c *Client) receiveWelcome() error {
if debug {
log.Print("turnpike: receive welcome")
}
var rec string
err := websocket.Message.Receive(c.ws, &rec)
if err != nil {
return fmt.Errorf("Error receiving welcome message: %s", err)
}
if typ := parseMessageType(rec); typ != msgWelcome {
return fmt.Errorf("First message received was not welcome")
}
var msg welcomeMsg
err = json.Unmarshal([]byte(rec), &msg)
if err != nil {
return fmt.Errorf("Error unmarshalling welcome message: %s", err)
}
c.SessionId = msg.SessionId
c.ProtocolVersion = msg.ProtocolVersion
c.ServerIdent = msg.ServerIdent
if debug {
log.Print("turnpike: session id: %s", c.SessionId)
log.Print("turnpike: protocol version: %d", c.ProtocolVersion)
log.Print("turnpike: server ident: %s", c.ServerIdent)
}
if c.sessionOpenCallback != nil {
c.sessionOpenCallback(c.SessionId)
}
return nil
}
func (c *Client) receive() {
for {
var rec string
err := websocket.Message.Receive(c.ws, &rec)
if err != nil {
if err != io.EOF {
if debug {
log.Printf("turnpike: error receiving message, aborting connection: %s", err)
}
}
break
}
if debug {
log.Printf("turnpike: message received: %s", rec)
}
data := []byte(rec)
switch typ := parseMessageType(rec); typ {
case msgCallResult:
var msg callResultMsg
err := json.Unmarshal(data, &msg)
if err != nil {
if debug {
log.Printf("turnpike: error unmarshalling call result message: %s", err)
}
continue
}
c.handleCallResult(msg)
case msgCallError:
var msg callErrorMsg
err := json.Unmarshal(data, &msg)
if err != nil {
if debug {
log.Printf("turnpike: error unmarshalling call error message: %s", err)
}
continue
}
c.handleCallError(msg)
case msgEvent:
var msg eventMsg
err := json.Unmarshal(data, &msg)
if err != nil {
if debug {
log.Printf("turnpike: error unmarshalling event message: %s", err)
}
continue
}
c.handleEvent(msg)
case msgPrefix, msgCall, msgSubscribe, msgUnsubscribe, msgPublish:
if debug {
log.Printf("turnpike: client -> server message received, ignored: %s", messageTypeString(typ))
}
case msgWelcome:
if debug {
log.Print("turnpike: received extraneous welcome message, ignored")
}
default:
if debug {
log.Printf("turnpike: invalid message format, message dropped: %s", data)
}
}
}
}
func (c *Client) send() {
for msg := range c.messages {
if debug {
log.Printf("turnpike: sending message: %s", msg)
}
if err := websocket.Message.Send(c.ws, msg); err != nil {
if debug {
log.Printf("turnpike: error sending message: %s", err)
}
}
}
}
// Connect will connect to server with an optional origin.
// More details here: http://godoc.org/code.google.com/p/go.net/websocket#Dial
func (c *Client) Connect(server, origin string) error {
if debug {
log.Print("turnpike: connect")
}
var err error
if c.ws, err = websocket.Dial(server, wampProtocolId, origin); err != nil {
return fmt.Errorf("Error connecting to websocket server: %s", err)
}
// Receive welcome message
if err = c.receiveWelcome(); err != nil {
return err
}
if debug {
log.Printf("turnpike: connected to server: %s", server)
}
go c.receive()
go c.send()
return nil
}
// 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 (c *Client) SetSessionOpenCallback(f func(string)) {
c.sessionOpenCallback = f
}
// newId generates a random string of fixed size.
func newId(size int) string {
const alpha = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnpqrstuvwxyz0123456789-_"
buf := make([]byte, size)
for i := 0; i < size; i++ {
buf[i] = alpha[rand.Intn(len(alpha))]
}
return string(buf)
}