-
-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathhandler_sse.go
More file actions
270 lines (237 loc) · 7.09 KB
/
Copy pathhandler_sse.go
File metadata and controls
270 lines (237 loc) · 7.09 KB
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
package centrifuge
import (
"errors"
"io"
"net/http"
"sync"
"time"
"github.com/centrifugal/centrifuge/internal/convert"
"github.com/centrifugal/centrifuge/internal/readerpool"
)
// SSEConfig represents config for SSEHandler.
type SSEConfig struct {
PingPongConfig
// MaxRequestBodySize limits initial request body size (when SSE starts with POST).
MaxRequestBodySize int
}
// SSEHandler handles WebSocket client connections. WebSocket protocol
// is a bidirectional connection between a client and a server for low-latency
// communication.
type SSEHandler struct {
node *Node
config SSEConfig
}
// NewSSEHandler creates new SSEHandler.
func NewSSEHandler(node *Node, config SSEConfig) *SSEHandler {
warnAboutIncorrectPingPongConfig(node, config.PingPongConfig, transportSSE)
return &SSEHandler{
node: node,
config: config,
}
}
// Since SSE is usually starts with a GET request (at least in browsers) we are looking
// for connect request in URL params. This should be a properly encoded command(s) in
// Centrifuge protocol.
const connectUrlParam = "cf_connect"
const defaultMaxSSEBodySize = 64 * 1024
func (h *SSEHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
_, ok := w.(http.Flusher)
if !ok {
h.node.logger.log(newErrorLogEntry(errors.New("not http.Flusher"), "SSE: ResponseWriter is not a Flusher", map[string]any{}))
http.Error(w, "expected http.ResponseWriter to be http.Flusher", http.StatusInternalServerError)
return
}
// messageSizeLimit bounds both the request body and a single decoded command;
// it must be positive since the stream decoder rejects a non-positive limit.
messageSizeLimit := h.config.MaxRequestBodySize
if messageSizeLimit <= 0 {
messageSizeLimit = defaultMaxSSEBodySize
}
var requestData []byte
if r.Method == http.MethodGet {
requestDataString := r.URL.Query().Get(connectUrlParam)
if requestDataString != "" {
requestData = []byte(requestDataString)
} else {
h.node.logger.log(newLogEntry(LogLevelDebug, "no connect command", map[string]any{}))
w.WriteHeader(http.StatusBadRequest)
return
}
} else if r.Method == http.MethodPost {
r.Body = http.MaxBytesReader(w, r.Body, int64(messageSizeLimit))
var err error
requestData, err = io.ReadAll(r.Body)
if err != nil {
h.node.logger.log(newLogEntry(LogLevelInfo, "error reading sse request body", map[string]any{"error": err.Error()}))
if len(requestData) >= messageSizeLimit {
w.WriteHeader(http.StatusRequestEntityTooLarge)
return
}
w.WriteHeader(statusCodeClientConnectionClosed)
return
}
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
ack := make(chan struct{})
transport := newSSETransport(r, sseTransportConfig{
pingPong: h.config.PingPongConfig,
protoMajor: uint8(r.ProtoMajor),
}, ack)
c, closeFn, err := NewClient(r.Context(), h.node, transport)
if err != nil {
h.node.logger.log(newErrorLogEntry(err, "error create client", map[string]any{"error": err.Error(), "transport": transportSSE}))
return
}
defer func() { _ = closeFn() }()
defer close(transport.closedCh) // need to execute this after client closeFn.
if h.node.logEnabled(LogLevelDebug) {
h.node.logger.log(newLogEntry(LogLevelDebug, "client connection established", map[string]any{"transport": transport.Name(), "client": c.ID()}))
defer func(started time.Time) {
h.node.logger.log(newLogEntry(LogLevelDebug, "client connection completed", map[string]any{"duration": time.Since(started).String(), "transport": transport.Name(), "client": c.ID()}))
}(time.Now())
}
if r.ProtoMajor == 1 {
// An endpoint MUST NOT generate an HTTP/2 message containing connection-specific header fields.
// Source: RFC7540.
w.Header().Set("Connection", "keep-alive")
}
w.Header().Set("X-Accel-Buffering", "no")
w.Header().Set("Content-Type", "text/event-stream; charset=utf-8")
w.Header().Set("Cache-Control", "private, no-cache, no-store, must-revalidate, max-age=0")
w.Header().Set("Pragma", "no-cache")
w.Header().Set("Expire", "0")
w.WriteHeader(http.StatusOK)
rc := http.NewResponseController(w)
err = rc.SetWriteDeadline(time.Now().Add(streamingResponseWriteTimeout))
if err != nil && h.node.logEnabled(LogLevelTrace) {
h.node.logger.log(newLogEntry(LogLevelTrace, "can't set custom write deadline", map[string]any{"error": err.Error()}))
}
_, err = w.Write([]byte("\r\n"))
if err != nil {
return
}
_ = rc.Flush()
_ = rc.SetWriteDeadline(time.Time{})
reader := readerpool.GetBytesReader(requestData)
_ = HandleReadFrame(c, reader, int64(messageSizeLimit))
readerpool.PutBytesReader(reader)
sendAck := func() {
select {
case ack <- struct{}{}:
case <-r.Context().Done():
}
}
for {
select {
case <-r.Context().Done():
return
case <-transport.disconnectCh:
return
case messages, messagesOK := <-transport.messages:
if !messagesOK {
sendAck()
return
}
_ = rc.SetWriteDeadline(time.Now().Add(streamingResponseWriteTimeout))
for _, msg := range messages {
_, err := w.Write(convert.StringToBytes("data: " + convert.BytesToString(msg) + "\n\n"))
if err != nil {
sendAck()
return
}
}
_ = rc.Flush()
_ = rc.SetWriteDeadline(time.Time{})
sendAck()
}
}
}
const (
transportSSE = "sse"
)
type sseTransport struct {
mu sync.Mutex
req *http.Request
ack chan struct{}
messages chan [][]byte
disconnectCh chan struct{}
closedCh chan struct{}
config sseTransportConfig
closed bool
}
type sseTransportConfig struct {
pingPong PingPongConfig
protoMajor uint8
}
func newSSETransport(req *http.Request, config sseTransportConfig, ack chan struct{}) *sseTransport {
return &sseTransport{
messages: make(chan [][]byte),
disconnectCh: make(chan struct{}),
closedCh: make(chan struct{}),
req: req,
config: config,
ack: ack,
}
}
func (t *sseTransport) Name() string {
return transportSSE
}
func (t *sseTransport) AcceptProtocol() string {
return getAcceptProtocolLabel(int8(t.config.protoMajor))
}
func (t *sseTransport) Protocol() ProtocolType {
return ProtocolTypeJSON
}
// ProtocolVersion returns transport protocol version.
func (t *sseTransport) ProtocolVersion() ProtocolVersion {
return ProtocolVersion2
}
// Unidirectional returns whether transport is unidirectional.
func (t *sseTransport) Unidirectional() bool {
return false
}
// Emulation ...
func (t *sseTransport) Emulation() bool {
return true
}
// DisabledPushFlags ...
func (t *sseTransport) DisabledPushFlags() uint64 {
return 0
}
// PingPongConfig ...
func (t *sseTransport) PingPongConfig() PingPongConfig {
return t.config.pingPong
}
func (t *sseTransport) Write(message []byte) error {
return t.WriteMany(message)
}
func (t *sseTransport) WriteMany(messages ...[]byte) error {
t.mu.Lock()
defer t.mu.Unlock()
if t.closed {
return nil
}
select {
case t.messages <- messages:
case <-t.closedCh:
}
select {
case <-t.ack:
case <-t.closedCh:
return nil
}
return nil
}
func (t *sseTransport) Close(_ Disconnect) error {
t.mu.Lock()
defer t.mu.Unlock()
if t.closed {
return nil
}
t.closed = true
close(t.disconnectCh)
<-t.closedCh
return nil
}