forked from nsqio/go-nsq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock_test.go
258 lines (226 loc) · 5.76 KB
/
mock_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
package nsq
import (
"bufio"
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"strconv"
"testing"
"time"
)
type instruction struct {
delay time.Duration
frameType int32
body []byte
}
type mockNSQD struct {
script []instruction
got [][]byte
tcpAddr *net.TCPAddr
tcpListener net.Listener
exitChan chan int
}
func newMockNSQD(script []instruction) *mockNSQD {
n := &mockNSQD{
script: script,
exitChan: make(chan int),
}
addr, _ := net.ResolveTCPAddr("tcp", "127.0.0.1:0")
tcpListener, err := net.Listen("tcp", addr.String())
if err != nil {
log.Fatalf("FATAL: listen (%s) failed - %s", n.tcpAddr.String(), err)
}
n.tcpListener = tcpListener
n.tcpAddr = tcpListener.Addr().(*net.TCPAddr)
go n.listen()
return n
}
func (n *mockNSQD) listen() {
log.Printf("TCP: listening on %s", n.tcpListener.Addr().String())
for {
conn, err := n.tcpListener.Accept()
if err != nil {
break
}
go n.handle(conn)
}
log.Printf("TCP: closing %s", n.tcpListener.Addr().String())
close(n.exitChan)
}
func (n *mockNSQD) handle(conn net.Conn) {
var idx int
log.Printf("TCP: new client(%s)", conn.RemoteAddr())
buf := make([]byte, 4)
_, err := io.ReadFull(conn, buf)
if err != nil {
log.Fatalf("ERROR: failed to read protocol version - %s", err)
}
readChan := make(chan []byte)
readDoneChan := make(chan int)
scriptTime := time.After(n.script[0].delay)
rdr := bufio.NewReader(conn)
go func() {
for {
line, err := rdr.ReadBytes('\n')
if err != nil {
return
}
// trim the '\n'
line = line[:len(line)-1]
readChan <- line
<-readDoneChan
}
}()
var rdyCount int
for idx < len(n.script) {
select {
case line := <-readChan:
log.Printf("mock: %s", line)
n.got = append(n.got, line)
params := bytes.Split(line, []byte(" "))
switch {
case bytes.Equal(params[0], []byte("IDENTIFY")):
l := make([]byte, 4)
_, err := io.ReadFull(rdr, l)
if err != nil {
log.Printf(err.Error())
goto exit
}
size := int32(binary.BigEndian.Uint32(l))
b := make([]byte, size)
_, err = io.ReadFull(rdr, b)
if err != nil {
log.Printf(err.Error())
goto exit
}
log.Printf("%s", b)
case bytes.Equal(params[0], []byte("RDY")):
rdy, _ := strconv.Atoi(string(params[1]))
rdyCount = rdy
case bytes.Equal(params[0], []byte("FIN")):
case bytes.Equal(params[0], []byte("REQ")):
}
readDoneChan <- 1
case <-scriptTime:
inst := n.script[idx]
if bytes.Equal(inst.body, []byte("exit")) {
goto exit
}
if inst.frameType == FrameTypeMessage {
if rdyCount == 0 {
log.Printf("!!! RDY == 0")
scriptTime = time.After(n.script[idx+1].delay)
continue
}
rdyCount--
}
_, err := conn.Write(framedResponse(inst.frameType, inst.body))
if err != nil {
log.Printf(err.Error())
goto exit
}
scriptTime = time.After(n.script[idx+1].delay)
idx++
}
}
exit:
n.tcpListener.Close()
}
func framedResponse(frameType int32, data []byte) []byte {
var w bytes.Buffer
beBuf := make([]byte, 4)
size := uint32(len(data)) + 4
binary.BigEndian.PutUint32(beBuf, size)
_, err := w.Write(beBuf)
if err != nil {
return nil
}
binary.BigEndian.PutUint32(beBuf, uint32(frameType))
_, err = w.Write(beBuf)
if err != nil {
return nil
}
_, err = w.Write(data)
return w.Bytes()
}
type testHandler struct{}
func (h *testHandler) HandleMessage(message *Message) error {
if bytes.Equal(message.Body, []byte("bad")) {
return errors.New("bad")
}
return nil
}
func TestReaderBackoff(t *testing.T) {
log.SetOutput(ioutil.Discard)
defer log.SetOutput(os.Stdout)
msgIdGood := MessageID{'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 's', 'd', 'f', 'g', 'h'}
msgGood := NewMessage(msgIdGood, []byte("good"))
msgBytesGood, _ := msgGood.EncodeBytes()
msgIdBad := MessageID{'z', 'x', 'c', 'v', 'b', '6', '7', '8', '9', '0', 'a', 's', 'd', 'f', 'g', 'h'}
msgBad := NewMessage(msgIdBad, []byte("bad"))
msgBytesBad, _ := msgBad.EncodeBytes()
script := []instruction{
// SUB
instruction{0, FrameTypeResponse, []byte("OK")},
// IDENTIFY
instruction{0, FrameTypeResponse, []byte("OK")},
instruction{20 * time.Millisecond, FrameTypeMessage, msgBytesGood},
instruction{20 * time.Millisecond, FrameTypeMessage, msgBytesGood},
instruction{20 * time.Millisecond, FrameTypeMessage, msgBytesGood},
instruction{20 * time.Millisecond, FrameTypeMessage, msgBytesBad},
instruction{20 * time.Millisecond, FrameTypeMessage, msgBytesBad},
instruction{20 * time.Millisecond, FrameTypeMessage, msgBytesGood},
instruction{20 * time.Millisecond, FrameTypeMessage, msgBytesGood},
// needed to exit test
instruction{200 * time.Millisecond, -1, []byte("exit")},
}
n := newMockNSQD(script)
topicName := "test_reader_commands" + strconv.Itoa(int(time.Now().Unix()))
q, _ := NewReader(topicName, "ch")
q.VerboseLogging = true
q.BackoffMultiplier = 10 * time.Millisecond
q.SetMaxInFlight(5)
q.AddHandler(&testHandler{})
err := q.ConnectToNSQ(n.tcpAddr.String())
if err != nil {
t.Fatalf(err.Error())
}
<-n.exitChan
for i, r := range n.got {
log.Printf("%d: %s", i, r)
}
expected := []string{
"IDENTIFY",
"SUB " + topicName + " ch",
"RDY 5",
fmt.Sprintf("FIN %s", msgIdGood),
fmt.Sprintf("FIN %s", msgIdGood),
fmt.Sprintf("FIN %s", msgIdGood),
"RDY 5",
fmt.Sprintf("REQ %s 0", msgIdBad),
"RDY 0",
"RDY 1",
fmt.Sprintf("REQ %s 0", msgIdBad),
"RDY 0",
"RDY 1",
fmt.Sprintf("FIN %s", msgIdGood),
"RDY 0",
"RDY 1",
fmt.Sprintf("FIN %s", msgIdGood),
"RDY 5",
}
if len(n.got) != len(expected) {
t.Fatalf("we got %d commands > %d expected", len(n.got), len(expected))
}
for i, r := range n.got {
if string(r) != expected[i] {
t.Fatalf("cmd %d bad %s != %s", i, r, expected[i])
}
}
}