migrate TTL manager to ds.TxnDatastore.

This commit is contained in:
Raúl Kripalani 2018-09-04 14:30:52 +01:00
parent 1b57c62e3d
commit de573ac1ff

View File

@ -424,22 +424,22 @@ type ttlManager struct {
ctx context.Context ctx context.Context
cancel context.CancelFunc cancel context.CancelFunc
ticker *time.Ticker ticker *time.Ticker
ds ds.Batching ds ds.TxnDatastore
cache cache cache cache
} }
func newTTLManager(parent context.Context, d ds.Datastore, c *cache, tick time.Duration) *ttlManager { func newTTLManager(parent context.Context, d ds.Datastore, c *cache, tick time.Duration) *ttlManager {
ctx, cancel := context.WithCancel(parent) ctx, cancel := context.WithCancel(parent)
batching, ok := d.(ds.Batching) txnDs, ok := d.(ds.TxnDatastore)
if !ok { if !ok {
panic("must construct ttlManager with batching datastore") panic("must construct ttlManager with transactional datastore")
} }
mgr := &ttlManager{ mgr := &ttlManager{
entries: make(map[ds.Key]*ttlEntry), entries: make(map[ds.Key]*ttlEntry),
ctx: ctx, ctx: ctx,
cancel: cancel, cancel: cancel,
ticker: time.NewTicker(tick), ticker: time.NewTicker(tick),
ds: batching, ds: txnDs,
cache: *c, cache: *c,
} }
@ -463,25 +463,24 @@ func (mgr *ttlManager) tick() {
mgr.Lock() mgr.Lock()
defer mgr.Unlock() defer mgr.Unlock()
txn := mgr.ds.NewTransaction(false)
defer txn.Discard()
now := time.Now() now := time.Now()
batch, err := mgr.ds.Batch()
if err != nil {
log.Error(err)
return
}
for key, entry := range mgr.entries { for key, entry := range mgr.entries {
if entry.ExpiresAt.Before(now) { if entry.ExpiresAt.After(now) {
if err := batch.Delete(key); err != nil { continue
log.Error(err)
} else {
mgr.cache.Remove(key)
} }
if err := txn.Delete(key); err != nil {
log.Error("failed to delete TTL key: %v, cause: %v", key.String(), err)
break
}
mgr.cache.Remove(key)
delete(mgr.entries, key) delete(mgr.entries, key)
} }
}
err = batch.Commit() if err := txn.Commit(); err != nil {
if err != nil { log.Error("failed to commit TTL deletion, cause: %v", err)
log.Error(err)
} }
} }