perf(clients): batch the client record lookup in bulk operations

BulkResetTraffic resolved every address with its own GetRecordByEmail
call, one SELECT per email, purely to find the disabled clients it has to
re-enable. Resetting 30 clients issued 30 queries before the batched
transaction even started, while BulkAdjust, BulkDelete and BulkSetEnable
next to it already loaded their rows with a single chunked IN query.

Those three carried a verbatim copy each of both the trim/dedupe loop and
the chunked record load, so the reuse is the fix: trimmedUniqueEmails now
delegates to the existing uniqueNonEmptyStrings, and clientRecordsByEmail
holds the one chunked lookup all four call sites share.

A DB failure during the lookup now aborts the reset instead of being
swallowed per email; a missing row is still skipped, as before.

The new test drives BulkResetTraffic with 3 and with 30 emails and fails
unless both issue the same number of SELECTs against clients.
This commit is contained in:
Sanaei
2026-09-10 21:07:49 +02:00
parent fc08b53395
commit 8b9cf260b6
5 changed files with 152 additions and 95 deletions
+22
View File
@@ -270,3 +270,25 @@ func (s *ClientService) findInboundIdsByClientEmail(email string) ([]int, error)
}
return out, nil
}
// clientRecordsByEmail batch-loads client rows for emails, keyed by email.
// Callers pass an already-deduplicated list; absent addresses are simply
// missing from the map.
func clientRecordsByEmail(tx *gorm.DB, emails []string) (map[string]*model.ClientRecord, error) {
if tx == nil {
tx = database.GetDB()
}
var records []model.ClientRecord
for _, batch := range chunkStrings(emails, sqlInChunk) {
var rows []model.ClientRecord
if err := tx.Where("email IN ?", batch).Find(&rows).Error; err != nil {
return nil, err
}
records = append(records, rows...)
}
byEmail := make(map[string]*model.ClientRecord, len(records))
for i := range records {
byEmail[records[i].Email] = &records[i]
}
return byEmail, nil
}