-
-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathhandler_http_stream.go
More file actions
281 lines (248 loc) · 7.27 KB
/
Copy pathhandler_http_stream.go
File metadata and controls
281 lines (248 loc) · 7.27 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
271
272
273
274
275
276
277
278
279
280
281
package centrifuge
import (
"errors"
"io"
"net/http"
"sync"
"time"
"github.com/centrifugal/centrifuge/internal/readerpool"
"github.com/centrifugal/protocol"
)
// HTTPStreamConfig represents config for HTTPStreamHandler.
type HTTPStreamConfig struct {
PingPongConfig
// MaxRequestBodySize limits request body size.
MaxRequestBodySize int
}
// HTTPStreamHandler handles WebSocket client connections. WebSocket protocol
// is a bidirectional connection between a client and a server for low-latency
// communication.
type HTTPStreamHandler struct {
node *Node
config HTTPStreamConfig
}
// NewHTTPStreamHandler creates new HTTPStreamHandler.
func NewHTTPStreamHandler(node *Node, config HTTPStreamConfig) *HTTPStreamHandler {
warnAboutIncorrectPingPongConfig(node, config.PingPongConfig, transportHTTPStream)
return &HTTPStreamHandler{
node: node,
config: config,
}
}
const (
defaultMaxHTTPStreamingBodySize = 64 * 1024
streamingResponseWriteTimeout = time.Second
statusCodeClientConnectionClosed = 499
)
func (h *HTTPStreamHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodOptions { // For pre-flight browser requests.
w.Header().Set("Access-Control-Max-Age", "300")
w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
w.WriteHeader(http.StatusNoContent)
return
}
_, ok := w.(http.Flusher)
if !ok {
h.node.logger.log(newErrorLogEntry(errors.New("not http.Flusher"), "HTTP stream: ResponseWriter is not a Flusher", map[string]any{}))
http.Error(w, "expected http.ResponseWriter to be http.Flusher", http.StatusInternalServerError)
return
}
protocolType := ProtocolTypeJSON
if r.Header.Get("Content-Type") == "application/octet-stream" {
protocolType = ProtocolTypeProtobuf
}
var requestData []byte
if r.Method == http.MethodPost {
maxBytesSize := h.config.MaxRequestBodySize
if maxBytesSize == 0 {
maxBytesSize = defaultMaxHTTPStreamingBodySize
}
r.Body = http.MaxBytesReader(w, r.Body, int64(maxBytesSize))
var err error
requestData, err = io.ReadAll(r.Body)
if err != nil {
h.node.logger.log(newLogEntry(LogLevelInfo, "error reading http stream request body", map[string]any{"error": err.Error()}))
if len(requestData) >= maxBytesSize {
w.WriteHeader(http.StatusRequestEntityTooLarge)
return
}
w.WriteHeader(statusCodeClientConnectionClosed)
return
}
} else {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
ack := make(chan struct{})
transport := newHTTPStreamTransport(r, httpStreamTransportConfig{
protocolType: protocolType,
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": transportHTTPStream}))
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": transportHTTPStream, "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": transportHTTPStream, "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("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)
reader := readerpool.GetBytesReader(requestData)
_ = HandleReadFrame(c, reader)
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
}
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()}))
}
if protocolType == ProtocolTypeProtobuf {
encoder := protocol.GetDataEncoder(protocolType.toProto())
for _, message := range messages {
_ = encoder.Encode(message)
}
_, err := w.Write(encoder.Finish())
if err != nil {
sendAck()
return
}
protocol.PutDataEncoder(protocolType.toProto(), encoder)
} else {
for _, message := range messages {
_, err = w.Write(message)
if err != nil {
sendAck()
return
}
_, err = w.Write([]byte("\n"))
if err != nil {
sendAck()
return
}
}
}
_ = rc.Flush()
_ = rc.SetWriteDeadline(time.Time{})
sendAck()
}
}
}
const (
transportHTTPStream = "http_stream"
)
type httpStreamTransport struct {
mu sync.Mutex
req *http.Request
ack chan struct{}
messages chan [][]byte
disconnectCh chan struct{}
closedCh chan struct{}
closed bool
config httpStreamTransportConfig
}
type httpStreamTransportConfig struct {
protocolType ProtocolType
pingPong PingPongConfig
protoMajor uint8
}
func newHTTPStreamTransport(req *http.Request, config httpStreamTransportConfig, ack chan struct{}) *httpStreamTransport {
return &httpStreamTransport{
messages: make(chan [][]byte),
disconnectCh: make(chan struct{}),
closedCh: make(chan struct{}),
req: req,
config: config,
ack: ack,
}
}
func (t *httpStreamTransport) Name() string {
return transportHTTPStream
}
func (t *httpStreamTransport) AcceptProtocol() string {
return getAcceptProtocolLabel(int8(t.config.protoMajor))
}
func (t *httpStreamTransport) Protocol() ProtocolType {
return t.config.protocolType
}
// ProtocolVersion returns transport protocol version.
func (t *httpStreamTransport) ProtocolVersion() ProtocolVersion {
return ProtocolVersion2
}
// Unidirectional returns whether transport is unidirectional.
func (t *httpStreamTransport) Unidirectional() bool {
return false
}
// Emulation ...
func (t *httpStreamTransport) Emulation() bool {
return true
}
// DisabledPushFlags ...
func (t *httpStreamTransport) DisabledPushFlags() uint64 {
return 0
}
// PingPongConfig ...
func (t *httpStreamTransport) PingPongConfig() PingPongConfig {
return t.config.pingPong
}
func (t *httpStreamTransport) Write(message []byte) error {
return t.WriteMany(message)
}
func (t *httpStreamTransport) 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 *httpStreamTransport) 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
}