Replace recursive user id retry with bounded loop
Signed-off-by: Sean Du <do4suki@gmail.com>
This commit is contained in:
@@ -73,7 +73,10 @@ func login(ctx *gin.Context) {
|
|||||||
if pass == "" {
|
if pass == "" {
|
||||||
// 未注册 - 自动注册
|
// 未注册 - 自动注册
|
||||||
// 检查是否 userID 已经注册
|
// 检查是否 userID 已经注册
|
||||||
userID, _ = checkUserID(ss, int(loginTime))
|
userID, err = getAvailableUserID(ss, int(loginTime))
|
||||||
|
if ss.CheckErr(err) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
pass = openssl.Md5ToString(password)
|
pass = openssl.Md5ToString(password)
|
||||||
autoKey = "AUTO" + strings.ToUpper(utils.RandomStr(32))
|
autoKey = "AUTO" + strings.ToUpper(utils.RandomStr(32))
|
||||||
@@ -275,18 +278,24 @@ func login(ctx *gin.Context) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func checkUserID(ss *session.Session, userID int) (int, bool) {
|
func getAvailableUserID(ss *session.Session, seed int) (int, error) {
|
||||||
exist, err := ss.UserEng.Table("users").Where("user_id = ?", userID).Exist()
|
const maxAttempts = 16
|
||||||
if ss.CheckErr(err) {
|
|
||||||
return 0, false
|
userID := seed
|
||||||
|
for attempt := range maxAttempts {
|
||||||
|
exist, err := ss.UserEng.Table("users").Where("user_id = ?", userID).Exist()
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
if !exist {
|
||||||
|
return userID, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Move to millisecond precision to reduce repeated collisions.
|
||||||
|
userID = int(time.Now().UnixMilli()) + attempt + 1
|
||||||
}
|
}
|
||||||
|
|
||||||
if exist {
|
return 0, errors.New("failed to allocate user id")
|
||||||
userID = int(time.Now().Unix())
|
|
||||||
return checkUserID(ss, userID)
|
|
||||||
}
|
|
||||||
|
|
||||||
return userID, true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|||||||
Reference in New Issue
Block a user