-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathtask_test.go
397 lines (358 loc) · 10.2 KB
/
task_test.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
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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package gws
import (
"bufio"
"fmt"
"net"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/lxzan/gws/internal"
"github.com/stretchr/testify/assert"
)
func serveWebSocket(
isServer bool,
config *Config,
session SessionStorage,
netConn net.Conn,
br *bufio.Reader,
handler Event,
compressEnabled bool,
subprotocol string,
pd PermessageDeflate,
) *Conn {
socket := &Conn{
isServer: isServer,
ss: session,
config: config,
conn: netConn,
closed: 0,
br: br,
fh: frameHeader{},
handler: handler,
subprotocol: subprotocol,
writeQueue: workerQueue{maxConcurrency: 1},
readQueue: make(channel, 8),
pd: pd,
}
if compressEnabled {
if isServer {
socket.deflater = new(deflaterPool).initialize(pd, config.ReadMaxPayloadSize).Select()
if pd.ServerContextTakeover {
socket.cpsWindow.initialize(config.cswPool, pd.ServerMaxWindowBits)
}
if pd.ClientContextTakeover {
socket.dpsWindow.initialize(config.dswPool, pd.ClientMaxWindowBits)
}
} else {
socket.deflater = new(deflater).initialize(false, pd, config.ReadMaxPayloadSize)
}
}
return socket
}
func newPeer(serverHandler Event, serverOption *ServerOption, clientHandler Event, clientOption *ClientOption) (server, client *Conn) {
serverOption = initServerOption(serverOption)
clientOption = initClientOption(clientOption)
size := 4096
s, c := net.Pipe()
{
br := bufio.NewReaderSize(s, size)
server = serveWebSocket(true, serverOption.getConfig(), newSmap(), s, br, serverHandler, serverOption.PermessageDeflate.Enabled, "", serverOption.PermessageDeflate)
}
{
br := bufio.NewReaderSize(c, size)
client = serveWebSocket(false, clientOption.getConfig(), newSmap(), c, br, clientHandler, clientOption.PermessageDeflate.Enabled, "", clientOption.PermessageDeflate)
}
return
}
func testCloneBytes(b []byte) []byte {
p := make([]byte, len(b))
copy(p, b)
return p
}
// 测试异步写入
func TestConn_WriteAsync(t *testing.T) {
var as = assert.New(t)
// 关闭压缩
t.Run("plain text", func(t *testing.T) {
var serverHandler = new(webSocketMocker)
var clientHandler = new(webSocketMocker)
var serverOption = &ServerOption{}
var clientOption = &ClientOption{}
server, client := newPeer(serverHandler, serverOption, clientHandler, clientOption)
var listA []string
var listB []string
var count = 128
var wg sync.WaitGroup
wg.Add(count)
clientHandler.onMessage = func(socket *Conn, message *Message) {
listB = append(listB, message.Data.String())
wg.Done()
}
go server.ReadLoop()
go client.ReadLoop()
for i := 0; i < count; i++ {
var n = internal.AlphabetNumeric.Intn(125)
var message = internal.AlphabetNumeric.Generate(n)
listA = append(listA, string(message))
server.WriteAsync(OpcodeText, message, nil)
}
wg.Wait()
as.ElementsMatch(listA, listB)
})
// 开启压缩
t.Run("compressed text", func(t *testing.T) {
var serverHandler = new(webSocketMocker)
var clientHandler = new(webSocketMocker)
var serverOption = &ServerOption{
PermessageDeflate: PermessageDeflate{Enabled: true, Threshold: 1},
}
var clientOption = &ClientOption{
PermessageDeflate: PermessageDeflate{Enabled: true, Threshold: 1},
}
server, client := newPeer(serverHandler, serverOption, clientHandler, clientOption)
var listA []string
var listB []string
const count = 128
var wg sync.WaitGroup
wg.Add(count)
clientHandler.onMessage = func(socket *Conn, message *Message) {
listB = append(listB, message.Data.String())
wg.Done()
}
go server.ReadLoop()
go client.ReadLoop()
go func() {
for i := 0; i < count; i++ {
var n = internal.AlphabetNumeric.Intn(1024)
var message = internal.AlphabetNumeric.Generate(n)
listA = append(listA, string(message))
server.WriteAsync(OpcodeText, message, nil)
}
}()
wg.Wait()
as.ElementsMatch(listA, listB)
})
// 往关闭的连接写数据
t.Run("write to closed conn", func(t *testing.T) {
var serverHandler = new(webSocketMocker)
var clientHandler = new(webSocketMocker)
var serverOption = &ServerOption{}
var clientOption = &ClientOption{}
server, client := newPeer(serverHandler, serverOption, clientHandler, clientOption)
var wg = sync.WaitGroup{}
wg.Add(1)
serverHandler.onClose = func(socket *Conn, err error) {
as.Error(err)
wg.Done()
}
go client.ReadLoop()
go server.ReadLoop()
client.NetConn().Close()
server.WriteAsync(OpcodeText, internal.AlphabetNumeric.Generate(8), nil)
wg.Wait()
})
t.Run("ping/pong", func(t *testing.T) {
var serverHandler = new(webSocketMocker)
var clientHandler = new(webSocketMocker)
var serverOption = &ServerOption{}
var clientOption = &ClientOption{}
server, client := newPeer(serverHandler, serverOption, clientHandler, clientOption)
var wg = sync.WaitGroup{}
wg.Add(4)
serverHandler.onPing = func(socket *Conn, payload []byte) {
wg.Done()
socket.WritePong(nil)
}
serverHandler.onMessage = func(socket *Conn, message *Message) {
if string(message.Bytes()) == "hello" {
wg.Done()
}
}
serverHandler.onClose = func(socket *Conn, err error) {
wg.Done()
}
clientHandler.onPong = func(socket *Conn, payload []byte) {
wg.Done()
}
go server.ReadLoop()
go client.ReadLoop()
client.WritePing(nil)
client.WriteString("hello")
{
var fh = frameHeader{}
var n, _ = fh.GenerateHeader(true, true, false, OpcodeText, 0)
go func() { client.conn.Write(fh[:n]) }()
}
wg.Wait()
})
}
// 测试异步读
func TestReadAsync(t *testing.T) {
var serverHandler = new(webSocketMocker)
var clientHandler = new(webSocketMocker)
var serverOption = &ServerOption{
PermessageDeflate: PermessageDeflate{Enabled: true, Threshold: 512},
ParallelEnabled: true,
}
var clientOption = &ClientOption{
PermessageDeflate: PermessageDeflate{Enabled: true, Threshold: 512},
ParallelEnabled: true,
}
server, client := newPeer(serverHandler, serverOption, clientHandler, clientOption)
var mu = &sync.Mutex{}
var listA []string
var listB []string
const count = 1000
var wg = &sync.WaitGroup{}
wg.Add(count)
clientHandler.onMessage = func(socket *Conn, message *Message) {
mu.Lock()
listB = append(listB, message.Data.String())
mu.Unlock()
wg.Done()
}
go server.ReadLoop()
go client.ReadLoop()
for i := 0; i < count; i++ {
var n = internal.AlphabetNumeric.Intn(1024)
var message = internal.AlphabetNumeric.Generate(n)
listA = append(listA, string(message))
server.WriteMessage(OpcodeText, message)
}
wg.Wait()
assert.ElementsMatch(t, listA, listB)
}
func TestTaskQueue(t *testing.T) {
var as = assert.New(t)
t.Run("", func(t *testing.T) {
var mu = &sync.Mutex{}
var listA []int
var listB []int
var count = 1000
var wg = &sync.WaitGroup{}
wg.Add(count)
var q = newWorkerQueue(8)
for i := 0; i < count; i++ {
listA = append(listA, i)
v := i
q.Push(func() {
defer wg.Done()
var latency = time.Duration(internal.AlphabetNumeric.Intn(100)) * time.Microsecond
time.Sleep(latency)
mu.Lock()
listB = append(listB, v)
mu.Unlock()
})
}
wg.Wait()
as.ElementsMatch(listA, listB)
})
t.Run("", func(t *testing.T) {
sum := int64(0)
w := newWorkerQueue(8)
var wg = &sync.WaitGroup{}
wg.Add(1000)
for i := int64(1); i <= 1000; i++ {
var tmp = i
w.Push(func() {
time.Sleep(time.Millisecond)
atomic.AddInt64(&sum, tmp)
wg.Done()
})
}
wg.Wait()
as.Equal(sum, int64(500500))
})
t.Run("", func(t *testing.T) {
sum := int64(0)
w := newWorkerQueue(1)
var wg = &sync.WaitGroup{}
wg.Add(1000)
for i := int64(1); i <= 1000; i++ {
var tmp = i
w.Push(func() {
time.Sleep(time.Millisecond)
atomic.AddInt64(&sum, tmp)
wg.Done()
})
}
wg.Wait()
as.Equal(sum, int64(500500))
})
}
func TestWriteAsyncBlocking(t *testing.T) {
var handler = new(webSocketMocker)
var upgrader = NewUpgrader(handler, nil)
allConns := map[*Conn]struct{}{}
for i := 0; i < 3; i++ {
svrConn, cliConn := net.Pipe() // no reading from another side
var sbrw = bufio.NewReader(svrConn)
var svrSocket = serveWebSocket(true, upgrader.option.getConfig(), newSmap(), svrConn, sbrw, handler, false, "", PermessageDeflate{})
go svrSocket.ReadLoop()
var cbrw = bufio.NewReader(cliConn)
var cliSocket = serveWebSocket(false, upgrader.option.getConfig(), newSmap(), cliConn, cbrw, handler, false, "", PermessageDeflate{})
if i == 0 { // client 0 1s后再开始读取;1s内不读取消息,则svrSocket 0在发送chan取出一个msg进行writePublic时即开始阻塞
time.AfterFunc(time.Second, func() {
cliSocket.ReadLoop()
})
} else {
go cliSocket.ReadLoop()
}
allConns[svrSocket] = struct{}{}
}
// 第一个msg被异步协程从chan取出了,取出后阻塞在writePublic、没有后续的取出,再入defaultAsyncIOGoLimit个msg到chan里,
// 则defaultAsyncIOGoLimit+2个消息会导致入chan阻塞。
// 1s后client 0开始读取,广播才会继续,这一轮对应的时间约为1s
for i := 0; i <= defaultParallelGolimit+2; i++ {
t0 := time.Now()
for wsConn := range allConns {
wsConn.WriteAsync(OpcodeBinary, []byte{0}, nil)
}
fmt.Printf("broadcast %d, used: %v\n", i, time.Since(t0).Nanoseconds())
}
time.Sleep(time.Second * 2)
}
func TestRQueue(t *testing.T) {
t.Run("", func(t *testing.T) {
const total = 1000
const limit = 8
var q = make(channel, limit)
var concurrency = int64(0)
var serial = int64(0)
var done = make(chan struct{})
for i := 0; i < total; i++ {
q.Go(nil, func(message *Message) error {
x := atomic.AddInt64(&concurrency, 1)
assert.LessOrEqual(t, x, int64(limit))
time.Sleep(10 * time.Millisecond)
atomic.AddInt64(&concurrency, -1)
if atomic.AddInt64(&serial, 1) == total {
done <- struct{}{}
}
return nil
})
}
<-done
})
t.Run("", func(t *testing.T) {
const total = 1000
const limit = 8
var q = newWorkerQueue(limit)
var concurrency = int64(0)
var serial = int64(0)
var done = make(chan struct{})
for i := 0; i < total; i++ {
q.Push(func() {
x := atomic.AddInt64(&concurrency, 1)
assert.LessOrEqual(t, x, int64(limit))
time.Sleep(10 * time.Millisecond)
atomic.AddInt64(&concurrency, -1)
if atomic.AddInt64(&serial, 1) == total {
done <- struct{}{}
}
})
}
<-done
})
}