fusenapi/shared/shared_state.go

69 lines
1.2 KiB
Go
Raw Normal View History

2023-08-09 08:54:52 +00:00
package shared
2023-08-09 08:17:24 +00:00
import (
"context"
2023-08-10 04:04:36 +00:00
"fusenapi/model/gmodel"
"fusenapi/utils/auth"
2023-08-09 08:17:24 +00:00
"log"
2023-08-10 04:04:36 +00:00
"time"
2023-08-09 08:17:24 +00:00
"github.com/lni/dragonboat/v4"
2023-08-10 04:04:36 +00:00
"gorm.io/gorm"
2023-08-09 08:17:24 +00:00
)
type SharedState struct {
shardID uint64
replicaID uint64
nh *dragonboat.NodeHost
}
2023-08-10 04:04:36 +00:00
func GetUserState(UserId int64, gdb *gorm.DB) (us *UserState, err error) {
models := gmodel.NewAllModels(gdb)
user, err := models.FsUser.FindUserById(context.TODO(), UserId)
if err != nil {
return nil, err
}
userState := &UserState{
UserId: UserId,
PwdHash: auth.StringToHash(*user.PasswordHash),
2023-09-05 07:00:45 +00:00
UpdateAt: time.Now().UTC(),
2023-08-10 04:04:36 +00:00
}
return userState, nil
}
2023-08-09 08:17:24 +00:00
func (ss *SharedState) GetUserState(Userid int64) (us *UserState, err error) {
ius, err := ss.nh.SyncRead(context.TODO(), ss.shardID, Userid)
if err != nil {
log.Println(err)
return nil, err
}
if ius != nil {
return ius.(*UserState), nil
}
cs := ss.nh.GetNoOPSession(128)
cmd := &CmdUpdate{UserId: Userid}
cmdBuf, err := FsPasser.PackToBytes(cmd)
if err != nil {
return nil, err
}
result, err := ss.nh.SyncPropose(context.TODO(), cs, cmdBuf)
if err != nil {
return nil, err
}
us = &UserState{}
err = us.Decode(result.Data)
if err != nil {
return nil, err
}
return us, err
}