-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathconnection.go
164 lines (140 loc) · 3.49 KB
/
connection.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
package websocketservice
import (
"crypto/rand"
"encoding/base64"
"sync"
"time"
"github.com/gorilla/websocket"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
)
type ConnectionId []byte
const (
connectionIdVersion0 = 0
connectionIdRandomBytes = 20
)
func NewConnectionId(address Address) (ConnectionId, error) {
id := make([]byte, 1+len(address)+connectionIdRandomBytes)
id[0] = connectionIdVersion0
copy(id[1:], address)
if _, err := rand.Read(id[1+len(address):]); err != nil {
return nil, err
}
return id, nil
}
func (id ConnectionId) Address() Address {
if id[0] != connectionIdVersion0 || len(id) < 1+connectionIdRandomBytes {
return nil
}
return Address(id[1 : len(id)-connectionIdRandomBytes])
}
func (id ConnectionId) String() string {
return base64.RawURLEncoding.EncodeToString(id)
}
type Connection struct {
conn *websocket.Conn
logger logrus.FieldLogger
readLoopDone chan struct{}
writeLoopDone chan struct{}
outgoing chan *websocket.PreparedMessage
handler ConnectionHandler
close chan struct{}
beginClosingOnce sync.Once
finishClosingOnce sync.Once
}
type ConnectionHandler interface {
HandleWebSocketMessage(msg *WebSocketMessage)
HandleClose()
}
const connectionSendBufferSize = 100
func NewConnection(conn *websocket.Conn, logger logrus.FieldLogger, handler ConnectionHandler) *Connection {
ret := &Connection{
conn: conn,
logger: logger,
readLoopDone: make(chan struct{}),
writeLoopDone: make(chan struct{}),
outgoing: make(chan *websocket.PreparedMessage, connectionSendBufferSize),
close: make(chan struct{}),
handler: handler,
}
go ret.readLoop()
go ret.writeLoop()
return ret
}
func (c *Connection) Send(msg *websocket.PreparedMessage) {
select {
case c.outgoing <- msg:
default:
c.logger.Warn("dropping outgoing websocket message")
}
}
func (c *Connection) Close() error {
c.beginClosing()
c.finishClosing()
return nil
}
func (c *Connection) readLoop() {
defer close(c.readLoopDone)
defer c.beginClosing()
for {
messageType, p, err := c.conn.ReadMessage()
if err != nil {
if !websocket.IsCloseError(err, websocket.CloseAbnormalClosure, websocket.CloseGoingAway) {
select {
case <-c.close:
default:
c.logger.Error(errors.Wrap(err, "websocket read error"))
}
}
return
}
if messageType == websocket.TextMessage {
text := string(p)
c.handler.HandleWebSocketMessage(&WebSocketMessage{
Text: &text,
})
} else if messageType == websocket.BinaryMessage {
c.handler.HandleWebSocketMessage(&WebSocketMessage{
Binary: p,
})
}
}
}
func (c *Connection) writeLoop() {
defer c.finishClosing()
defer close(c.writeLoopDone)
defer c.conn.Close()
for {
select {
case msg, ok := <-c.outgoing:
if !ok {
return
}
c.conn.SetWriteDeadline(time.Now().Add(5 * time.Second))
if err := c.conn.WritePreparedMessage(msg); err != nil {
if !websocket.IsCloseError(err, websocket.CloseAbnormalClosure, websocket.CloseGoingAway) && err != websocket.ErrCloseSent {
c.logger.Error(errors.Wrap(err, "websocket write error"))
}
return
}
case <-c.close:
return
}
}
}
func (c *Connection) beginClosing() {
c.beginClosingOnce.Do(func() {
close(c.close)
})
}
func (c *Connection) finishClosing() {
<-c.readLoopDone
<-c.writeLoopDone
invokeHandler := false
c.finishClosingOnce.Do(func() {
invokeHandler = true
})
if invokeHandler {
c.handler.HandleClose()
}
}