Debian Codegraph @

simulation_test.go

raw symbols SCIP
1 package bolt_test
2
3 import (
4 "bytes"
5 "fmt"
6 "math/rand"
7 "sync"
8 "testing"
9
10 "github.com/NebulousLabs/bolt"
11 )
12
13 func TestSimulate_1op_1p(t *testing.T) { testSimulate(t, 1, 1) }
14 func TestSimulate_10op_1p(t *testing.T) { testSimulate(t, 10, 1) }
15 func TestSimulate_100op_1p(t *testing.T) { testSimulate(t, 100, 1) }
16 func TestSimulate_1000op_1p(t *testing.T) { testSimulate(t, 1000, 1) }
17 func TestSimulate_10000op_1p(t *testing.T) { testSimulate(t, 10000, 1) }
18
19 func TestSimulate_10op_10p(t *testing.T) { testSimulate(t, 10, 10) }
20 func TestSimulate_100op_10p(t *testing.T) { testSimulate(t, 100, 10) }
21 func TestSimulate_1000op_10p(t *testing.T) { testSimulate(t, 1000, 10) }
22 func TestSimulate_10000op_10p(t *testing.T) { testSimulate(t, 10000, 10) }
23
24 func TestSimulate_100op_100p(t *testing.T) { testSimulate(t, 100, 100) }
25 func TestSimulate_1000op_100p(t *testing.T) { testSimulate(t, 1000, 100) }
26 func TestSimulate_10000op_100p(t *testing.T) { testSimulate(t, 10000, 100) }
27
28 func TestSimulate_10000op_1000p(t *testing.T) { testSimulate(t, 10000, 1000) }
29
30 // Randomly generate operations on a given database with multiple clients to ensure consistency and thread safety.
31 func testSimulate(t *testing.T, threadCount, parallelism int) {
32 if testing.Short() {
33 t.Skip("skipping test in short mode.")
34 }
35
36 rand.Seed(int64(qseed))
37
38 // A list of operations that readers and writers can perform.
39 var readerHandlers = []simulateHandler{simulateGetHandler}
40 var writerHandlers = []simulateHandler{simulateGetHandler, simulatePutHandler}
41
42 var versions = make(map[int]*QuickDB)
43 versions[1] = NewQuickDB()
44
45 db := MustOpenDB()
46 defer db.MustClose()
47
48 var mutex sync.Mutex
49
50 // Run n threads in parallel, each with their own operation.
51 var wg sync.WaitGroup
52 var threads = make(chan bool, parallelism)
53 var i int
54 for {
55 threads <- true
56 wg.Add(1)
57 writable := ((rand.Int() % 100) < 20) // 20% writers
58
59 // Choose an operation to execute.
60 var handler simulateHandler
61 if writable {
62 handler = writerHandlers[rand.Intn(len(writerHandlers))]
63 } else {
64 handler = readerHandlers[rand.Intn(len(readerHandlers))]
65 }
66
67 // Execute a thread for the given operation.
68 go func(writable bool, handler simulateHandler) {
69 defer wg.Done()
70
71 // Start transaction.
72 tx, err := db.Begin(writable)
73 if err != nil {
74 t.Fatal("tx begin: ", err)
75 }
76
77 // Obtain current state of the dataset.
78 mutex.Lock()
79 var qdb = versions[tx.ID()]
80 if writable {
81 qdb = versions[tx.ID()-1].Copy()
82 }
83 mutex.Unlock()
84
85 // Make sure we commit/rollback the tx at the end and update the state.
86 if writable {
87 defer func() {
88 mutex.Lock()
89 versions[tx.ID()] = qdb
90 mutex.Unlock()
91
92 if err := tx.Commit(); err != nil {
93 t.Fatal(err)
94 }
95 }()
96 } else {
97 defer func() { _ = tx.Rollback() }()
98 }
99
100 // Ignore operation if we don't have data yet.
101 if qdb == nil {
102 return
103 }
104
105 // Execute handler.
106 handler(tx, qdb)
107
108 // Release a thread back to the scheduling loop.
109 <-threads
110 }(writable, handler)
111
112 i++
113 if i > threadCount {
114 break
115 }
116 }
117
118 // Wait until all threads are done.
119 wg.Wait()
120 }
121
122 type simulateHandler func(tx *bolt.Tx, qdb *QuickDB)
123
124 // Retrieves a key from the database and verifies that it is what is expected.
125 func simulateGetHandler(tx *bolt.Tx, qdb *QuickDB) {
126 // Randomly retrieve an existing exist.
127 keys := qdb.Rand()
128 if len(keys) == 0 {
129 return
130 }
131
132 // Retrieve root bucket.
133 b := tx.Bucket(keys[0])
134 if b == nil {
135 panic(fmt.Sprintf("bucket[0] expected: %08x\n", trunc(keys[0], 4)))
136 }
137
138 // Drill into nested buckets.
139 for _, key := range keys[1 : len(keys)-1] {
140 b = b.Bucket(key)
141 if b == nil {
142 panic(fmt.Sprintf("bucket[n] expected: %v -> %v\n", keys, key))
143 }
144 }
145
146 // Verify key/value on the final bucket.
147 expected := qdb.Get(keys)
148 actual := b.Get(keys[len(keys)-1])
149 if !bytes.Equal(actual, expected) {
150 fmt.Println("=== EXPECTED ===")
151 fmt.Println(expected)
152 fmt.Println("=== ACTUAL ===")
153 fmt.Println(actual)
154 fmt.Println("=== END ===")
155 panic("value mismatch")
156 }
157 }
158
159 // Inserts a key into the database.
160 func simulatePutHandler(tx *bolt.Tx, qdb *QuickDB) {
161 var err error
162 keys, value := randKeys(), randValue()
163
164 // Retrieve root bucket.
165 b := tx.Bucket(keys[0])
166 if b == nil {
167 b, err = tx.CreateBucket(keys[0])
168 if err != nil {
169 panic("create bucket: " + err.Error())
170 }
171 }
172
173 // Create nested buckets, if necessary.
174 for _, key := range keys[1 : len(keys)-1] {
175 child := b.Bucket(key)
176 if child != nil {
177 b = child
178 } else {
179 b, err = b.CreateBucket(key)
180 if err != nil {
181 panic("create bucket: " + err.Error())
182 }
183 }
184 }
185
186 // Insert into database.
187 if err := b.Put(keys[len(keys)-1], value); err != nil {
188 panic("put: " + err.Error())
189 }
190
191 // Insert into in-memory database.
192 qdb.Put(keys, value)
193 }
194
195 // QuickDB is an in-memory database that replicates the functionality of the
196 // Bolt DB type except that it is entirely in-memory. It is meant for testing
197 // that the Bolt database is consistent.
198 type QuickDB struct {
199 sync.RWMutex
200 m map[string]interface{}
201 }
202
203 // NewQuickDB returns an instance of QuickDB.
204 func NewQuickDB() *QuickDB {
205 return &QuickDB{m: make(map[string]interface{})}
206 }
207
208 // Get retrieves the value at a key path.
209 func (db *QuickDB) Get(keys [][]byte) []byte {
210 db.RLock()
211 defer db.RUnlock()
212
213 m := db.m
214 for _, key := range keys[:len(keys)-1] {
215 value := m[string(key)]
216 if value == nil {
217 return nil
218 }
219 switch value := value.(type) {
220 case map[string]interface{}:
221 m = value
222 case []byte:
223 return nil
224 }
225 }
226
227 // Only return if it's a simple value.
228 if value, ok := m[string(keys[len(keys)-1])].([]byte); ok {
229 return value
230 }
231 return nil
232 }
233
234 // Put inserts a value into a key path.
235 func (db *QuickDB) Put(keys [][]byte, value []byte) {
236 db.Lock()
237 defer db.Unlock()
238
239 // Build buckets all the way down the key path.
240 m := db.m
241 for _, key := range keys[:len(keys)-1] {
242 if _, ok := m[string(key)].([]byte); ok {
243 return // Keypath intersects with a simple value. Do nothing.
244 }
245
246 if m[string(key)] == nil {
247 m[string(key)] = make(map[string]interface{})
248 }
249 m = m[string(key)].(map[string]interface{})
250 }
251
252 // Insert value into the last key.
253 m[string(keys[len(keys)-1])] = value
254 }
255
256 // Rand returns a random key path that points to a simple value.
257 func (db *QuickDB) Rand() [][]byte {
258 db.RLock()
259 defer db.RUnlock()
260 if len(db.m) == 0 {
261 return nil
262 }
263 var keys [][]byte
264 db.rand(db.m, &keys)
265 return keys
266 }
267
268 func (db *QuickDB) rand(m map[string]interface{}, keys *[][]byte) {
269 i, index := 0, rand.Intn(len(m))
270 for k, v := range m {
271 if i == index {
272 *keys = append(*keys, []byte(k))
273 if v, ok := v.(map[string]interface{}); ok {
274 db.rand(v, keys)
275 }
276 return
277 }
278 i++
279 }
280 panic("quickdb rand: out-of-range")
281 }
282
283 // Copy copies the entire database.
284 func (db *QuickDB) Copy() *QuickDB {
285 db.RLock()
286 defer db.RUnlock()
287 return &QuickDB{m: db.copy(db.m)}
288 }
289
290 func (db *QuickDB) copy(m map[string]interface{}) map[string]interface{} {
291 clone := make(map[string]interface{}, len(m))
292 for k, v := range m {
293 switch v := v.(type) {
294 case map[string]interface{}:
295 clone[k] = db.copy(v)
296 default:
297 clone[k] = v
298 }
299 }
300 return clone
301 }
302
303 func randKey() []byte {
304 var min, max = 1, 1024
305 n := rand.Intn(max-min) + min
306 b := make([]byte, n)
307 for i := 0; i < n; i++ {
308 b[i] = byte(rand.Intn(255))
309 }
310 return b
311 }
312
313 func randKeys() [][]byte {
314 var keys [][]byte
315 var count = rand.Intn(2) + 2
316 for i := 0; i < count; i++ {
317 keys = append(keys, randKey())
318 }
319 return keys
320 }
321
322 func randValue() []byte {
323 n := rand.Intn(8192)
324 b := make([]byte, n)
325 for i := 0; i < n; i++ {
326 b[i] = byte(rand.Intn(255))
327 }
328 return b
329 }