Skip to content

Commit

Permalink
Add check expirations method.
Browse files Browse the repository at this point in the history
  • Loading branch information
kakaLQY committed Apr 24, 2017
1 parent 218e66c commit 30665be
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 4 deletions.
30 changes: 30 additions & 0 deletions action.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package tdb

import (
"path/filepath"
"time"
)

const (
Expand Down Expand Up @@ -44,6 +45,35 @@ func (db *TDB) GetActions() ([]string, []uint32, []uint32, error) {
return targets, starts, lasts, nil
}

// CheckExpirations to check expired actions
func (db *TDB) CheckExpirations() error {
targets, starts, lasts, err := db.GetActions()
if err != nil {
return err
}

changed := false
now := uint32(time.Now().Unix())

db.action.contentLock.Lock()
for i := 0; i < len(lasts); i++ {
if now-lasts[i] > actionExp {
changed = true
if err := db.AddSlot(targets[i], starts[i], lasts[i]-starts[i]); err != nil {
db.action.contentLock.Unlock()
return err
}
delete(db.action.content, targets[i])
}
}
db.action.contentLock.Unlock()

if changed {
return db.action.writeToDisk()
}
return nil
}

func handleAction(db *TDB, target string, active bool, ts uint32) error {
actions := db.action.content
v := actions[target]
Expand Down
27 changes: 27 additions & 0 deletions action_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ func TestActions(t *testing.T) {
assert.Len(t, targets, 1, "targets count wrong")
assert.Len(t, allStarts, 1, "starts count wrong")
assert.Len(t, allLasts, 1, "lasts count wrong")

testCheckEXP(t, db)
}

func testNormalCloseAction(t *testing.T, db *TDB) {
Expand Down Expand Up @@ -134,3 +136,28 @@ func testLaterActiveAction(t *testing.T, db *TDB) {
assert.Len(t, allStarts, 1, "starts count wrong")
assert.Len(t, allLasts, 1, "lasts count wrong")
}

func testCheckEXP(t *testing.T, db *TDB) {
var keys []string
for k := range db.action.content {
keys = append(keys, k)
}
for i := 0; i < len(keys); i++ {
delete(db.action.content, keys[i])
}

target := string(randBytes(6))
now := uint32(time.Now().Unix())

err := db.AddAction(target, true, now-actionExp-2)
assert.NoError(t, err, "error add an action")

err = db.CheckExpirations()
assert.NoError(t, err, "error check expiration")

targets, allStarts, allLasts, err := db.GetActions()
assert.NoError(t, err, "get all actions wrong")
assert.Len(t, targets, 0, "targets count wrong")
assert.Len(t, allStarts, 0, "starts count wrong")
assert.Len(t, allLasts, 0, "lasts count wrong")
}
8 changes: 4 additions & 4 deletions glide.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 30665be

Please sign in to comment.