Add cache into querying user

This commit is contained in:
LittleSheep 2024-12-08 20:21:40 +08:00
parent 77c543f88e
commit 02f122328a
6 changed files with 111 additions and 17 deletions

12
.idea/workspace.xml generated
View File

@ -4,9 +4,13 @@
<option name="autoReloadType" value="ALL" /> <option name="autoReloadType" value="ALL" />
</component> </component>
<component name="ChangeListManager"> <component name="ChangeListManager">
<list default="true" id="3fefb2c4-b6f9-466b-a523-53352e8d6f95" name="更改" comment=":bug: Bug fix directory service wasn't registered"> <list default="true" id="3fefb2c4-b6f9-466b-a523-53352e8d6f95" name="更改" comment=":bug: Fix random panic">
<change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" /> <change beforePath="$PROJECT_DIR$/.idea/workspace.xml" beforeDir="false" afterPath="$PROJECT_DIR$/.idea/workspace.xml" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/check_in.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/check_in.go" afterDir="false" /> <change beforePath="$PROJECT_DIR$/pkg/internal/grpc/user.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/grpc/user.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/http/api/accounts_api.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/http/api/accounts_api.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/http/api/userinfo_api.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/http/api/userinfo_api.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/accounts.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/accounts.go" afterDir="false" />
<change beforePath="$PROJECT_DIR$/pkg/internal/services/preferences.go" beforeDir="false" afterPath="$PROJECT_DIR$/pkg/internal/services/preferences.go" afterDir="false" />
</list> </list>
<option name="SHOW_DIALOG" value="false" /> <option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" /> <option name="HIGHLIGHT_CONFLICTS" value="true" />
@ -159,7 +163,6 @@
</component> </component>
<component name="VcsManagerConfiguration"> <component name="VcsManagerConfiguration">
<option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="false" /> <option name="CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT" value="false" />
<MESSAGE value=":loud_sound: Verbose notifying logging" />
<MESSAGE value=":loud_sound: Verbose notifying check logging" /> <MESSAGE value=":loud_sound: Verbose notifying check logging" />
<MESSAGE value=":bug: Fix notifiable is empty when user do not set" /> <MESSAGE value=":bug: Fix notifiable is empty when user do not set" />
<MESSAGE value=":bug: Fix notification push batch emitted twice" /> <MESSAGE value=":bug: Fix notification push batch emitted twice" />
@ -184,7 +187,8 @@
<MESSAGE value=":loud_sound: Verbose logging at setting last seen at" /> <MESSAGE value=":loud_sound: Verbose logging at setting last seen at" />
<MESSAGE value=":loud_sound: Verbose logging at receive broadcasting event" /> <MESSAGE value=":loud_sound: Verbose logging at receive broadcasting event" />
<MESSAGE value=":bug: Bug fix directory service wasn't registered" /> <MESSAGE value=":bug: Bug fix directory service wasn't registered" />
<option name="LAST_COMMIT_MESSAGE" value=":bug: Bug fix directory service wasn't registered" /> <MESSAGE value=":bug: Fix random panic" />
<option name="LAST_COMMIT_MESSAGE" value=":bug: Fix random panic" />
<option name="GROUP_MULTIFILE_MERGE_BY_DIRECTORY" value="true" /> <option name="GROUP_MULTIFILE_MERGE_BY_DIRECTORY" value="true" />
</component> </component>
<component name="VgoProject"> <component name="VgoProject">

View File

@ -5,25 +5,68 @@ import (
"fmt" "fmt"
"git.solsynth.dev/hypernet/nexus/pkg/proto" "git.solsynth.dev/hypernet/nexus/pkg/proto"
"git.solsynth.dev/hypernet/passport/pkg/authkit/models" "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
localCache "git.solsynth.dev/hypernet/passport/pkg/internal/cache"
"git.solsynth.dev/hypernet/passport/pkg/internal/database" "git.solsynth.dev/hypernet/passport/pkg/internal/database"
"git.solsynth.dev/hypernet/passport/pkg/internal/services"
"github.com/eko/gocache/lib/v4/cache"
"github.com/eko/gocache/lib/v4/marshaler"
"github.com/samber/lo" "github.com/samber/lo"
"google.golang.org/grpc/codes" "google.golang.org/grpc/codes"
"google.golang.org/grpc/status" "google.golang.org/grpc/status"
"gorm.io/gorm"
) )
func (v *App) GetUser(ctx context.Context, request *proto.GetUserRequest) (*proto.UserInfo, error) { func (v *App) GetUser(ctx context.Context, request *proto.GetUserRequest) (*proto.UserInfo, error) {
tx := database.C cacheManager := cache.New[any](localCache.S)
if request.UserId != nil { marshal := marshaler.New(cacheManager)
tx = tx.Where("id = ?", uint(request.GetUserId())) contx := context.Background()
}
if request.Name != nil {
tx = tx.Where("name = ?", request.GetName())
}
var account models.Account var account models.Account
if err := tx.First(&account).Error; err != nil {
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("requested user with id %d was not found", request.GetUserId())) tx := database.C
hitCache := false
if request.UserId != nil {
if val, err := marshal.Get(contx, services.GetAccountCacheKey(request.GetUserId()), new(models.Account)); err == nil {
account = *val.(*models.Account)
hitCache = true
} else {
tx = tx.Where("id = ?", uint(request.GetUserId()))
}
} }
if request.Name != nil {
if val, err := marshal.Get(contx, services.GetAccountCacheKey(request.GetName()), new(models.Account)); err == nil {
account = *val.(*models.Account)
hitCache = true
} else {
tx = tx.Where("name = ?", request.GetName())
}
}
if !hitCache {
if err := tx.
Preload("Profile").
Preload("Badges", func(db *gorm.DB) *gorm.DB {
return db.Order("badges.type DESC")
}).
First(&account).Error; err != nil {
return nil, status.Errorf(codes.NotFound, fmt.Sprintf("requested user with id %d was not found", request.GetUserId()))
}
groups, err := services.GetUserAccountGroup(account)
if err != nil {
return nil, status.Errorf(codes.Internal, fmt.Sprintf("unable to get account groups: %v", err))
}
for _, group := range groups {
for k, v := range group.PermNodes {
if _, ok := account.PermNodes[k]; !ok {
account.PermNodes[k] = v
}
}
}
services.CacheAccount(account)
}
return account.EncodeToUserInfo(), nil return account.EncodeToUserInfo(), nil
} }

View File

@ -65,8 +65,9 @@ func getUserinfo(c *fiber.Ctx) error {
var resp fiber.Map var resp fiber.Map
raw, _ := jsoniter.Marshal(data) raw, _ := jsoniter.Marshal(data)
jsoniter.Unmarshal(raw, &resp) _ = jsoniter.Unmarshal(raw, &resp)
// Used to support OIDC standard
resp["sub"] = strconv.Itoa(int(data.ID)) resp["sub"] = strconv.Itoa(int(data.ID))
resp["family_name"] = data.Profile.FirstName resp["family_name"] = data.Profile.FirstName
resp["given_name"] = data.Profile.LastName resp["given_name"] = data.Profile.LastName

View File

@ -1,8 +1,12 @@
package api package api
import ( import (
"context"
"fmt" "fmt"
"git.solsynth.dev/hypernet/passport/pkg/authkit/models" "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
localCache "git.solsynth.dev/hypernet/passport/pkg/internal/cache"
"github.com/eko/gocache/lib/v4/cache"
"github.com/eko/gocache/lib/v4/marshaler"
"gorm.io/gorm" "gorm.io/gorm"
"strconv" "strconv"
"strings" "strings"
@ -15,10 +19,21 @@ import (
func getOtherUserinfo(c *fiber.Ctx) error { func getOtherUserinfo(c *fiber.Ctx) error {
alias := c.Params("alias") alias := c.Params("alias")
cacheManager := cache.New[any](localCache.S)
marshal := marshaler.New(cacheManager)
ctx := context.Background()
if val, err := marshal.Get(ctx, services.GetAccountCacheKey(alias), new(models.Account)); err == nil {
return c.JSON(*val.(*models.Account))
}
tx := database.C.Where("name = ?", alias) tx := database.C.Where("name = ?", alias)
numericId, err := strconv.Atoi(alias) numericId, err := strconv.Atoi(alias)
if err == nil { if err == nil {
if val, err := marshal.Get(ctx, services.GetAccountCacheKey(numericId), new(models.Account)); err == nil {
return c.JSON(*val.(*models.Account))
}
tx = tx.Or("id = ?", numericId) tx = tx.Or("id = ?", numericId)
} }
@ -44,6 +59,8 @@ func getOtherUserinfo(c *fiber.Ctx) error {
} }
} }
services.CacheAccount(account)
return c.JSON(account) return c.JSON(account)
} }

View File

@ -6,6 +6,10 @@ import (
"git.solsynth.dev/hypernet/nexus/pkg/nex" "git.solsynth.dev/hypernet/nexus/pkg/nex"
"git.solsynth.dev/hypernet/nexus/pkg/proto" "git.solsynth.dev/hypernet/nexus/pkg/proto"
"git.solsynth.dev/hypernet/passport/pkg/authkit/models" "git.solsynth.dev/hypernet/passport/pkg/authkit/models"
localCache "git.solsynth.dev/hypernet/passport/pkg/internal/cache"
"github.com/eko/gocache/lib/v4/cache"
"github.com/eko/gocache/lib/v4/marshaler"
"github.com/eko/gocache/lib/v4/store"
"time" "time"
"unicode" "unicode"
@ -22,6 +26,31 @@ import (
"github.com/samber/lo" "github.com/samber/lo"
) )
func GetAccountCacheKey(query any) string {
return fmt.Sprintf("account-query#%v", query)
}
func CacheAccount(account models.Account) {
cacheManager := cache.New[any](localCache.S)
marshal := marshaler.New(cacheManager)
ctx := context.Background()
_ = marshal.Set(
ctx,
GetAccountCacheKey(account.Name),
account,
store.WithExpiration(30*time.Minute),
store.WithTags([]string{"account", fmt.Sprintf("user#%d", account.ID)}),
)
_ = marshal.Set(
ctx,
GetAccountCacheKey(account.ID),
account,
store.WithExpiration(30*time.Minute),
store.WithTags([]string{"account", fmt.Sprintf("user#%d", account.ID)}),
)
}
func ValidateAccountName(val string, min, max int) bool { func ValidateAccountName(val string, min, max int) bool {
actualLength := 0 actualLength := 0
for _, r := range val { for _, r := range val {

View File

@ -49,10 +49,10 @@ func GetNotificationPreference(account models.Account) (models.PreferenceNotific
var notification models.PreferenceNotification var notification models.PreferenceNotification
cacheManager := cache.New[any](localCache.S) cacheManager := cache.New[any](localCache.S)
marshal := marshaler.New(cacheManager) marshal := marshaler.New(cacheManager)
contx := context.Background() ctx := context.Background()
if val, err := marshal.Get(contx, GetNotificationPreferenceCacheKey(account.ID), new(models.PreferenceNotification)); err == nil { if val, err := marshal.Get(ctx, GetNotificationPreferenceCacheKey(account.ID), new(models.PreferenceNotification)); err == nil {
notification = val.(models.PreferenceNotification) notification = *val.(*models.PreferenceNotification)
} else { } else {
if err := database.C.Where("account_id = ?", account.ID).First(&notification).Error; err != nil { if err := database.C.Where("account_id = ?", account.ID).First(&notification).Error; err != nil {
return notification, err return notification, err