-
-
Notifications
You must be signed in to change notification settings - Fork 121
Expand file tree
/
Copy pathhandler_sse_test.go
More file actions
277 lines (239 loc) · 7.6 KB
/
Copy pathhandler_sse_test.go
File metadata and controls
277 lines (239 loc) · 7.6 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
package centrifuge
import (
"bufio"
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"testing"
"time"
"github.com/centrifugal/protocol"
"github.com/stretchr/testify/require"
)
func TestSSEHandler_GET(t *testing.T) {
t.Parallel()
n, _ := New(Config{
LogLevel: LogLevelDebug,
})
n.OnConnecting(func(ctx context.Context, event ConnectEvent) (ConnectReply, error) {
return ConnectReply{Credentials: &Credentials{
UserID: "test",
}}, nil
})
require.NoError(t, n.Run())
defer func() { _ = n.Shutdown(context.Background()) }()
mux := http.NewServeMux()
mux.Handle("/connection/sse", NewSSEHandler(n, SSEConfig{}))
server := httptest.NewServer(mux)
defer server.Close()
client := &http.Client{Timeout: 5 * time.Second}
command := &protocol.Command{
Id: 1,
Connect: &protocol.ConnectRequest{},
}
jsonData, err := json.Marshal(command)
require.NoError(t, err)
netURL, err := url.Parse(server.URL + "/connection/sse")
require.NoError(t, err)
// Test bad request without connect param.
req, err := http.NewRequest(http.MethodGet, netURL.String(), nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
// And OK with connect param.
values := netURL.Query()
values.Add(connectUrlParam, string(jsonData))
netURL.RawQuery = values.Encode()
req, err = http.NewRequest(http.MethodGet, netURL.String(), nil)
require.NoError(t, err)
resp, err = client.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
defer func() { _ = resp.Body.Close() }()
dec := newSSEStreamDecoder(resp.Body)
for {
msg, err := dec.decode()
require.NoError(t, err)
if len(msg.Data) == 0 {
continue
}
var reply protocol.Reply
err = json.Unmarshal(msg.Data, &reply)
require.NoError(t, err)
require.NotNil(t, reply.Connect)
require.Equal(t, uint32(1), reply.Id)
require.NotZero(t, reply.Connect.Session)
require.NotZero(t, reply.Connect.Node)
break
}
}
func TestSSEHandler_POST(t *testing.T) {
t.Parallel()
n, _ := New(Config{})
n.OnConnecting(func(ctx context.Context, event ConnectEvent) (ConnectReply, error) {
return ConnectReply{Credentials: &Credentials{
UserID: "test",
}}, nil
})
require.NoError(t, n.Run())
defer func() { _ = n.Shutdown(context.Background()) }()
mux := http.NewServeMux()
mux.Handle("/connection/sse", NewSSEHandler(n, SSEConfig{}))
server := httptest.NewServer(mux)
defer server.Close()
client := &http.Client{Timeout: 5 * time.Second}
command := &protocol.Command{
Id: 1,
Connect: &protocol.ConnectRequest{},
}
jsonData, err := json.Marshal(command)
require.NoError(t, err)
req, err := http.NewRequest(http.MethodPost, server.URL+"/connection/sse", bytes.NewBuffer(jsonData))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusOK, resp.StatusCode)
defer func() { _ = resp.Body.Close() }()
dec := newSSEStreamDecoder(resp.Body)
for {
msg, err := dec.decode()
require.NoError(t, err)
if len(msg.Data) == 0 {
continue
}
var reply protocol.Reply
err = json.Unmarshal(msg.Data, &reply)
require.NoError(t, err)
require.NotNil(t, reply.Connect)
require.Equal(t, uint32(1), reply.Id)
require.NotZero(t, reply.Connect.Session)
require.NotZero(t, reply.Connect.Node)
break
}
}
func TestSSEHandler_RequestTooLarge(t *testing.T) {
t.Parallel()
n, _ := New(Config{})
require.NoError(t, n.Run())
defer func() { _ = n.Shutdown(context.Background()) }()
mux := http.NewServeMux()
mux.Handle("/connection/sse", NewSSEHandler(n, SSEConfig{
MaxRequestBodySize: 2,
}))
server := httptest.NewServer(mux)
defer server.Close()
client := &http.Client{Timeout: 5 * time.Second}
command := &protocol.Command{
Id: 1,
Connect: &protocol.ConnectRequest{},
}
jsonData, err := json.Marshal(command)
require.NoError(t, err)
req, err := http.NewRequest(http.MethodPost, server.URL+"/connection/sse", bytes.NewBuffer(jsonData))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusRequestEntityTooLarge, resp.StatusCode)
_ = resp.Body.Close()
}
func TestSSEHandler_UnknownMethod(t *testing.T) {
t.Parallel()
n, _ := New(Config{})
require.NoError(t, n.Run())
defer func() { _ = n.Shutdown(context.Background()) }()
mux := http.NewServeMux()
mux.Handle("/connection/sse", NewSSEHandler(n, SSEConfig{
MaxRequestBodySize: 2,
}))
server := httptest.NewServer(mux)
defer server.Close()
client := &http.Client{Timeout: 5 * time.Second}
command := &protocol.Command{
Id: 1,
Connect: &protocol.ConnectRequest{},
}
jsonData, err := json.Marshal(command)
require.NoError(t, err)
req, err := http.NewRequest(http.MethodPatch, server.URL+"/connection/sse", bytes.NewBuffer(jsonData))
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
require.Equal(t, http.StatusMethodNotAllowed, resp.StatusCode)
_ = resp.Body.Close()
}
// TestSSEHandlerGETMissingConnectParam covers the "no connect command" branch in
// the SSE handler when a GET request lacks the cf_connect query parameter.
func TestSSEHandlerGETMissingConnectParam(t *testing.T) {
t.Parallel()
n, _ := New(Config{LogLevel: LogLevelDebug, LogHandler: func(LogEntry) {}})
require.NoError(t, n.Run())
defer func() { _ = n.Shutdown(context.Background()) }()
mux := http.NewServeMux()
mux.Handle("/connection/sse", NewSSEHandler(n, SSEConfig{}))
server := httptest.NewServer(mux)
defer server.Close()
client := &http.Client{Timeout: 5 * time.Second}
resp, err := client.Get(server.URL + "/connection/sse")
require.NoError(t, err)
require.Equal(t, http.StatusBadRequest, resp.StatusCode)
_ = resp.Body.Close()
}
// TestSSEHandlerNonFlusher verifies the SSE handler returns 500 when the
// ResponseWriter does not implement http.Flusher.
func TestSSEHandlerNonFlusher(t *testing.T) {
t.Parallel()
n, _ := New(Config{LogLevel: LogLevelInfo, LogHandler: func(LogEntry) {}})
require.NoError(t, n.Run())
defer func() { _ = n.Shutdown(context.Background()) }()
h := NewSSEHandler(n, SSEConfig{})
req := httptest.NewRequest(http.MethodGet, "/connection/sse?cf_connect=%7B%7D", nil)
w := newNonFlusherWriter()
h.ServeHTTP(w, req)
require.Equal(t, http.StatusInternalServerError, w.status)
}
// TestSSETransportGetters mirrors the http stream transport getter coverage.
func TestSSETransportGetters(t *testing.T) {
t.Parallel()
req := httptest.NewRequest(http.MethodGet, "/connection/sse", nil)
req.ProtoMajor = 1
transport := newSSETransport(req, sseTransportConfig{
protoMajor: uint8(req.ProtoMajor),
pingPong: PingPongConfig{
PingInterval: 5 * time.Second,
PongTimeout: 3 * time.Second,
},
}, make(chan struct{}))
require.Equal(t, transportSSE, transport.Name())
require.Equal(t, "h1", transport.AcceptProtocol())
require.Equal(t, ProtocolVersion2, transport.ProtocolVersion())
require.Equal(t, ProtocolTypeJSON, transport.Protocol())
require.False(t, transport.Unidirectional())
require.True(t, transport.Emulation())
require.EqualValues(t, 0, transport.DisabledPushFlags())
require.Equal(t, 5*time.Second, transport.PingPongConfig().PingInterval)
}
func newSSEStreamDecoder(body io.Reader) *sseStreamDecoder {
return &sseStreamDecoder{
r: bufio.NewReader(body),
}
}
type sseStreamDecoder struct {
r *bufio.Reader
}
type sseMessage struct {
Data []byte
}
func (d *sseStreamDecoder) decode() (sseMessage, error) {
// Very naive parser for SSE in general, but works for our case.
line, _, err := d.r.ReadLine()
if bytes.HasPrefix(line, []byte("data: ")) {
line = line[6:]
}
return sseMessage{
Data: line,
}, err
}