forked from centrifugal/centrifuge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_sockjs.go
218 lines (182 loc) · 5.39 KB
/
handler_sockjs.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
package centrifuge
import (
"encoding/json"
"io"
"net/http"
"sync"
"time"
"github.com/centrifugal/centrifuge/internal/proto"
"github.com/igm/sockjs-go/sockjs"
)
const (
transportSockJS = "sockjs"
// We don't use specific close codes here because our connections
// can use other transport that do not have the same code semantics as SockJS.
sockjsCloseStatus = 3000
)
type sockjsTransport struct {
mu sync.RWMutex
closed bool
closeCh chan struct{}
session sockjs.Session
writer *writer
}
func newSockjsTransport(s sockjs.Session, w *writer) *sockjsTransport {
t := &sockjsTransport{
session: s,
writer: w,
closeCh: make(chan struct{}),
}
w.onWrite(t.write)
return t
}
func (t *sockjsTransport) Name() string {
return transportSockJS
}
func (t *sockjsTransport) Encoding() proto.Encoding {
return proto.EncodingJSON
}
func (t *sockjsTransport) Info() TransportInfo {
return TransportInfo{
Request: t.session.Request(),
}
}
func (t *sockjsTransport) Send(reply *preparedReply) error {
data := reply.Data()
disconnect := t.writer.write(data)
if disconnect != nil {
// Close in goroutine to not block message broadcast.
go t.Close(disconnect)
return io.EOF
}
return nil
}
func (t *sockjsTransport) write(data ...[]byte) error {
select {
case <-t.closeCh:
return nil
default:
for _, payload := range data {
// TODO: can actually be sent in single message as streaming JSON.
err := t.session.Send(string(payload))
if err != nil {
go t.Close(DisconnectWriteError)
return err
}
transportMessagesSent.WithLabelValues(transportSockJS).Inc()
}
return nil
}
}
func (t *sockjsTransport) Close(disconnect *Disconnect) error {
t.mu.Lock()
if t.closed {
// Already closed, noop.
t.mu.Unlock()
return nil
}
t.closed = true
t.mu.Unlock()
// Send messages remaining in queue.
t.writer.close()
t.mu.Lock()
close(t.closeCh)
t.mu.Unlock()
if disconnect == nil {
disconnect = DisconnectNormal
}
reason, err := json.Marshal(disconnect)
if err != nil {
return err
}
return t.session.Close(sockjsCloseStatus, string(reason))
}
// SockjsConfig represents config for SockJS handler.
type SockjsConfig struct {
// HandlerPrefix sets prefix for SockJS handler endpoint path.
HandlerPrefix string
// URL is URL address to SockJS client javascript library.
URL string
// HeartbeatDelay sets how often to send heartbeat frames to clients.
HeartbeatDelay time.Duration
// WebsocketReadBufferSize is a parameter that is used for raw websocket Upgrader.
// If set to zero reasonable default value will be used.
WebsocketReadBufferSize int
// WebsocketWriteBufferSize is a parameter that is used for raw websocket Upgrader.
// If set to zero reasonable default value will be used.
WebsocketWriteBufferSize int
}
// SockjsHandler accepts SockJS connections.
type SockjsHandler struct {
node *Node
config SockjsConfig
handler http.Handler
}
// NewSockjsHandler creates new SockjsHandler.
func NewSockjsHandler(n *Node, c SockjsConfig) *SockjsHandler {
sockjs.WebSocketReadBufSize = c.WebsocketReadBufferSize
sockjs.WebSocketWriteBufSize = c.WebsocketWriteBufferSize
options := sockjs.DefaultOptions
// Override sockjs url. It's important to use the same SockJS
// library version on client and server sides when using iframe
// based SockJS transports, otherwise SockJS will raise error
// about version mismatch.
options.SockJSURL = c.URL
options.HeartbeatDelay = c.HeartbeatDelay
s := &SockjsHandler{
node: n,
config: c,
}
handler := newSockJSHandler(s, c.HandlerPrefix, options)
s.handler = handler
return s
}
func (s *SockjsHandler) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
s.handler.ServeHTTP(rw, r)
}
// newSockJSHandler returns SockJS handler bind to sockjsPrefix url prefix.
// SockJS handler has several handlers inside responsible for various tasks
// according to SockJS protocol.
func newSockJSHandler(s *SockjsHandler, sockjsPrefix string, sockjsOpts sockjs.Options) http.Handler {
return sockjs.NewHandler(sockjsPrefix, sockjsOpts, s.sockJSHandler)
}
// sockJSHandler called when new client connection comes to SockJS endpoint.
func (s *SockjsHandler) sockJSHandler(sess sockjs.Session) {
transportConnectCount.WithLabelValues(transportSockJS).Inc()
// Separate goroutine for better GC of caller's data.
go func() {
config := s.node.Config()
writerConf := writerConfig{
MaxQueueSize: config.ClientQueueMaxSize,
}
writer := newWriter(writerConf)
defer writer.close()
transport := newSockjsTransport(sess, writer)
select {
case <-s.node.NotifyShutdown():
transport.Close(DisconnectShutdown)
return
default:
}
c, err := newClient(sess.Request().Context(), s.node, transport)
if err != nil {
s.node.logger.log(newLogEntry(LogLevelError, "error creating client", map[string]interface{}{"transport": transportSockJS}))
return
}
defer c.close(nil)
s.node.logger.log(newLogEntry(LogLevelDebug, "client connection established", map[string]interface{}{"client": c.ID(), "transport": transportSockJS}))
defer func(started time.Time) {
s.node.logger.log(newLogEntry(LogLevelDebug, "client connection completed", map[string]interface{}{"client": c.ID(), "transport": transportSockJS, "duration": time.Since(started)}))
}(time.Now())
for {
if msg, err := sess.Recv(); err == nil {
ok := c.handleRawData([]byte(msg), writer)
if !ok {
return
}
continue
}
break
}
}()
}