Skip to content

Commit 993170b

Browse files
author
Christian Roessner
committed
Fix: Refactor Redis counters and context usage
Refactor Redis read/write counters to unify logic and eliminate redundant increments. Additionally, modify Redis functions to use context consistently, enhancing maintainability and context management across the codebase. Signed-off-by: Christian Roessner <[email protected]>
1 parent e451605 commit 993170b

18 files changed

+622
-582
lines changed

server/backend/cache.go

+14-3
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
"github.com/croessner/nauthilus/server/global"
2727
"github.com/croessner/nauthilus/server/log"
2828
"github.com/croessner/nauthilus/server/rediscli"
29+
"github.com/croessner/nauthilus/server/stats"
2930
"github.com/croessner/nauthilus/server/util"
3031
"github.com/go-kit/log/level"
3132
"github.com/redis/go-redis/v9"
@@ -61,6 +62,8 @@ type RedisCache interface {
6162
func LookupUserAccountFromRedis(ctx context.Context, username string) (accountName string, err error) {
6263
key := config.LoadableConfig.Server.Redis.Prefix + global.RedisUserHashKey
6364

65+
defer stats.RedisReadCounter.Inc()
66+
6467
accountName, err = rediscli.ReadHandle.HGet(ctx, key, username).Result()
6568
if err != nil {
6669
if !errors.Is(err, redis.Nil) {
@@ -81,6 +84,8 @@ func LookupUserAccountFromRedis(ctx context.Context, username string) (accountNa
8184
func LoadCacheFromRedis[T RedisCache](ctx context.Context, key string, cache **T) (isRedisErr bool, err error) {
8285
var redisValue []byte
8386

87+
defer stats.RedisReadCounter.Inc()
88+
8489
if redisValue, err = rediscli.ReadHandle.Get(ctx, key).Bytes(); err != nil {
8590
if errors.Is(err, redis.Nil) {
8691
return true, nil
@@ -108,7 +113,7 @@ func LoadCacheFromRedis[T RedisCache](ctx context.Context, key string, cache **T
108113

109114
// SaveUserDataToRedis is a generic routine to store a cache object on Redis. The type is a RedisCache, which is a
110115
// union.
111-
func SaveUserDataToRedis[T RedisCache](ctx context.Context, guid string, key string, ttl uint, cache *T) error {
116+
func SaveUserDataToRedis[T RedisCache](ctx context.Context, guid string, key string, ttl uint, cache *T) {
112117
var result string
113118

114119
util.DebugModule(
@@ -124,9 +129,11 @@ func SaveUserDataToRedis[T RedisCache](ctx context.Context, guid string, key str
124129
global.LogKeyMsg, err,
125130
)
126131

127-
return err
132+
return
128133
}
129134

135+
defer stats.RedisWriteCounter.Inc()
136+
130137
//nolint:lll // Ignore
131138
if result, err = rediscli.WriteHandle.Set(ctx, key, redisValue, time.Duration(ttl)*time.Second).Result(); err != nil {
132139
level.Error(log.Logger).Log(
@@ -140,7 +147,7 @@ func SaveUserDataToRedis[T RedisCache](ctx context.Context, guid string, key str
140147
global.LogKeyGUID, guid,
141148
"redis", result)
142149

143-
return err
150+
return
144151
}
145152

146153
// GetCacheNames returns the set of cache names for the requested protocol and cache backends.
@@ -207,6 +214,8 @@ func GetWebAuthnFromRedis(ctx context.Context, uniqueUserId string) (user *User,
207214

208215
key := "as_webauthn:user:" + uniqueUserId
209216

217+
defer stats.RedisReadCounter.Inc()
218+
210219
if redisValue, err = rediscli.ReadHandle.Get(ctx, key).Bytes(); err != nil {
211220
level.Error(log.Logger).Log(global.LogKeyMsg, err)
212221

@@ -241,6 +250,8 @@ func SaveWebAuthnToRedis(ctx context.Context, user *User, ttl uint) error {
241250

242251
key := "as_webauthn:user:" + user.Id
243252

253+
defer stats.RedisWriteCounter.Inc()
254+
244255
//nolint:lll // Ignore
245256
if result, err = rediscli.WriteHandle.Set(ctx, key, redisValue, time.Duration(ttl)*time.Second).Result(); err != nil {
246257
level.Error(log.Logger).Log(global.LogKeyMsg, err)

server/core/auth.go

+41-8
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ package core
1717

1818
import (
1919
"bytes"
20+
"context"
2021
"encoding/base64"
2122
stderrors "errors"
2223
"fmt"
@@ -1116,6 +1117,43 @@ func (a *AuthState) setStatusCodes(service string) error {
11161117
return nil
11171118
}
11181119

1120+
// getUserAccountFromCache fetches the user account name from Redis cache using the provided username.
1121+
// Logs errors and increments Redis read counter. Returns an empty string if the account name is not found or an error occurs.
1122+
func getUserAccountFromCache(ctx context.Context, username string, guid string) (accountName string) {
1123+
var err error
1124+
1125+
accountName, err = backend.LookupUserAccountFromRedis(ctx, username)
1126+
if err != nil || accountName == "" {
1127+
if err != nil {
1128+
level.Error(log.Logger).Log(global.LogKeyGUID, guid, global.LogKeyMsg, err)
1129+
}
1130+
1131+
return ""
1132+
}
1133+
1134+
return accountName
1135+
}
1136+
1137+
// refreshUserAccount updates the user account information from the cache.
1138+
// It sets the account field and attributes if they are nil and the account name is found.
1139+
func (a *AuthState) refreshUserAccount() (accountName string) {
1140+
accountName = getUserAccountFromCache(a.HTTPClientContext, a.Username, *a.GUID)
1141+
if accountName == "" {
1142+
return
1143+
}
1144+
1145+
if a.AccountField == nil && a.Attributes == nil {
1146+
accountField := global.MetaUserAccount
1147+
attributes := make(backend.DatabaseResult)
1148+
1149+
a.AccountField = &accountField
1150+
attributes[global.MetaUserAccount] = []any{accountName}
1151+
a.Attributes = attributes
1152+
}
1153+
1154+
return
1155+
}
1156+
11191157
// handleFeatures iterates through the list of enabled features and returns true, if a feature returned positive.
11201158
func (a *AuthState) handleFeatures(ctx *gin.Context) (authResult global.AuthResult) {
11211159
// Helper function that sends an action request and waits for it to be finished. Features may change the Lua context.
@@ -1571,11 +1609,7 @@ func (a *AuthState) postVerificationProcesses(ctx *gin.Context, useCache bool, b
15711609
Attributes: a.Attributes,
15721610
}
15731611

1574-
go func() {
1575-
if err := backend.SaveUserDataToRedis(a.HTTPClientContext, *a.GUID, redisUserKey, config.LoadableConfig.Server.Redis.PosCacheTTL, ppc); err == nil {
1576-
stats.RedisWriteCounter.Inc()
1577-
}
1578-
}()
1612+
go backend.SaveUserDataToRedis(a.HTTPClientContext, *a.GUID, redisUserKey, config.LoadableConfig.Server.Redis.PosCacheTTL, ppc)
15791613
}
15801614
}
15811615
}
@@ -1843,10 +1877,9 @@ func (a *AuthState) updateUserAccountInRedis() (accountName string, err error) {
18431877

18441878
accountName = strings.Join(accounts, ":")
18451879

1880+
defer stats.RedisWriteCounter.Inc()
1881+
18461882
err = rediscli.WriteHandle.HSet(a.HTTPClientContext, key, a.Username, accountName).Err()
1847-
if err == nil {
1848-
stats.RedisWriteCounter.Inc()
1849-
}
18501883
}
18511884

18521885
return

0 commit comments

Comments
 (0)