-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathqed_test.go
295 lines (263 loc) · 5.96 KB
/
qed_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
package qed
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/docker/go-connections/nat"
_ "github.com/lib/pq"
"io"
"math/rand"
"os"
"strconv"
"strings"
"sync"
"testing"
"time"
)
const (
PostgresImage = "postgres:14.3"
)
// setupPostgres starts a new dockerized PostgreSQL instance, applies project
// schema migrations and returns a handle to the database.
func setupPostgres(t *testing.T) (*sql.DB, func(), error) {
cli, err := client.NewClientWithOpts(
client.FromEnv,
client.WithAPIVersionNegotiation())
if err != nil {
return nil, nil, err
}
ctx := context.Background()
out, err := cli.ImagePull(ctx, PostgresImage, types.ImagePullOptions{})
if err != nil {
return nil, nil, err
}
defer out.Close()
io.Copy(os.Stdout, out)
port := "5432"
password := "password"
database := "postgres"
resp, err := cli.ContainerCreate(
ctx,
&container.Config{
ExposedPorts: map[nat.Port]struct{}{
nat.Port(port): {},
},
Env: []string{
fmt.Sprintf("POSTGRES_PASSWORD=%s", password),
fmt.Sprintf("POSTGRES_DB=%s", database),
},
Image: PostgresImage,
},
&container.HostConfig{
PortBindings: map[nat.Port][]nat.PortBinding{
nat.Port(port): {
{
HostIP: "localhost",
HostPort: port,
},
},
},
},
nil,
nil,
"")
if err != nil {
return nil, nil, err
}
cleanup := func() {
err := cli.ContainerRemove(
ctx,
resp.ID,
types.ContainerRemoveOptions{Force: true})
if err != nil {
t.Log(err)
}
}
// Start the container.
err = cli.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{})
if err != nil {
cleanup()
return nil, nil, err
}
// Open a new connection to the database.
connStr := fmt.Sprintf(
"host=%s port=%s user=%s password=%s dbname=postgres sslmode=disable",
"localhost",
port,
database,
password,
)
db, err := sql.Open("postgres", connStr)
if err != nil {
cleanup()
return nil, nil, err
}
// Wait for the database to start.
started := false
retryCount := 16
for i := 0; i < retryCount; i++ {
_, err = db.Exec("SELECT 1")
if err != nil {
time.Sleep(time.Second)
continue
}
started = true
break
}
if !started {
// Database failed to start.
cleanup()
return nil, nil, errors.New("failed to start database")
}
// Load the schema.
migration, err := os.ReadFile("database/postgres/schema.sql")
if err != nil {
cleanup()
return nil, nil, err
}
// Apply the schema.
_, err = db.Exec(string(migration))
if err != nil {
cleanup()
return nil, nil, err
}
return db, cleanup, nil
}
func TestNoHandler(t *testing.T) {
db, cleanup, err := setupPostgres(t)
if err != nil {
t.Fatal(err)
}
defer cleanup()
// Create a new queue that will poll every 50 milliseconds.
options := Options{Tick: 50 * time.Millisecond, Timeout: 60 * time.Second}
taskQueue := NewTaskQueue(db, options)
_, err = taskQueue.QueueTask("foo", nil)
if err != nil {
t.Fatal(err)
}
err = taskQueue.Run()
if err == nil {
t.Fatal("task run without handler")
}
if !strings.Contains(err.Error(), "foo") {
t.Fatal("expected queue name in error message")
}
}
func TestSimpleTasks(t *testing.T) {
db, cleanup, err := setupPostgres(t)
if err != nil {
t.Fatal(err)
}
defer cleanup()
// Create a new queue that will poll every 50 milliseconds.
options := Options{Tick: 50 * time.Millisecond, Timeout: 60 * time.Second}
taskQueue := NewTaskQueue(db, options)
// Task handler sets the appropriate array item to done.
mutex := sync.Mutex{}
items := make(map[string]string)
handler := func(data []byte) error {
mutex.Lock()
defer mutex.Unlock()
items[string(data)] = string(data) + "foo"
return nil
}
// Register the handler.
taskQueue.RegisterHandler("test", handler)
// Start the task queue
go func() {
err = taskQueue.Run()
if err != nil {
t.Log(err)
}
}()
// Register tasks.
for i := 0; i < 64; i++ {
delay := time.Duration(rand.Int63n(60)) * time.Second
err = taskQueue.QueueTaskWithDelay("test", []byte(strconv.Itoa(i)), delay)
if err != nil {
t.Fatal(err)
}
}
// Wait until we have drained all tasks.
for {
remaining, err := taskQueue.size()
if err != nil {
t.Fatal(err)
}
if remaining == 0 {
break
}
time.Sleep(250 * time.Millisecond)
}
// Check we handled each task.
for k, v := range items {
expected := k + "foo"
if v != expected {
t.Fatalf("failed to run task for item %s", k)
}
}
}
func TestExpiredTasks(t *testing.T) {
db, cleanup, err := setupPostgres(t)
if err != nil {
t.Fatal(err)
}
defer cleanup()
// Create a new queue that will poll every 50 milliseconds and reclaim
// tasks that have not been acked after 10 seconds.
options := Options{Tick: 50 * time.Millisecond, Timeout: 10 * time.Second}
taskQueue := NewTaskQueue(db, options)
// Task handler sets the appropriate array item to done. The handler might
// block for longer than the ack timeout.
mutex := sync.Mutex{}
items := make(map[string]string)
handler := func(data []byte) error {
if rand.Float32() < 0.5 {
time.Sleep(15 * time.Second)
}
mutex.Lock()
defer mutex.Unlock()
items[string(data)] = string(data) + "foo"
return nil
}
// Register the handler.
taskQueue.RegisterHandler("test", handler)
// Start the task queue
go func() {
err = taskQueue.Run()
if err != nil {
t.Log(err)
}
}()
// Register tasks.
for i := 0; i < 64; i++ {
delay := time.Duration(rand.Int63n(60)) * time.Second
err = taskQueue.QueueTaskWithDelay("test", []byte(strconv.Itoa(i)), delay)
if err != nil {
t.Fatal(err)
}
}
// Wait until we have drained all tasks.
for {
remaining, err := taskQueue.size()
if err != nil {
t.Fatal(err)
}
if remaining == 0 {
break
}
time.Sleep(250 * time.Millisecond)
}
// Check we handled each task.
for k, v := range items {
expected := k + "foo"
if v != expected {
t.Fatalf("failed to run task for item %s", k)
}
}
}