fix: allow login during sqlite write pressure

This commit is contained in:
ShukeBta
2026-06-11 20:06:55 +08:00
parent 7274ea19b7
commit 52d75171b2
10 changed files with 225 additions and 16 deletions
+18 -7
View File
@@ -865,13 +865,18 @@ type PermissionRepository struct{ db *gorm.DB }
// Create inserts a new permission record.
func (r *PermissionRepository) Create(ctx context.Context, p *model.UserPermission) error {
return r.db.WithContext(ctx).Create(p).Error
return withSQLiteBusyRetry(ctx, func() error {
return r.db.WithContext(ctx).Create(p).Error
})
}
// FindByUserID returns the permission record for a user, or (nil, nil) when absent.
func (r *PermissionRepository) FindByUserID(ctx context.Context, userID string) (*model.UserPermission, error) {
var p model.UserPermission
err := r.db.WithContext(ctx).Where("user_id = ?", userID).First(&p).Error
err := withSQLiteBusyRetry(ctx, func() error {
p = model.UserPermission{}
return r.db.WithContext(ctx).Where("user_id = ?", userID).First(&p).Error
})
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, nil
}
@@ -883,19 +888,25 @@ func (r *PermissionRepository) FindByUserID(ctx context.Context, userID string)
// Update updates permission fields for a user.
func (r *PermissionRepository) Update(ctx context.Context, userID string, updates map[string]bool) error {
return r.db.WithContext(ctx).Model(&model.UserPermission{}).
Where("user_id = ?", userID).Updates(updates).Error
return withSQLiteBusyRetry(ctx, func() error {
return r.db.WithContext(ctx).Model(&model.UserPermission{}).
Where("user_id = ?", userID).Updates(updates).Error
})
}
// Upsert creates or updates a permission record.
func (r *PermissionRepository) Upsert(ctx context.Context, p *model.UserPermission) error {
return r.db.WithContext(ctx).Where("user_id = ?", p.UserID).
Assign(*p).FirstOrCreate(p).Error
return withSQLiteBusyRetry(ctx, func() error {
return r.db.WithContext(ctx).Where("user_id = ?", p.UserID).
Assign(*p).FirstOrCreate(p).Error
})
}
// Delete removes a permission record.
func (r *PermissionRepository) Delete(ctx context.Context, userID string) error {
return r.db.WithContext(ctx).Where("user_id = ?", userID).Delete(&model.UserPermission{}).Error
return withSQLiteBusyRetry(ctx, func() error {
return r.db.WithContext(ctx).Where("user_id = ?", userID).Delete(&model.UserPermission{}).Error
})
}
// ─── Refresh Token ───────────────────────────────────────────────────────────
+2 -2
View File
@@ -13,7 +13,7 @@ func withSQLiteBusyRetry(ctx context.Context, op func() error) error {
deadline := time.Now().Add(sqliteBusyRetryMaxElapsed)
for {
err := op()
if !isSQLiteBusyError(err) {
if !IsSQLiteBusyError(err) {
return err
}
if ctxErr := ctx.Err(); ctxErr != nil {
@@ -35,7 +35,7 @@ func withSQLiteBusyRetry(ctx context.Context, op func() error) error {
}
}
func isSQLiteBusyError(err error) bool {
func IsSQLiteBusyError(err error) bool {
if err == nil {
return false
}