From ce54f57f53f1857d51bde6988e98f005db68f1c4 Mon Sep 17 00:00:00 2001 From: Helzoph <50453568+Helzoph@users.noreply.github.com> Date: Thu, 26 Sep 2024 08:46:52 +0800 Subject: [PATCH] feat: Update cache implementation to use Redis for improved performance --- cache/account.go | 88 +++++++++++++++++++++++++---------------------- cache/cache.go | 10 ------ cache/daily.go | 12 ++++--- cache/game.go | 35 ++----------------- cache/savedata.go | 9 ++--- db/game.go | 14 ++------ 6 files changed, 65 insertions(+), 103 deletions(-) diff --git a/cache/account.go b/cache/account.go index 753f074..cf7c6c6 100644 --- a/cache/account.go +++ b/cache/account.go @@ -18,18 +18,20 @@ package cache import ( + "fmt" + "log" "time" ) func AddAccountSession(uuid []byte, token []byte) bool { - rdb.Do("SELECT", sessionDB) - err := rdb.Set(string(token), string(uuid), 7*24*time.Hour).Err() + key := fmt.Sprintf("session:%s", token) + err := rdb.Set(key, string(uuid), 24*time.Hour).Err() return err == nil } func FetchUsernameBySessionToken(token []byte) (string, bool) { - rdb.Do("SELECT", sessionDB) - username, err := rdb.Get(string(token)).Result() + key := fmt.Sprintf("session:%s", token) + username, err := rdb.Get(key).Result() if err != nil { return "", false } @@ -37,40 +39,31 @@ func FetchUsernameBySessionToken(token []byte) (string, bool) { return username, true } -func updateActivePlayers(uuid []byte) bool { - rdb.Do("SELECT", activePlayersDB) - err := rdb.Set(string(uuid), 1, 0).Err() - if err != nil { - return false - } - err = rdb.Expire(string(uuid), 5*time.Minute).Err() - return err == nil -} - func UpdateAccountLastActivity(uuid []byte) bool { - rdb.Do("SELECT", accountsDB) - err := rdb.HSet(string(uuid), "lastActivity", time.Now().Format("2006-01-02 15:04:05")).Err() + key := fmt.Sprintf("account:%s", uuid) + err := rdb.HSet(key, "lastActivity", time.Now().Format("2006-01-02 15:04:05")).Err() if err != nil { return false } - updateActivePlayers(uuid) - + err = rdb.Expire(key, 5*time.Minute).Err() return err == nil } +// FIXME func UpdateAccountStats(uuid []byte, battles, classicSessionsPlayed int) bool { - rdb.Do("SELECT", accountsDB) - err := rdb.HIncrBy(string(uuid), "battles", int64(battles)).Err() + key := fmt.Sprintf("account:%s", uuid) + err := rdb.HIncrBy(key, "battles", int64(battles)).Err() if err != nil { return false } - err = rdb.HIncrBy(string(uuid), "classicSessionsPlayed", int64(classicSessionsPlayed)).Err() + err = rdb.HIncrBy(key, "classicSessionsPlayed", int64(classicSessionsPlayed)).Err() return err == nil } func FetchTrainerIds(uuid []byte) (int, int, bool) { - rdb.Do("SELECT", accountsDB) - vals, err := rdb.HMGet(string(uuid), "trainerId", "secretId").Result() + log.Println("FetchTrainerIds", uuid) + key := fmt.Sprintf("account:%s", uuid) + vals, err := rdb.HMGet(key, "trainerId", "secretId").Result() if err == nil && len(vals) == 2 && vals[0] != nil && vals[1] != nil { trainerId, ok1 := vals[0].(int) secretId, ok2 := vals[1].(int) @@ -83,42 +76,53 @@ func FetchTrainerIds(uuid []byte) (int, int, bool) { } func UpdateTrainerIds(trainerId, secretId int, uuid []byte) bool { - rdb.Do("SELECT", accountsDB) - err := rdb.HMSet(string(uuid), map[string]interface{}{ + key := fmt.Sprintf("account:%s", uuid) + err := rdb.HMSet(key, map[string]interface{}{ "trainerId": trainerId, "secretId": secretId, }).Err() + if err != nil { + return false + } + + err = rdb.Expire(key, 5*time.Minute).Err() return err == nil } func IsActiveSession(uuid []byte, sessionId string) (bool, bool) { - rdb.Do("SELECT", activeClientSessionsDB) - id, err := rdb.Get(string(uuid)).Result() + key := fmt.Sprintf("active_sessions:%s", uuid) + id, err := rdb.Get(key).Result() + return id == sessionId, err == nil +} + +func UpdateActiveSession(uuid []byte, sessionId string) bool { + key := fmt.Sprintf("active_sessions:%s", uuid) + err := rdb.Set(key, sessionId, 0).Err() if err != nil { - return false, false + return false + } + err = rdb.Expire(key, 5*time.Minute).Err() + if err != nil { + return false } - return id == sessionId, true -} + err = rdb.SAdd("active_players", uuid).Err() + if err != nil { + return false + } + err = rdb.Expire("active_players", 5*time.Minute).Err() -func UpdateActiveSession(uuid []byte, sessionId string) bool { - rdb.Do("SELECT", activeClientSessionsDB) - err := rdb.Set(string(uuid), sessionId, 0).Err() return err == nil } func FetchUUIDFromToken(token []byte) ([]byte, bool) { - rdb.Do("SELECT", sessionDB) - uuid, err := rdb.Get(string(token)).Bytes() - if err != nil { - return nil, false - } - - return uuid, true + key := fmt.Sprintf("session:%s", token) + uuid, err := rdb.Get(key).Bytes() + return uuid, err == nil } func RemoveSessionFromToken(token []byte) bool { - rdb.Do("SELECT", sessionDB) - err := rdb.Del(string(token)).Err() + key := fmt.Sprintf("session:%s", token) + err := rdb.Del(key).Err() return err == nil } diff --git a/cache/cache.go b/cache/cache.go index 814dfb6..276eb38 100644 --- a/cache/cache.go +++ b/cache/cache.go @@ -24,16 +24,6 @@ import ( "github.com/go-redis/redis" ) -const ( - dailyRunCompletionsDB = 1 - dailyRunsDB = 2 - accountDailyRunsDB = 3 - accountsDB = 4 - sessionDB = 5 - activeClientSessionsDB = 6 - activePlayersDB = 7 -) - var rdb *redis.Client func InitRedis(address, password, database string) error { diff --git a/cache/daily.go b/cache/daily.go index 4edf1e5..f3c9aba 100644 --- a/cache/daily.go +++ b/cache/daily.go @@ -18,18 +18,22 @@ package cache import ( + "fmt" "time" ) func TryAddDailyRun(seed string) bool { - rdb.Do("SELECT", dailyRunsDB) - err := rdb.Set(time.Now().Format("2006-01-02"), seed, 24*time.Hour).Err() + key := fmt.Sprintf("daily:%s", time.Now().Format("2006-01-02")) + now := time.Now() + midnight := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 1, 0, 0, now.Location()) + duration := time.Until(midnight) + err := rdb.Set(key, seed, duration).Err() return err == nil } func GetDailyRunSeed() (string, bool) { - rdb.Do("SELECT", dailyRunsDB) - cachedSeed, err := rdb.Get(time.Now().Format("2006-01-02")).Result() + key := fmt.Sprintf("daily:%s", time.Now().Format("2006-01-02")) + cachedSeed, err := rdb.Get(key).Result() if err != nil { return "", false } diff --git a/cache/game.go b/cache/game.go index 47b0b1b..b7c050b 100644 --- a/cache/game.go +++ b/cache/game.go @@ -18,8 +18,7 @@ package cache func FetchPlayerCount() (int, bool) { - rdb.Do("SELECT", activePlayersDB) - cachedPlayerCount, err := rdb.DBSize().Result() + cachedPlayerCount, err := rdb.SCard("active_players").Result() if err != nil { return 0, false } @@ -27,34 +26,6 @@ func FetchPlayerCount() (int, bool) { return int(cachedPlayerCount), true } -func FetchBattleCount() (int, bool) { - rdb.Do("SELECT", accountsDB) - cachedBattleCount, err := rdb.Get("battleCount").Int() - if err != nil { - return 0, false - } - - return cachedBattleCount, true -} - -func UpdateBattleCount(battleCount int) bool { - rdb.Do("SELECT", accountsDB) - err := rdb.Set("battleCount", battleCount, 0).Err() - return err == nil -} +// TODO Cache battle count -func FetchClassicSessionCount() (int, bool) { - rdb.Do("SELECT", accountsDB) - cachedClassicSessionCount, err := rdb.Get("classicSessionCount").Int() - if err != nil { - return 0, false - } - - return cachedClassicSessionCount, true -} - -func UpdateClassicSessionCount(classicSessionCount int) bool { - rdb.Do("SELECT", accountsDB) - err := rdb.Set("classicSessionCount", classicSessionCount, 0).Err() - return err == nil -} +// TODO Cache classic session count diff --git a/cache/savedata.go b/cache/savedata.go index 9f7f777..aad6bdd 100644 --- a/cache/savedata.go +++ b/cache/savedata.go @@ -18,12 +18,13 @@ package cache import ( + "fmt" "time" ) func TryAddSeedCompletion(uuid []byte, seed string, mode int) bool { - rdb.Do("SELECT", dailyRunCompletionsDB) - err := rdb.HMSet(string(uuid), map[string]interface{}{ + key := fmt.Sprintf("savedata:%s", uuid) + err := rdb.HMSet(key, map[string]interface{}{ "mode": mode, "seed": seed, "timestamp": time.Now().Unix(), @@ -32,7 +33,7 @@ func TryAddSeedCompletion(uuid []byte, seed string, mode int) bool { } func ReadSeedCompletion(uuid []byte, seed string) (bool, bool) { - rdb.Do("SELECT", dailyRunCompletionsDB) - completed, err := rdb.HExists(string(uuid), seed).Result() + key := fmt.Sprintf("savedata:%s", uuid) + completed, err := rdb.HExists(key, seed).Result() return completed, err == nil } diff --git a/db/game.go b/db/game.go index 0f81944..c0c3cbc 100644 --- a/db/game.go +++ b/db/game.go @@ -36,9 +36,9 @@ func FetchPlayerCount() (int, error) { } func FetchBattleCount() (int, error) { - if cachedBattleCount, ok := cache.FetchBattleCount(); ok { - return cachedBattleCount, nil - } + // if cachedBattleCount, ok := cache.FetchBattleCount(); ok { + // return cachedBattleCount, nil + // } var battleCount int err := handle.QueryRow("SELECT COALESCE(SUM(s.battles), 0) FROM accountStats s JOIN accounts a ON a.uuid = s.uuid WHERE a.banned = 0").Scan(&battleCount) @@ -46,23 +46,15 @@ func FetchBattleCount() (int, error) { return 0, err } - cache.UpdateBattleCount(battleCount) - return battleCount, nil } func FetchClassicSessionCount() (int, error) { - if cachedClassicSessionCount, ok := cache.FetchClassicSessionCount(); ok { - return cachedClassicSessionCount, nil - } - var classicSessionCount int err := handle.QueryRow("SELECT COALESCE(SUM(s.classicSessionsPlayed), 0) FROM accountStats s JOIN accounts a ON a.uuid = s.uuid WHERE a.banned = 0").Scan(&classicSessionCount) if err != nil { return 0, err } - cache.UpdateClassicSessionCount(classicSessionCount) - return classicSessionCount, nil }