From b6763a86feb066595a4b1f3821e08442b8e4bd16 Mon Sep 17 00:00:00 2001 From: xuning Date: Sun, 24 Mar 2024 19:18:39 +0800 Subject: [PATCH] bugfix: Use rounding to calculate TTL 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. --- database/keys.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/database/keys.go b/database/keys.go index 245309c5..abdbf422 100644 --- a/database/keys.go +++ b/database/keys.go @@ -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" @@ -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 @@ -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