Skip to content

Instantly share code, notes, and snippets.

@rumtid
Last active October 8, 2021 05:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rumtid/925539b3623f2a54d01960af028bd497 to your computer and use it in GitHub Desktop.
Save rumtid/925539b3623f2a54d01960af028bd497 to your computer and use it in GitHub Desktop.
An example that crashes BadgerDB (fixed)
package main
import (
"log"
"math/rand"
"time"
"github.com/dgraph-io/badger/v3"
)
const (
ValueThreshold int64 = 1 << 10
// let the value size greater than threshold
MaxValueSize int = 1 << 11
)
func main() {
rand.Seed(time.Now().UnixNano())
for i := 0; i < 100; i++ {
opts := badger.DefaultOptions("tmp/badger")
opts = opts.WithValueThreshold(ValueThreshold)
db, err := badger.Open(opts)
if err != nil {
log.Fatalln(err)
}
populate(db)
if err := db.Close(); err != nil {
log.Fatalln(err)
}
time.Sleep(time.Second * 2)
}
}
func populate(db *badger.DB) {
wb := db.NewWriteBatch()
defer wb.Cancel()
for i := 0; i < 10000; i++ {
err := wb.Set(randBytes(128), randBytes(MaxValueSize))
if err != nil {
log.Fatalln(err)
}
}
err := wb.Flush()
if err != nil {
log.Fatalln(err)
}
}
func randBytes(n int) []byte {
data := make([]byte, rand.Intn(n)+1)
for i := range data {
data[i] = byte(rand.Intn(256))
}
return data
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment