forked from centrifugal/centrifuge-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport_websocket.go
171 lines (153 loc) · 4.21 KB
/
transport_websocket.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
package centrifuge
import (
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"time"
"github.com/centrifugal/centrifuge-go/internal/proto"
"github.com/gorilla/websocket"
)
func extractDisconnectWebsocket(err error) *disconnect {
if err != nil {
if closeErr, ok := err.(*websocket.CloseError); ok {
var disconnect disconnect
err := json.Unmarshal([]byte(closeErr.Text), &disconnect)
if err == nil {
return &disconnect
}
}
}
return nil
}
type websocketTransport struct {
mu sync.Mutex
conn *websocket.Conn
encoding proto.Encoding
commandEncoder proto.CommandEncoder
replyDecoder proto.ReplyDecoder
replyCh chan *proto.Reply
config websocketConfig
disconnect *disconnect
closed bool
closeCh chan struct{}
}
// websocketConfig configures Websocket transport.
type websocketConfig struct {
// TLSConfig specifies the TLS configuration to use with tls.Client.
// If nil, the default configuration is used.
TLSConfig *tls.Config
// HandshakeTimeout specifies the duration for the handshake to complete.
HandshakeTimeout time.Duration
// EnableCompression specifies if the client should attempt to negotiate
// per message compression (RFC 7692). Setting this value to true does not
// guarantee that compression will be supported. Currently only "no context
// takeover" modes are supported.
EnableCompression bool
// CookieJar specifies the cookie jar.
// If CookieJar is nil, cookies are not sent in requests and ignored
// in responses.
CookieJar http.CookieJar
// Header specifies custom HTTP Header to send.
Header http.Header
}
func newWebsocketTransport(url string, encoding proto.Encoding, config websocketConfig) (transport, error) {
wsHeaders := config.Header
dialer := websocket.DefaultDialer
dialer.HandshakeTimeout = config.HandshakeTimeout
dialer.EnableCompression = config.EnableCompression
dialer.TLSClientConfig = config.TLSConfig
dialer.Jar = config.CookieJar
conn, resp, err := dialer.Dial(url, wsHeaders)
if err != nil {
return nil, fmt.Errorf("Error dial: %v", err)
}
if resp.StatusCode != http.StatusSwitchingProtocols {
return nil, fmt.Errorf("Wrong status code while connecting to server: %d", resp.StatusCode)
}
t := &websocketTransport{
conn: conn,
replyCh: make(chan *proto.Reply, 128),
config: config,
closeCh: make(chan struct{}),
commandEncoder: proto.NewCommandEncoder(encoding),
encoding: encoding,
}
go t.reader()
return t, nil
}
func (t *websocketTransport) Close() error {
t.mu.Lock()
defer t.mu.Unlock()
if t.closed {
return nil
}
t.closed = true
close(t.closeCh)
t.conn.WriteControl(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""), time.Now().Add(time.Second))
return t.conn.Close()
}
func (t *websocketTransport) reader() {
defer t.Close()
defer close(t.replyCh)
for {
_, data, err := t.conn.ReadMessage()
if err != nil {
disconnect := extractDisconnectWebsocket(err)
t.disconnect = disconnect
return
}
loop:
for {
decoder := proto.NewReplyDecoder(t.encoding, data)
for {
reply, err := decoder.Decode()
if err != nil {
if err == io.EOF {
break loop
}
t.disconnect = &disconnect{Reason: "decode error", Reconnect: false}
return
}
select {
case <-t.closeCh:
return
case t.replyCh <- reply:
default:
// Can't keep up with server message rate.
t.disconnect = &disconnect{Reason: "client slow", Reconnect: true}
return
}
}
}
}
}
func (t *websocketTransport) Write(cmd *proto.Command, timeout time.Duration) error {
data, err := t.commandEncoder.Encode(cmd)
if err != nil {
return err
}
t.mu.Lock()
defer t.mu.Unlock()
if timeout > 0 {
t.conn.SetWriteDeadline(time.Now().Add(timeout))
}
if t.encoding == proto.EncodingJSON {
err = t.conn.WriteMessage(websocket.TextMessage, data)
} else {
err = t.conn.WriteMessage(websocket.BinaryMessage, data)
}
if timeout > 0 {
t.conn.SetWriteDeadline(time.Time{})
}
return err
}
func (t *websocketTransport) Read() (*proto.Reply, *disconnect, error) {
reply, ok := <-t.replyCh
if !ok {
return nil, t.disconnect, io.EOF
}
return reply, nil, nil
}