Skip to content

Commit

Permalink
bugfix: Use rounding to calculate TTL
Browse files Browse the repository at this point in the history
The previous code calculated TTL directly by int64 / time.Second or int64 / time.Millisecond, which could result in a calculation error of up to 1s/1ms. Now, using math.Round ensures that TTL is rounded to the nearest whole second/millisecond, improving the accuracy of the calculation.
  • Loading branch information
xuning888 authored and HDT3213 committed Mar 26, 2024
1 parent b7b8ece commit b6763a8
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions database/keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"github.com/hdt3213/godis/lib/utils"
"github.com/hdt3213/godis/lib/wildcard"
"github.com/hdt3213/godis/redis/protocol"
"math"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -274,8 +275,8 @@ func execTTL(db *DB, args [][]byte) redis.Reply {
return protocol.MakeIntReply(-1)
}
expireTime, _ := raw.(time.Time)
ttl := expireTime.Sub(time.Now())
return protocol.MakeIntReply(int64(ttl / time.Second))
ttl := expireTime.Sub(time.Now()).Seconds()
return protocol.MakeIntReply(int64(math.Round(ttl)))
}

// execPTTL returns a key's time to live in milliseconds
Expand All @@ -291,8 +292,8 @@ func execPTTL(db *DB, args [][]byte) redis.Reply {
return protocol.MakeIntReply(-1)
}
expireTime, _ := raw.(time.Time)
ttl := expireTime.Sub(time.Now())
return protocol.MakeIntReply(int64(ttl / time.Millisecond))
ttl := expireTime.Sub(time.Now()).Milliseconds()
return protocol.MakeIntReply(int64(math.Round(float64(ttl))))
}

// execPersist removes expiration from a key
Expand Down

0 comments on commit b6763a8

Please sign in to comment.