perf(clients): write client_inbounds deltas and check identity from the clients table

Client CRUD latency scaled with the number of client-inbound edges rather
than with the size of the change. On a 5k-client / 8-inbound / ~56k-edge
PostgreSQL panel, creating one client took 60-120s (#6252).

Two independent causes, both confirmed by the reporter's pg_stat_statements
and reproduced locally at their topology.

SyncInbound deleted every client_inbounds row for an inbound and re-inserted
the whole set, so a one-client edit rewrote thousands of unrelated rows. The
dominant caller was not user CRUD: the node traffic poll re-syncs every node
inbound from its snapshot every 5s, so the panel churned the entire
membership table continuously in the background. SyncInbound now reads the
current links and writes only the difference - insert missing, update a
changed flow_override, delete departed. Callers are unchanged, so every
reconciliation path benefits, and the four hot client CRUD paths additionally
pass only the clients they touched via ApplyInboundClientDelta.

The insert needs clause.OnConflict: the unconditional delete it replaces also
serialized concurrent syncs of one inbound, and the node poll commits in its
own transaction outside the serialized writer, where a duplicate key would
abort the whole poll on PostgreSQL.

Identity and membership questions expanded every inbound's settings.clients
JSON - 5.75s per call under the reporter's load. They now read the indexed
clients and client_inbounds tables, which every read path already trusts,
over just the emails being checked. A LOWER(email) expression index keeps
the case-insensitive matching indexed; a struct tag cannot declare one.

Measured on PostgreSQL 17 at 8 inbounds x 6000 clients, rows written to
client_inbounds per operation, before -> after:

  create across 8 inbounds   48008 ins / 48000 del  ->  8 ins / 0 del
  update the client          48008 ins / 48008 del  ->  0 ins / 0 del
  detach from 4 inbounds     24000 ins / 24004 del  ->  0 ins / 4 del
  delete the client          24000 ins / 24004 del  ->  0 ins / 4 del

Two behavior changes worth naming. An email seen with two different subIds
across two inbounds' JSON used to be locked so that no add could claim it,
including the one with the correct subId; the clients row now adjudicates.
And on an install whose settings JSON holds an email with no matching link,
"is this email on another inbound" now answers no, so deleting it elsewhere
purges its traffic rows; compactOrphans and the startup heal already
converge such drift.

Every added test was verified against a hand-written mutation of this change,
so none of them pass regardless of the fix. One mutation survives on purpose:
swapping OnConflict DoUpdates for DoNothing is only observable when two
transactions race the same row, and a timing-dependent test would be flaky.

Per-node batching of remote pushes and the metadata-only inbounds list from
the same report are deliberately not in this change.

Closes #6252
This commit is contained in:
Sanaei
2026-08-20 04:09:57 +02:00
parent c8a3a2d723
commit f7db247b07
13 changed files with 804 additions and 126 deletions
+36 -37
View File
@@ -42,7 +42,7 @@ func advancePushedInbound(rt runtime.Runtime, prevSettings string, ib *model.Inb
}
// delInboundClients removes several clients from a single inbound in one pass:
// one settings rewrite, one runtime sweep, one Save and one SyncInbound for the
// one settings rewrite, one runtime sweep, one Save and one link delta for the
// whole batch, instead of repeating the full per-client cycle. It mirrors the
// semantics of DelInboundClientByEmail for each removed client. needRestart is
// the OR across all removals.
@@ -177,11 +177,13 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId
if e := tx.Save(oldInbound).Error; e != nil {
return e
}
finalClients, gcErr := inboundSvc.GetClients(oldInbound)
if gcErr != nil {
return gcErr
detached := make([]string, 0, len(targets))
for _, t := range targets {
if t.email != "" {
detached = append(detached, t.email)
}
}
if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
if err := s.ApplyInboundClientDelta(tx, inboundId, nil, detached); err != nil {
return err
}
if oldInbound.NodeID != nil {
@@ -239,13 +241,10 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId
return needRestart, nil
}
func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client, emailSubIDs map[string]string) (string, error) {
if emailSubIDs == nil {
var err error
emailSubIDs, err = inboundSvc.getAllEmailSubIDs()
if err != nil {
return "", err
}
func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, clients []model.Client) (string, error) {
emailSubIDs, err := inboundSvc.emailSubIDsForClients(clients)
if err != nil {
return "", err
}
seen := make(map[string]string, len(clients))
for _, client := range clients {
@@ -270,14 +269,6 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c
}
func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) {
return s.addInboundClient(inboundSvc, data, nil)
}
// addInboundClient is AddInboundClient with an optional precomputed email→subId
// map. Bulk callers pass a single snapshot so the global getAllEmailSubIDs scan
// runs once for the whole batch instead of once per target inbound; a nil map
// makes it compute its own (the single-add path).
func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, emailSubIDs map[string]string) (bool, error) {
defer lockInbound(data.Id).Unlock()
clients, err := inboundSvc.GetClients(data)
@@ -306,7 +297,7 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model
interfaceClients[i] = cm
}
}
existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, emailSubIDs)
existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
if err != nil {
return false, err
}
@@ -422,6 +413,13 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model
prevSettings := oldInbound.Settings
oldInbound.Settings = string(newSettings)
// From the stamped wire entries, not from clients: created_at / updated_at /
// subId are written onto interfaceClients above, after clients was parsed.
addedClients, err := settingsEntriesToClients(interfaceClients)
if err != nil {
return false, err
}
needRestart := false
rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound)
@@ -443,11 +441,7 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model
if e := tx.Save(oldInbound).Error; e != nil {
return e
}
finalClients, gcErr := inboundSvc.GetClients(oldInbound)
if gcErr != nil {
return gcErr
}
if err := s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, addedClients, nil); err != nil {
return err
}
if oldInbound.NodeID != nil {
@@ -587,7 +581,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
}
if clients[0].Email != oldEmail {
existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients, nil)
existEmail, err := s.checkEmailsExistForClients(inboundSvc, clients)
if err != nil {
return false, err
}
@@ -731,6 +725,17 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
prevSettings := oldInbound.Settings
oldInbound.Settings = string(newSettings)
// From the stamped wire entry, not from clients[0]: created_at, the
// preserved subId and the WireGuard carry-forward land on interfaceClients.
changedClients, err := settingsEntriesToClients(interfaceClients[:1])
if err != nil {
return false, err
}
var detachEmails []string
if len(oldEmail) > 0 && oldEmail != clients[0].Email {
detachEmails = []string{oldEmail}
}
needRestart := false
// Resolve the push plan before the DB write so a node-state lookup failure
@@ -820,11 +825,9 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo
}
}
}
finalClients, gcErr := inboundSvc.GetClients(oldInbound)
if gcErr != nil {
return gcErr
}
if err := s.SyncInbound(tx, oldInbound.Id, finalClients); err != nil {
// detachEmails covers the rename the guard above refused: the old record
// keeps this inbound's link otherwise, which the full sync used to drop.
if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, changedClients, detachEmails); err != nil {
return err
}
if oldInbound.NodeID != nil {
@@ -998,11 +1001,7 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo
if e := tx.Save(oldInbound).Error; e != nil {
return e
}
finalClients, gcErr := inboundSvc.GetClients(oldInbound)
if gcErr != nil {
return gcErr
}
if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
if err := s.ApplyInboundClientDelta(tx, inboundId, nil, []string{email}); err != nil {
return err
}
if oldInbound.NodeID != nil {