forked from neptulon/neptulon
/
conn.go
280 lines (242 loc) · 7.52 KB
/
conn.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
package neptulon
import (
"errors"
"expvar"
"fmt"
"io"
"log"
"net"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/neptulon/cmap"
"github.com/neptulon/shortid"
"golang.org/x/net/websocket"
)
var recvCounter = expvar.NewInt("receivers")
var reqCounter = expvar.NewInt("requests")
var resCounter = expvar.NewInt("responses")
// Conn is a client connection.
type Conn struct {
ID string // Randomly generated unique client connection ID.
Session *cmap.CMap // Thread-safe data store for storing arbitrary data for this connection session.
middleware []func(ctx *ReqCtx) error
resRoutes *cmap.CMap // message ID (string) -> handler func(ctx *ResCtx) error : expected responses for requests that we've sent
ws atomic.Value // -> *websocket.Conn
wg sync.WaitGroup // incremented by one per goroutine created by conn
deadline time.Duration
isClientConn bool
connected atomic.Value // -> bool
disconnHandler func(c *Conn)
}
// NewConn creates a new Conn object.
func NewConn() (*Conn, error) {
id, err := shortid.UUID()
if err != nil {
return nil, err
}
c := &Conn{
ID: id,
Session: cmap.New(),
resRoutes: cmap.New(),
deadline: time.Second * time.Duration(300),
disconnHandler: func(c *Conn) {},
}
c.connected.Store(false)
return c, nil
}
// SetDeadline set the read/write deadlines for the connection, in seconds.
// Default value for read/write deadline is 300 seconds.
func (c *Conn) SetDeadline(seconds int) {
c.deadline = time.Second * time.Duration(seconds)
}
// Middleware registers middleware to handle incoming request messages.
func (c *Conn) Middleware(middleware ...Middleware) {
for _, m := range middleware {
c.MiddlewareFunc(m.Middleware)
}
}
// MiddlewareFunc registers middleware function to handle incoming request messages.
func (c *Conn) MiddlewareFunc(middleware ...func(ctx *ReqCtx) error) {
c.middleware = append(c.middleware, middleware...)
}
// DisconnHandler registers a function to handle disconnection event.
func (c *Conn) DisconnHandler(handler func(c *Conn)) {
c.disconnHandler = handler
}
// Connect connects to the given WebSocket server.
// addr should be formatted as ws://host:port -or- wss://host:port (i.e. ws://127.0.0.1:3000 -or- wss://localhost:3000)
func (c *Conn) Connect(addr string) error {
ws, err := websocket.Dial(addr, "", "http://localhost")
if err != nil {
return err
}
if err := c.setConn(ws); err != nil {
return err
}
c.isClientConn = true
c.wg.Add(1)
go func() {
defer recoverAndLog(c, &c.wg)
c.startReceive()
}()
time.Sleep(time.Millisecond) // give receive goroutine a few cycles to start
return nil
}
// RemoteAddr returns the remote network address.
func (c *Conn) RemoteAddr() net.Addr {
ws := c.ws.Load().(*websocket.Conn)
if ws == nil {
return nil
}
return ws.RemoteAddr()
}
// SendRequest sends a JSON-RPC request through the connection with an auto generated request ID.
// resHandler is called when a response is returned.
func (c *Conn) SendRequest(method string, params interface{}, resHandler func(res *ResCtx) error) (reqID string, err error) {
id, err := shortid.UUID()
if err != nil {
return "", err
}
req := request{ID: id, Method: method, Params: params}
if err = c.send(req); err != nil {
return "", err
}
c.resRoutes.Set(req.ID, resHandler)
return id, nil
}
// SendRequestArr sends a JSON-RPC request through the connection, with array params and auto generated request ID.
// resHandler is called when a response is returned.
func (c *Conn) SendRequestArr(method string, resHandler func(res *ResCtx) error, params ...interface{}) (reqID string, err error) {
return c.SendRequest(method, params, resHandler)
}
// Close closes the connection.
func (c *Conn) Close() error {
c.connected.Store(false)
ws := c.ws.Load().(*websocket.Conn)
if ws != nil {
ws.Close()
}
return nil
}
// Wait waits for all message/connection handler goroutines to exit.
// Returns error if wait timeouts (in seconds).
func (c *Conn) Wait(timeout int) error {
done := make(chan bool)
go func() { c.wg.Wait(); done <- true }()
select {
case <-done:
return nil
case <-time.After(time.Second * time.Duration(timeout)):
return errors.New("wait timed out")
}
}
// SendResponse sends a JSON-RPC response message through the connection.
func (c *Conn) sendResponse(id string, result interface{}, err *ResError) error {
return c.send(response{ID: id, Result: result, Error: err})
}
// Send sends the given message through the connection.
func (c *Conn) send(msg interface{}) error {
if !c.connected.Load().(bool) {
return errors.New("use of closed connection")
}
return websocket.JSON.Send(c.ws.Load().(*websocket.Conn), msg)
}
// Receive receives message from the connection.
func (c *Conn) receive(msg *message) error {
if !c.connected.Load().(bool) {
return errors.New("use of closed connection")
}
return websocket.JSON.Receive(c.ws.Load().(*websocket.Conn), &msg)
}
// Reuse an established websocket.Conn.
func (c *Conn) setConn(ws *websocket.Conn) error {
c.ws.Store(ws)
c.connected.Store(true)
if err := ws.SetDeadline(time.Now().Add(c.deadline)); err != nil {
return fmt.Errorf("conn: error while setting websocket connection deadline: %v", err)
}
return nil
}
// startReceive starts receiving messages. This method blocks and does not return until the connection is closed.
func (c *Conn) startReceive() {
recvCounter.Add(1)
defer func() {
c.Close()
c.disconnHandler(c)
recvCounter.Add(-1)
}()
for {
var m message
err := c.receive(&m)
if err != nil {
// if we closed the connection
if !c.connected.Load().(bool) {
log.Printf("conn: closed %v: %v", c.ID, c.RemoteAddr())
break
}
// if peer closed the connection
if err == io.EOF {
log.Printf("conn: peer disconnected %v: %v", c.ID, c.RemoteAddr())
break
}
log.Printf("conn: error while receiving message: %v", err)
break
}
// if the message is a request
if m.Method != "" {
reqCounter.Add(1)
c.wg.Add(1)
go func() {
defer reqCounter.Add(-1)
defer recoverAndLog(c, &c.wg)
ctx := newReqCtx(c, m.ID, m.Method, m.Params, c.middleware)
if err := ctx.Next(); err != nil {
log.Printf("ctx: request middleware returned error: %v", err)
c.Close()
}
if ctx.Res != nil || ctx.Err != nil {
if err := ctx.Conn.sendResponse(ctx.ID, ctx.Res, ctx.Err); err != nil {
log.Printf("ctx: error sending response: %v", err)
c.Close()
}
}
}()
continue
}
// if the message is not a JSON-RPC message
if m.ID == "" || (m.Result == nil && m.Error == nil) {
log.Printf("conn: received an unknown message %v: %v, %v", c.ID, c.RemoteAddr(), m)
break
}
// if the message is a response
if resHandler, ok := c.resRoutes.GetOk(m.ID); ok {
resCounter.Add(1)
c.wg.Add(1)
go func() {
defer resCounter.Add(-1)
defer recoverAndLog(c, &c.wg)
err := resHandler.(func(ctx *ResCtx) error)(newResCtx(c, m.ID, m.Result, m.Error))
c.resRoutes.Delete(m.ID)
if err != nil {
log.Printf("conn: error while handling response: %v", err)
c.Close()
}
}()
} else {
log.Printf("conn: error while handling response: got response to a request with unknown ID: %v", m.ID)
break
}
}
}
func recoverAndLog(c *Conn, wg *sync.WaitGroup) {
defer wg.Done()
if err := recover(); err != nil {
c.Close()
const size = 64 << 10
buf := make([]byte, size)
buf = buf[:runtime.Stack(buf, false)]
log.Printf("conn: panic handling response %v: %v\nstack trace: %s", c.RemoteAddr(), err, buf)
}
}