-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
collection_test.go
456 lines (400 loc) · 10.3 KB
/
collection_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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// Copyright (c) Roman Atachiants and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
package column
import (
"context"
"encoding/json"
"fmt"
"math"
"math/rand"
"os"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/kelindar/column/commit"
"github.com/stretchr/testify/assert"
)
/*
cpu: Intel(R) Core(TM) i7-9700K CPU @ 3.60GHz
BenchmarkCollection/insert-8 5439637 221.3 ns/op 18 B/op 0 allocs/op
BenchmarkCollection/fetch-8 23985608 48.55 ns/op 0 B/op 0 allocs/op
BenchmarkCollection/scan-8 1845 689796 ns/op 25 B/op 0 allocs/op
BenchmarkCollection/count-8 1000000 1133 ns/op 0 B/op 0 allocs/op
BenchmarkCollection/range-8 10000 107436 ns/op 10 B/op 0 allocs/op
BenchmarkCollection/update-at-8 4171920 286.7 ns/op 0 B/op 0 allocs/op
BenchmarkCollection/update-all-8 837 1312193 ns/op 52392 B/op 0 allocs/op
BenchmarkCollection/delete-at-8 7141628 169.9 ns/op 0 B/op 0 allocs/op
BenchmarkCollection/delete-all-8 189722 6322 ns/op 0 B/op 0 allocs/op
*/
func BenchmarkCollection(b *testing.B) {
amount := 100000
players := loadPlayers(amount)
obj := Object{
"name": "Roman",
"age": 35,
"wallet": 50.99,
"health": 100,
"mana": 200,
}
b.Run("insert", func(b *testing.B) {
col := NewCollection()
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
col.Insert(obj)
if col.Count() >= 1000 {
col = NewCollection()
}
}
})
b.Run("fetch", func(b *testing.B) {
name := ""
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
if s, ok := players.Fetch(20); ok {
name = s.StringAt("name")
}
}
assert.NotEmpty(b, name)
})
b.Run("scan", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
players.Query(func(txn *Txn) error {
txn.WithString("race", func(v string) bool {
return v == "human"
}).WithString("class", func(v string) bool {
return v == "mage"
}).WithFloat("age", func(v float64) bool {
return v >= 30
}).Count()
return nil
})
}
})
b.Run("count", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
players.Query(func(txn *Txn) error {
txn.With("human", "mage", "old").Count()
return nil
})
}
})
b.Run("range", func(b *testing.B) {
count, name := 0, ""
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
players.Query(func(txn *Txn) error {
txn.With("human", "mage", "old").Range("name", func(v Cursor) {
count++
name = v.String()
})
return nil
})
}
assert.NotEmpty(b, name)
})
b.Run("update-at", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
players.UpdateAt(20, "balance", 1.0)
}
})
b.Run("update-all", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
players.Query(func(txn *Txn) error {
txn.Range("balance", func(v Cursor) {
v.Update(1.0)
})
return nil
})
}
})
b.Run("delete-at", func(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
players.DeleteAt(20)
}
})
b.Run("delete-all", func(b *testing.B) {
temp := loadPlayers(amount)
b.ReportAllocs()
b.ResetTimer()
for n := 0; n < b.N; n++ {
temp.Query(func(txn *Txn) error {
txn.DeleteAll()
return nil
})
}
})
}
// Test replication many times
func TestReplicate(t *testing.T) {
for x := 0; x < 20; x++ {
runReplication(t, 5000, 50)
}
}
// runReplication runs a concurrent replication test
func runReplication(t *testing.T, updates, inserts int) {
t.Run(fmt.Sprintf("replicate-%v-%v", updates, inserts), func(t *testing.T) {
writer := make(commit.Channel, 1024)
object := map[string]interface{}{
"float64": float64(0),
"int32": int32(0),
"string": "",
}
// Create a primary
primary := NewCollection(Options{
Capacity: inserts,
Writer: &writer,
})
// Replica with the same schema
replica := NewCollection(Options{
Capacity: inserts,
})
// Create schemas and start streaming replication into the replica
primary.CreateColumnsOf(object)
replica.CreateColumnsOf(object)
var done sync.WaitGroup
go func() {
done.Add(1)
defer done.Done()
for change := range writer {
assert.NoError(t, replica.Replay(change))
}
}()
// Write some objects
for i := 0; i < inserts; i++ {
primary.Insert(object)
}
// Random concurrent updates
var wg sync.WaitGroup
wg.Add(updates)
for i := 0; i < updates; i++ {
go func() {
defer wg.Done()
// Randomly update a column
offset := uint32(rand.Int31n(int32(inserts - 1)))
switch rand.Int31n(3) {
case 0:
primary.UpdateAt(offset, "float64", math.Round(rand.Float64()*1000)/100)
case 1:
primary.UpdateAt(offset, "int32", rand.Int31n(100000))
case 2:
primary.UpdateAt(offset, "string", fmt.Sprintf("hi %v", rand.Int31n(10)))
}
// Randomly delete an item
if rand.Int31n(100) == 0 {
primary.DeleteAt(uint32(rand.Int31n(int32(inserts - 1))))
}
// Randomly insert an item
if rand.Int31n(100) == 0 {
primary.Insert(object)
}
}()
}
// Replay all of the changes into the replica
wg.Wait()
close(writer)
done.Wait()
// Check if replica and primary are the same
assert.Equal(t, primary.Count(), replica.Count())
primary.Query(func(txn *Txn) error {
return txn.Range("float64", func(v Cursor) {
v1, v2 := v.FloatAt("float64"), v.IntAt("int32")
if v1 != 0 {
clone, _ := replica.Fetch(v.idx)
assert.Equal(t, v.FloatAt("float64"), clone.FloatAt("float64"))
}
if v2 != 0 {
clone, _ := replica.Fetch(v.idx)
assert.Equal(t, v.IntAt("int32"), clone.IntAt("int32"))
}
})
})
})
}
func TestCollection(t *testing.T) {
obj := Object{
"name": "Roman",
"age": 35,
"wallet": 50.99,
"health": 100,
"mana": 200,
}
col := NewCollection()
col.CreateColumnsOf(obj)
idx := col.Insert(obj)
// Should not drop, since it's not an index
col.DropIndex("name")
// Create a coupe of indices
assert.Error(t, col.CreateIndex("", "", nil))
assert.NoError(t, col.CreateIndex("rich", "wallet", func(v interface{}) bool {
return v.(float64) > 100
}))
{ // Find the object by its index
v, ok := col.Fetch(idx)
assert.True(t, ok)
assert.Equal(t, "Roman", v.StringAt("name"))
}
{ // Remove the object
col.DeleteAt(idx)
_, ok := col.Fetch(idx)
assert.False(t, ok)
}
{ // Add a new one, should replace
idx := col.Insert(obj)
v, ok := col.Fetch(idx)
assert.True(t, ok)
assert.Equal(t, "Roman", v.StringAt("name"))
}
{ // Update the wallet
col.UpdateAt(0, "wallet", float64(1000))
v, ok := col.Fetch(idx)
assert.True(t, ok)
assert.Equal(t, int64(1000), v.IntAt("wallet"))
assert.Equal(t, true, v.BoolAt("rich"))
}
{ // Drop the colun
col.DropColumn("rich")
col.Query(func(txn *Txn) error {
assert.Equal(t, 0, txn.With("rich").Count())
return nil
})
}
}
func TestExpire(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
obj := Object{
"name": "Roman",
"age": 35,
"wallet": 50.99,
"health": 100,
"mana": 200,
}
col := NewCollection()
col.CreateColumnsOf(obj)
defer col.Close()
// Insert an object
col.InsertWithTTL(obj, time.Microsecond)
col.Query(func(txn *Txn) error {
return txn.Range(expireColumn, func(v Cursor) {
expireAt := time.Unix(0, v.Int())
v.Update(expireAt.Add(1 * time.Microsecond).UnixNano())
})
})
assert.Equal(t, 1, col.Count())
// Perform a cleanup every microsecond for tests
go col.vacuum(ctx, time.Microsecond)
// Wait a bit, should be cleaned up
time.Sleep(100 * time.Millisecond)
assert.Equal(t, 0, col.Count())
}
func TestInsertParallel(t *testing.T) {
obj := Object{
"name": "Roman",
"age": 35,
"wallet": 50.99,
"health": 100,
"mana": 200,
}
col := NewCollection()
var wg sync.WaitGroup
for i := 0; i < 500; i++ {
wg.Add(1)
go func() {
col.Insert(obj)
wg.Done()
}()
}
wg.Wait()
assert.Equal(t, 500, col.Count())
}
// loadPlayers loads a list of players from the fixture
func loadPlayers(amount int) *Collection {
out := NewCollection(Options{
Capacity: amount,
Vacuum: 500 * time.Millisecond,
Writer: new(noopWriter),
})
// index on humans
out.CreateIndex("human", "race", func(v interface{}) bool {
return v == "human"
})
// index on dwarves
out.CreateIndex("dwarf", "race", func(v interface{}) bool {
return v == "dwarf"
})
// index on elves
out.CreateIndex("elf", "race", func(v interface{}) bool {
return v == "elf"
})
// index on orcs
out.CreateIndex("orc", "race", func(v interface{}) bool {
return v == "orc"
})
// index for mages
out.CreateIndex("mage", "class", func(v interface{}) bool {
return v == "mage"
})
// index for old
out.CreateIndex("old", "age", func(v interface{}) bool {
return v.(float64) >= 30
})
// Load the items into the collection
out.CreateColumn("serial", ForAny())
out.CreateColumn("name", ForAny())
out.CreateColumn("active", ForBool())
out.CreateColumn("class", ForEnum())
out.CreateColumn("race", ForEnum())
out.CreateColumn("age", ForFloat64())
out.CreateColumn("hp", ForFloat64())
out.CreateColumn("mp", ForFloat64())
out.CreateColumn("balance", ForFloat64())
out.CreateColumn("gender", ForEnum())
out.CreateColumn("guild", ForEnum())
out.CreateColumn("location", ForAny())
// Load and copy until we reach the amount required
data := loadFixture("players.json")
for i := 0; i < amount/len(data); i++ {
out.Query(func(txn *Txn) error {
for _, p := range data {
txn.Insert(p)
}
return nil
})
}
return out
}
// loadFixture loads a fixture by its name
func loadFixture(name string) []Object {
b, err := os.ReadFile("fixtures/" + name)
if err != nil {
panic(err)
}
var data []Object
if err := json.Unmarshal(b, &data); err != nil {
panic(err)
}
return data
}
// noopWriter is a writer that simply counts the commits
type noopWriter struct {
commits uint64
}
// Write clones the commit and writes it into the writer
func (w *noopWriter) Write(commit commit.Commit) error {
atomic.AddUint64(&w.commits, 1)
return nil
}