fix(idgen): retry snowflake generation and error on negative ID

NextUint64ID now retries up to 3 times when Int64() is negative, then
returns an error instead of 0 or Fatalf. All call sites propagate the
error to avoid GORM omitting zero-value primary keys.
This commit is contained in:
ryan
2026-06-17 13:08:00 +08:00
parent a27113feb2
commit 92dc6a59c0
11 changed files with 145 additions and 44 deletions
+30 -17
View File
@@ -117,21 +117,10 @@ func UploadFile(c *gin.Context) {
uploadType := c.DefaultPostForm("type", "generic")
accessModeStr := c.PostForm("access_mode")
var accessMode int
if accessModeStr == "" {
if uploadType == defaultPublicUploadType {
accessMode = 1
} else {
accessMode = 0
}
} else {
var err error
accessMode, err = strconv.Atoi(accessModeStr)
if err != nil || (accessMode != 0 && accessMode != 1) {
c.JSON(http.StatusOK, response.Err("无效的 access_mode 参数"))
return
}
accessMode, errMsg := resolveUploadAccessMode(c, uploadType)
if errMsg != "" {
c.JSON(http.StatusOK, response.Err(errMsg))
return
}
// 6. 秒传匹配校验:校验数据库中是否存在相同 Hash 且大小一致的可用文件
@@ -151,7 +140,11 @@ func UploadFile(c *gin.Context) {
return
}
id := idgen.NextUint64ID()
id, err := idgen.NextUint64ID()
if err != nil {
c.JSON(http.StatusOK, response.Err(ErrSaveUploadRecordFailed))
return
}
subPath := fmt.Sprintf("uploads/%s/%d.%s", time.Now().Format("2006/01/02"), id, ext)
// 8. 写入当前活动存储驱动。
@@ -336,6 +329,22 @@ func BatchDownloadFiles(c *gin.Context) {
}
}
func resolveUploadAccessMode(c *gin.Context, uploadType string) (int, string) {
accessModeStr := c.PostForm("access_mode")
if accessModeStr == "" {
if uploadType == defaultPublicUploadType {
return 1, ""
}
return 0, ""
}
accessMode, err := strconv.Atoi(accessModeStr)
if err != nil || (accessMode != 0 && accessMode != 1) {
return 0, "无效的 access_mode 参数"
}
return accessMode, ""
}
// validateUploadExtension 校验文件后缀是否在系统允许的上传扩展名列表中
func validateUploadExtension(ctx context.Context, ext string) string {
var sc model.SystemConfig
@@ -367,7 +376,11 @@ func tryInstantUpload(ctx context.Context, c *gin.Context, currUser *model.User,
return true, nil
}
id := idgen.NextUint64ID()
id, err := idgen.NextUint64ID()
if err != nil {
c.JSON(http.StatusOK, response.Err(ErrSaveUploadRecordFailed))
return true, err
}
newUpload := model.Upload{
ID: id,
UserID: currUser.ID,