perf(clients): persist reconciled timestamps in one write (#7242)

Reconciling a client record whose fields changed wrote it twice: Save stamped updated_at with the current time, then a second UPDATE put the agreed timestamp back. A PostgreSQL master with about 7,000 clients counted roughly 179,000 of each in 50 minutes.

Run the Save through a session whose clock returns the agreed timestamp, so GORM's hooks and serializers still run and one UPDATE carries the right value. An unchanged row still writes nothing. Verified on SQLite and PostgreSQL 18: one UPDATE per changed row, where the previous code issues two.

Fixes #7234
This commit is contained in:
Hamed
2026-11-29 17:17:36 +03:30
committed by GitHub
parent 8205a5be6a
commit b13c6d9be9
3 changed files with 86 additions and 6 deletions
+4 -6
View File
@@ -5,6 +5,7 @@ import (
"fmt"
"reflect"
"strings"
"time"
"github.com/google/uuid"
@@ -252,12 +253,9 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [
if reflect.DeepEqual(*row, before) {
continue
}
if err := tx.Save(row).Error; err != nil {
return err
}
if err := tx.Model(&model.ClientRecord{}).
Where("id = ?", row.Id).
UpdateColumn("updated_at", preservedUpdatedAt).Error; err != nil {
// Keep GORM's save hooks and serializers while writing the agreed timestamp once.
save := tx.Session(&gorm.Session{NowFunc: func() time.Time { return time.UnixMilli(preservedUpdatedAt) }})
if err := save.Save(row).Error; err != nil {
return err
}
}
@@ -1,7 +1,13 @@
package service
import (
"errors"
"fmt"
"strings"
"testing"
"time"
"gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
@@ -207,3 +213,75 @@ func TestDelInboundClientDetachesOnlyTheRemovedClient(t *testing.T) {
t.Errorf("bystander comment = %q, want %q", kept.Comment, "keep me")
}
}
func TestSyncInboundClientWritesTimestampOnce(t *testing.T) {
testSyncInboundClientWritesTimestampOnce(t, initTrafficTestDB(t))
}
func testSyncInboundClientWritesTimestampOnce(t *testing.T, db *gorm.DB) {
t.Helper()
tag := fmt.Sprintf("single-client-write-%d", time.Now().UnixNano())
inbound := durableTestInbound(nil, tag, 42534)
if err := db.Create(inbound).Error; err != nil {
t.Fatal(err)
}
svc := &ClientService{}
client := model.Client{Email: tag + "@x", Enable: true, TotalGB: 200, Comment: "old", UpdatedAt: 600}
if err := svc.SyncInbound(nil, inbound.Id, []model.Client{client}); err != nil {
t.Fatal(err)
}
updates := 0
const callback = "test:count-client-reconcile-writes"
if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) {
sql := tx.Statement.SQL.String()
if tx.Statement.Table == "clients" && strings.Contains(sql, "updated_at") {
updates++
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) })
assertClient := func(wantTimestamp int64, wantUpdates int) {
t.Helper()
var rec model.ClientRecord
if err := db.Where("email = ?", client.Email).First(&rec).Error; err != nil {
t.Fatal(err)
}
if rec.Enable || rec.TotalGB != 0 || rec.Comment != "" || rec.UpdatedAt != wantTimestamp {
t.Fatalf("saved enabled/quota/comment/timestamp: %t/%d/%q/%d, want false/0/empty/%d", rec.Enable, rec.TotalGB, rec.Comment, rec.UpdatedAt, wantTimestamp)
}
if updates != wantUpdates {
t.Fatalf("client UPDATEs = %d, want %d", updates, wantUpdates)
}
updates = 0
}
client.Enable, client.TotalGB, client.Comment, client.UpdatedAt = false, 0, "", 400
if err := svc.SyncInbound(nil, inbound.Id, []model.Client{client}); err != nil {
t.Fatal(err)
}
assertClient(600, 1)
if err := svc.SyncInbound(nil, inbound.Id, []model.Client{client}); err != nil {
t.Fatal(err)
}
assertClient(600, 0)
client.UpdatedAt = 900
if err := svc.SyncInbound(nil, inbound.Id, []model.Client{client}); err != nil {
t.Fatal(err)
}
assertClient(900, 1)
rollback := errors.New("roll back client change")
err := db.Transaction(func(tx *gorm.DB) error {
client.Comment = "rolled back"
client.UpdatedAt = 1000
if err := svc.SyncInbound(tx, inbound.Id, []model.Client{client}); err != nil {
return err
}
return rollback
})
if !errors.Is(err, rollback) {
t.Fatalf("transaction error = %v", err)
}
assertClient(900, 1)
}
@@ -30,3 +30,7 @@ func TestSyncInboundClientsOnPostgres(t *testing.T) {
t.Fatalf("SyncInbound on PostgreSQL: %v", err)
}
}
func TestSyncInboundClientWritesTimestampOncePostgres(t *testing.T) {
testSyncInboundClientWritesTimestampOnce(t, durablePostgresDB(t))
}