2018-05-17 17:24:00 +00:00
|
|
|
package mailserver
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/ethereum/go-ethereum/common"
|
|
|
|
"github.com/syndtr/goleveldb/leveldb"
|
|
|
|
"github.com/syndtr/goleveldb/leveldb/iterator"
|
|
|
|
"github.com/syndtr/goleveldb/leveldb/util"
|
|
|
|
)
|
|
|
|
|
|
|
|
const batchSize = 1000
|
|
|
|
|
|
|
|
// Cleaner removes old messages from a db
|
|
|
|
type Cleaner struct {
|
2018-06-27 12:22:09 +00:00
|
|
|
db dbImpl
|
2018-05-17 17:24:00 +00:00
|
|
|
batchSize int
|
|
|
|
}
|
|
|
|
|
|
|
|
// NewCleanerWithDB returns a new Cleaner for db
|
2018-06-27 12:22:09 +00:00
|
|
|
func NewCleanerWithDB(db dbImpl) *Cleaner {
|
2018-05-17 17:24:00 +00:00
|
|
|
return &Cleaner{
|
|
|
|
db: db,
|
|
|
|
batchSize: batchSize,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Prune removes messages sent between lower and upper timestamps and returns how many has been removed
|
|
|
|
func (c *Cleaner) Prune(lower, upper uint32) (int, error) {
|
|
|
|
var zero common.Hash
|
2018-12-11 10:23:47 +00:00
|
|
|
kl := NewDBKey(lower, zero)
|
|
|
|
ku := NewDBKey(upper, zero)
|
|
|
|
i := c.db.NewIterator(&util.Range{Start: kl.Bytes(), Limit: ku.Bytes()}, nil)
|
2018-05-17 17:24:00 +00:00
|
|
|
defer i.Release()
|
|
|
|
|
|
|
|
return c.prune(i)
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *Cleaner) prune(i iterator.Iterator) (int, error) {
|
|
|
|
batch := leveldb.Batch{}
|
|
|
|
removed := 0
|
|
|
|
|
|
|
|
for i.Next() {
|
|
|
|
batch.Delete(i.Key())
|
|
|
|
|
|
|
|
if batch.Len() == c.batchSize {
|
|
|
|
if err := c.db.Write(&batch, nil); err != nil {
|
|
|
|
return removed, err
|
|
|
|
}
|
|
|
|
|
|
|
|
removed = removed + batch.Len()
|
|
|
|
batch.Reset()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if batch.Len() > 0 {
|
|
|
|
if err := c.db.Write(&batch, nil); err != nil {
|
|
|
|
return removed, err
|
|
|
|
}
|
|
|
|
|
|
|
|
removed = removed + batch.Len()
|
|
|
|
}
|
|
|
|
|
|
|
|
return removed, nil
|
|
|
|
}
|