2020-11-26 14:26:53 +00:00
|
|
|
package blobovnicza
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/binary"
|
|
|
|
"fmt"
|
2021-06-16 08:58:38 +00:00
|
|
|
"strconv"
|
2020-11-26 14:26:53 +00:00
|
|
|
|
|
|
|
"go.etcd.io/bbolt"
|
|
|
|
)
|
|
|
|
|
|
|
|
const firstBucketBound = uint64(32 * 1 << 10) // 32KB
|
|
|
|
|
|
|
|
func stringifyBounds(lower, upper uint64) string {
|
|
|
|
return fmt.Sprintf("[%s:%s]",
|
|
|
|
stringifyByteSize(lower),
|
|
|
|
stringifyByteSize(upper),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
|
|
|
func stringifyByteSize(sz uint64) string {
|
2021-06-16 08:58:38 +00:00
|
|
|
return strconv.FormatUint(sz, 10)
|
2020-11-26 14:26:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func bucketKeyFromBounds(upperBound uint64) []byte {
|
|
|
|
buf := make([]byte, binary.MaxVarintLen64)
|
|
|
|
|
|
|
|
ln := binary.PutUvarint(buf, upperBound)
|
|
|
|
|
|
|
|
return buf[:ln]
|
|
|
|
}
|
|
|
|
|
|
|
|
func bucketForSize(sz uint64) []byte {
|
2020-12-14 09:25:05 +00:00
|
|
|
return bucketKeyFromBounds(upperPowerOfTwo(sz))
|
|
|
|
}
|
2020-11-26 14:26:53 +00:00
|
|
|
|
2020-12-14 09:25:05 +00:00
|
|
|
func upperPowerOfTwo(v uint64) (upperBound uint64) {
|
|
|
|
for upperBound = firstBucketBound; upperBound < v; upperBound *= 2 {
|
2020-11-26 14:26:53 +00:00
|
|
|
}
|
|
|
|
|
2020-12-14 09:25:05 +00:00
|
|
|
return
|
2020-11-26 14:26:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (b *Blobovnicza) incSize(sz uint64) {
|
|
|
|
b.filled.Add(sz)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b *Blobovnicza) decSize(sz uint64) {
|
|
|
|
b.filled.Sub(sz)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (b *Blobovnicza) full() bool {
|
|
|
|
return b.filled.Load() >= b.fullSizeLimit
|
|
|
|
}
|
|
|
|
|
2021-12-08 10:45:23 +00:00
|
|
|
func (b *Blobovnicza) syncFullnessCounter(tx *bbolt.Tx) error {
|
|
|
|
sz := uint64(0)
|
2020-11-26 14:26:53 +00:00
|
|
|
|
2021-12-08 10:45:23 +00:00
|
|
|
if err := b.iterateBucketKeys(func(lower, upper uint64, key []byte) (bool, error) {
|
|
|
|
buck := tx.Bucket(key)
|
|
|
|
if buck == nil {
|
|
|
|
return false, fmt.Errorf("bucket not found %s", stringifyBounds(lower, upper))
|
2020-11-26 14:26:53 +00:00
|
|
|
}
|
|
|
|
|
2021-12-08 10:50:15 +00:00
|
|
|
sz += uint64(buck.Stats().KeyN) * (upper + lower) / 2
|
2020-11-26 14:26:53 +00:00
|
|
|
|
2021-12-08 10:45:23 +00:00
|
|
|
return false, nil
|
|
|
|
}); err != nil {
|
|
|
|
return err
|
2021-05-18 08:12:51 +00:00
|
|
|
}
|
2021-12-08 10:45:23 +00:00
|
|
|
|
|
|
|
b.filled.Store(sz)
|
|
|
|
|
2021-05-18 08:12:51 +00:00
|
|
|
return nil
|
2020-11-26 14:26:53 +00:00
|
|
|
}
|