mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-12-04 00:15:09 +03:00
fix(ip-sync): prevent reporter lock inversion with client mutations
Take the PostgreSQL flat reporter fence after its IP writes. Match flat IP row order across bulk cleanup and rename, and discard observations whose row identity disappeared while the report was waiting. Exercise real CRUD and lifecycle overlap in the PostgreSQL CI gate.
This commit is contained in:
@@ -134,6 +134,17 @@ jobs:
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: PostgreSQL IP reporter lock order and lifecycle
|
||||
run: |
|
||||
set -o pipefail
|
||||
go test ./internal/web/service -run '^TestPostgres(NodeIPReporterClientLockOrder|FlatIPReporterLifecycleCommit|PolledAttributionSurvivesConcurrentPrune)$' -count=1 -v | tee /tmp/postgres-ip-reporter-locks.log
|
||||
for test in NodeIPReporterClientLockOrder FlatIPReporterLifecycleCommit PolledAttributionSurvivesConcurrentPrune; do
|
||||
if ! grep -q -- "^--- PASS: TestPostgres${test} " /tmp/postgres-ip-reporter-locks.log; then
|
||||
echo "expected PostgreSQL reporter test TestPostgres${test} to pass" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
|
||||
- name: PostgreSQL Xray traffic retry
|
||||
run: |
|
||||
set -o pipefail
|
||||
|
||||
@@ -1021,9 +1021,9 @@ func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string,
|
||||
if e := tx.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
if e := tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if e := inboundSvc.delClientIPsByEmails(tx, successEmails); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
for _, batch := range chunkInts(successIds, sqlInChunk) {
|
||||
|
||||
@@ -251,14 +251,12 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId
|
||||
// Persist the batch deletion atomically, serialized against the traffic poll
|
||||
// to avoid the cross-transaction lock-order deadlock (runSerializedTx).
|
||||
if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error {
|
||||
var purgeIPs []string
|
||||
for _, t := range targets {
|
||||
if t.emailShared || keepTraffic {
|
||||
continue
|
||||
}
|
||||
if e := inboundSvc.DelClientIPs(tx, t.email); e != nil {
|
||||
logger.Error("Error in delete client IPs")
|
||||
return e
|
||||
}
|
||||
purgeIPs = append(purgeIPs, t.email)
|
||||
if len(t.email) > 0 {
|
||||
if e := inboundSvc.DelClientStat(tx, t.email); e != nil {
|
||||
logger.Error("Delete stats Data Error")
|
||||
@@ -266,6 +264,9 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId
|
||||
}
|
||||
}
|
||||
}
|
||||
if e := inboundSvc.delClientIPsByEmails(tx, purgeIPs); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := commitInboundClientSettings(tx, oldInbound, prevSettings); e != nil {
|
||||
return e
|
||||
}
|
||||
|
||||
@@ -314,9 +314,9 @@ func (s *ClientService) DeleteOrphans() (int, error) {
|
||||
if e := tx.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
if e := tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error; e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
if e := (&InboundService{}).delClientIPsByEmails(tx, emails); e != nil {
|
||||
return e
|
||||
}
|
||||
if e := clearGlobalTraffic(tx, emails...); e != nil {
|
||||
return e
|
||||
|
||||
@@ -101,7 +101,7 @@ func (s *ClientService) ReapSyncOrphans() (int, error) {
|
||||
if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error
|
||||
return (&InboundService{}).delClientIPsByEmails(tx, batch)
|
||||
}); err != nil {
|
||||
return reaped, err
|
||||
}
|
||||
|
||||
@@ -2631,6 +2631,7 @@ func (s *InboundService) updateClientTraffics(tx *gorm.DB, inboundId int, oldCli
|
||||
|
||||
// Drop stats rows for removed emails — but not when a sibling inbound
|
||||
// still references the email, since the row is the shared accumulator.
|
||||
var removedIPs []string
|
||||
for i := range oldClients {
|
||||
email := oldClients[i].Email
|
||||
if email == "" {
|
||||
@@ -2649,11 +2650,11 @@ func (s *InboundService) updateClientTraffics(tx *gorm.DB, inboundId int, oldCli
|
||||
if err := s.DelClientStat(tx, email); err != nil {
|
||||
return err
|
||||
}
|
||||
// Keep inbound_client_ips in sync when the inbound edit drops an
|
||||
// email, so the IP-limit job doesn't keep a ghost tracking row (#4963).
|
||||
if err := s.DelClientIPs(tx, email); err != nil {
|
||||
return err
|
||||
}
|
||||
removedIPs = append(removedIPs, email)
|
||||
}
|
||||
// The IP-limit job must not keep tracking removed clients (#4963).
|
||||
if err := s.delClientIPsByEmails(tx, removedIPs); err != nil {
|
||||
return err
|
||||
}
|
||||
keptEmails := make([]string, 0, len(newClients))
|
||||
keptClients := make(map[string]*model.Client, len(newClients))
|
||||
|
||||
@@ -3,7 +3,9 @@ package service
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
@@ -103,7 +105,7 @@ func mergeInboundClientIps(db *gorm.DB, reporter *model.Node, incomingIps []mode
|
||||
if tx.Error != nil {
|
||||
return tx.Error
|
||||
}
|
||||
if reporter != nil {
|
||||
if reporter != nil && tx.Name() != database.DialectPostgres {
|
||||
if err := lockOnlineNodeIPReporter(tx, reporter); err != nil {
|
||||
tx.Rollback()
|
||||
return err
|
||||
@@ -147,6 +149,9 @@ func mergeInboundClientIps(db *gorm.DB, reporter *model.Node, incomingIps []mode
|
||||
}
|
||||
current = &model.InboundClientIps{}
|
||||
if err := tx.Where("client_email = ?", incoming.ClientEmail).First(current).Error; err != nil {
|
||||
if reporter != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
continue
|
||||
}
|
||||
tx.Rollback()
|
||||
return err
|
||||
}
|
||||
@@ -155,7 +160,21 @@ func mergeInboundClientIps(db *gorm.DB, reporter *model.Node, incomingIps []mode
|
||||
|
||||
// check_client_ip_job rewrites this blob too; an unconditional Update loses
|
||||
// whichever writer commits second and its remote IPs with it (#6587).
|
||||
if err := mergeExistingClientIps(tx, current, incomingEntries, cutoff); err != nil {
|
||||
err := mergeExistingClientIps(tx, current, incomingEntries, cutoff)
|
||||
// The observation belongs to the email in the report. A concurrent
|
||||
// delete or rename can remove it while the poll waits for the row.
|
||||
if reporter != nil && errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Client mutations lock flat IP rows before marking the node dirty.
|
||||
// Take the PostgreSQL reporter lock last and roll back obsolete reports.
|
||||
if reporter != nil && tx.Name() == database.DialectPostgres {
|
||||
if err := lockOnlineNodeIPReporter(tx, reporter); err != nil {
|
||||
tx.Rollback()
|
||||
return err
|
||||
}
|
||||
@@ -181,6 +200,7 @@ func CasUpdateInboundClientIps(tx *gorm.DB, id int, expectedIps, newIps string)
|
||||
|
||||
// Seed the first CAS from the preload; only a competing write requires a re-read.
|
||||
func mergeExistingClientIps(tx *gorm.DB, current *model.InboundClientIps, incoming []model.ClientIpEntry, cutoff int64) error {
|
||||
email := current.ClientEmail
|
||||
for attempt := range ClientIpCasRetries {
|
||||
var oldEntries []model.ClientIpEntry
|
||||
if current.Ips != "" {
|
||||
@@ -191,7 +211,7 @@ func mergeExistingClientIps(tx *gorm.DB, current *model.InboundClientIps, incomi
|
||||
if current.Ips == mergedStr {
|
||||
return nil
|
||||
}
|
||||
ok, err := CasUpdateInboundClientIps(tx, current.Id, current.Ips, mergedStr)
|
||||
ok, err := CasUpdateInboundClientIps(tx.Where("client_email = ?", email), current.Id, current.Ips, mergedStr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -200,7 +220,7 @@ func mergeExistingClientIps(tx *gorm.DB, current *model.InboundClientIps, incomi
|
||||
return nil
|
||||
}
|
||||
if attempt+1 < ClientIpCasRetries {
|
||||
if err := tx.Where("id = ?", current.Id).First(current).Error; err != nil {
|
||||
if err := tx.Where("id = ? AND client_email = ?", current.Id, email).First(current).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -212,6 +232,11 @@ func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail
|
||||
// The caller only renames onto a free identity, so a row already sitting on
|
||||
// newEmail is stale tracking data — drop it instead of failing the edit.
|
||||
if oldEmail != newEmail {
|
||||
if tx.Name() == database.DialectPostgres {
|
||||
if _, err := lockFlatClientIPRows(tx, []string{oldEmail, newEmail}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := tx.Where("client_email = ?", newEmail).Delete(model.InboundClientIps{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -225,15 +250,40 @@ func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error {
|
||||
|
||||
func (s *InboundService) delClientIPsByEmails(tx *gorm.DB, emails []string) error {
|
||||
const chunk = 400
|
||||
postgres := tx.Name() == database.DialectPostgres
|
||||
if postgres {
|
||||
emails = slices.Clone(emails)
|
||||
slices.Sort(emails)
|
||||
}
|
||||
for start := 0; start < len(emails); start += chunk {
|
||||
end := min(start+chunk, len(emails))
|
||||
if err := tx.Where("client_email IN ?", emails[start:end]).Delete(model.InboundClientIps{}).Error; err != nil {
|
||||
query := tx.Where("client_email IN ?", emails[start:end])
|
||||
if postgres {
|
||||
ids, err := lockFlatClientIPRows(tx, emails[start:end])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
continue
|
||||
}
|
||||
query = tx.Where("id IN ?", ids)
|
||||
}
|
||||
if err := query.Delete(model.InboundClientIps{}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Acquire flat IP row locks in the same byte order as the scanner and poller.
|
||||
// The planner may visit a multi-row DELETE's targets in heap order instead.
|
||||
func lockFlatClientIPRows(tx *gorm.DB, emails []string) ([]int, error) {
|
||||
var ids []int
|
||||
err := tx.Model(&model.InboundClientIps{}).Where("client_email IN ?", emails).
|
||||
Order(`client_email COLLATE "C"`).Clauses(clause.Locking{Strength: "UPDATE"}).Pluck("id", &ids).Error
|
||||
return ids, err
|
||||
}
|
||||
|
||||
func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) {
|
||||
db := database.GetDB()
|
||||
InboundClientIps := &model.InboundClientIps{}
|
||||
|
||||
@@ -204,8 +204,8 @@ func nodeClientIpSnapshot(row model.NodeClientIp) clause.Expression {
|
||||
// ErrIneligibleNodeIPReport identifies work invalidated while in flight.
|
||||
var ErrIneligibleNodeIPReport = errors.New("node IP report is no longer eligible")
|
||||
|
||||
// PostgreSQL keeps the reporter stable through commit. SQLite write
|
||||
// transactions already begin IMMEDIATE before checking eligibility.
|
||||
// Keep the reporter stable through commit. The flat PostgreSQL merge calls
|
||||
// this after its IP writes. Attribution and node deletion lock the node first.
|
||||
func lockOnlineNodeIPReporter(tx *gorm.DB, reporter *model.Node) error {
|
||||
var current model.Node
|
||||
query := tx.Select("id", "guid", "scheme", "address", "port", "base_path").
|
||||
|
||||
@@ -862,7 +862,7 @@ func (s *NodeService) Delete(id int) error {
|
||||
return common.NewError(fmt.Sprintf("cannot delete node: %d inbound(s) still attached to it; detach or delete them first", attached))
|
||||
}
|
||||
var n model.Node
|
||||
// Match the reporter-before-attribution lock order of IP sync.
|
||||
// Match the attribution reporter's node-before-attribution order.
|
||||
reporter := tx.Select("guid").Where("id = ?", id)
|
||||
if tx.Name() == database.DialectPostgres {
|
||||
reporter = reporter.Clauses(clause.Locking{Strength: "UPDATE"})
|
||||
|
||||
@@ -0,0 +1,534 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"maps"
|
||||
"slices"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"gorm.io/gorm"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/config"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
|
||||
)
|
||||
|
||||
type nodeIPLockReportKey struct{}
|
||||
|
||||
type nodeIPLockEvent struct {
|
||||
PID int
|
||||
SQL string
|
||||
Err error
|
||||
}
|
||||
|
||||
func nodeIPTestBackend(tx *gorm.DB) nodeIPLockEvent {
|
||||
event := nodeIPLockEvent{SQL: tx.Statement.SQL.String()}
|
||||
event.Err = tx.Session(&gorm.Session{NewDB: true}).Raw("SELECT pg_backend_pid()").Scan(&event.PID).Error
|
||||
return event
|
||||
}
|
||||
|
||||
func waitNodeIPTestValue[T any](t *testing.T, ctx context.Context, ready <-chan T, stage string) T {
|
||||
t.Helper()
|
||||
select {
|
||||
case value := <-ready:
|
||||
return value
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("%s: %v", stage, ctx.Err())
|
||||
var zero T
|
||||
return zero
|
||||
}
|
||||
}
|
||||
|
||||
func nodeIPBlocker(db *gorm.DB, waiter, blocker int) (bool, error) {
|
||||
var blocked bool
|
||||
err := db.Raw("SELECT ? = ANY(pg_blocking_pids(?))", blocker, waiter).Scan(&blocked).Error
|
||||
return blocked, err
|
||||
}
|
||||
|
||||
func waitNodeIPBlocked(t *testing.T, ctx context.Context, db *gorm.DB, waiter, blocker int) {
|
||||
t.Helper()
|
||||
ticker := time.NewTicker(10 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
blocked, err := nodeIPBlocker(db.WithContext(ctx), waiter, blocker)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if blocked {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("backend %d never waited on %d: %v", waiter, blocker, ctx.Err())
|
||||
case <-ticker.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func seedNodeIPLockFixture(t *testing.T, name string, port int, emails ...string) (model.Node, []model.Client) {
|
||||
t.Helper()
|
||||
db := database.GetDB()
|
||||
node := model.Node{
|
||||
Name: name, Guid: name, Scheme: "http", Address: "127.0.0.1", Port: port,
|
||||
BasePath: "/", AllowPrivateAddress: true, ApiToken: "test", Enable: true, Status: "online",
|
||||
}
|
||||
if err := db.Create(&node).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
clients := make([]model.Client, 0, len(emails))
|
||||
for i, email := range emails {
|
||||
clients = append(clients, model.Client{
|
||||
Email: email, SubID: email, Enable: true,
|
||||
ID: fmt.Sprintf("00000000-0000-4000-8000-%012d", port*10+i),
|
||||
})
|
||||
}
|
||||
inbound := model.Inbound{
|
||||
NodeID: &node.Id, UserId: 1, Port: port, Tag: name,
|
||||
Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, clients),
|
||||
}
|
||||
if err := db.Create(&inbound).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := (&ClientService{}).SyncInbound(db, inbound.Id, clients); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return node, clients
|
||||
}
|
||||
|
||||
func TestPostgresNodeIPReporterClientLockOrder(t *testing.T) {
|
||||
if config.GetDBKind() != database.DialectPostgres {
|
||||
t.Skip("requires PostgreSQL row locks")
|
||||
}
|
||||
for _, operation := range []string{"delete", "rename", "bulk_delete"} {
|
||||
t.Run(operation, func(t *testing.T) { testNodeIPReporterClientLockOrder(t, operation) })
|
||||
}
|
||||
}
|
||||
|
||||
func testNodeIPReporterClientLockOrder(t *testing.T, operation string) {
|
||||
t.Helper()
|
||||
setupClientIpTestDB(t)
|
||||
resetTrafficWriterForTest(t)
|
||||
StartTrafficWriter()
|
||||
t.Cleanup(StopTrafficWriter)
|
||||
db := database.GetDB()
|
||||
const target, secondTarget, survivor = "a-target@example.test", "b-target@example.test", "z-survivor@example.test"
|
||||
const healthyEmail = "healthy@example.test"
|
||||
nodeEmails := []string{target, survivor}
|
||||
removed := []string{target}
|
||||
if operation == "bulk_delete" {
|
||||
nodeEmails = append(nodeEmails, secondTarget)
|
||||
removed = append(removed, secondTarget)
|
||||
}
|
||||
node, clients := seedNodeIPLockFixture(t, "contended-edge", 23081, nodeEmails...)
|
||||
healthy, _ := seedNodeIPLockFixture(t, "healthy-edge", 23082, healthyEmail)
|
||||
inbounds, clientService := &InboundService{}, &ClientService{}
|
||||
record, err := clientService.GetRecordByEmail(nil, target)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
before := model.ClientIpEntry{IP: "192.0.2.10", Timestamp: now - 20}
|
||||
refreshed := model.ClientIpEntry{IP: before.IP, Timestamp: now - 2}
|
||||
fresh := model.ClientIpEntry{IP: "192.0.2.20", Timestamp: now - 1}
|
||||
seedEmails := append([]string{healthyEmail}, nodeEmails...)
|
||||
slices.Reverse(seedEmails)
|
||||
for _, email := range seedEmails {
|
||||
if err := db.Create(&model.InboundClientIps{ClientEmail: email, Ips: marshalIps(t, before)}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
payload := marshalIps(t, refreshed, fresh)
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 12*time.Second)
|
||||
defer cancel()
|
||||
reportCtx := context.WithValue(ctx, nodeIPLockReportKey{}, true)
|
||||
mutationLocked := make(chan nodeIPLockEvent, 1)
|
||||
reportWriting := make(chan nodeIPLockEvent, 1)
|
||||
resumeMutation := make(chan struct{})
|
||||
releaseMutation := sync.OnceFunc(func() { close(resumeMutation) })
|
||||
var mutationStarted, reportStarted bool
|
||||
mutationDone, reportDone := make(chan struct{}), make(chan struct{})
|
||||
var mutationErr, reportErr error
|
||||
defer func() {
|
||||
releaseMutation()
|
||||
if mutationStarted {
|
||||
<-mutationDone
|
||||
}
|
||||
if reportStarted {
|
||||
<-reportDone
|
||||
}
|
||||
}()
|
||||
blockMutation := func(tx *gorm.DB) {
|
||||
if tx.Statement.Table != "inbound_client_ips" || tx.RowsAffected == 0 || tx.Error != nil ||
|
||||
tx.Statement.Context.Value(nodeIPLockReportKey{}) != nil {
|
||||
return
|
||||
}
|
||||
select {
|
||||
case mutationLocked <- nodeIPTestBackend(tx):
|
||||
<-resumeMutation
|
||||
default:
|
||||
}
|
||||
}
|
||||
const cb = "test:node_ip_lock_order"
|
||||
var hookedMutation bool
|
||||
mutationHook := func(tx *gorm.DB) {
|
||||
if tx.Statement.Table == "inbound_client_ips" && !hookedMutation {
|
||||
hookedMutation = true
|
||||
blockMutation(tx)
|
||||
}
|
||||
}
|
||||
if operation == "rename" {
|
||||
if err := db.Callback().Update().After("gorm:update").Register(cb+"-mutation", mutationHook); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Callback().Update().Remove(cb + "-mutation") })
|
||||
} else {
|
||||
if err := db.Callback().Delete().After("gorm:delete").Register(cb+"-mutation", mutationHook); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Callback().Delete().Remove(cb + "-mutation") })
|
||||
}
|
||||
if err := db.Callback().Update().Before("gorm:update").Register(cb+"-report", func(tx *gorm.DB) {
|
||||
if tx.Statement.Table == "inbound_client_ips" && tx.Statement.Context.Value(nodeIPLockReportKey{}) != nil {
|
||||
select {
|
||||
case reportWriting <- nodeIPTestBackend(tx):
|
||||
default:
|
||||
}
|
||||
}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Callback().Update().Remove(cb + "-report") })
|
||||
|
||||
mutationStarted = true
|
||||
go func() {
|
||||
defer close(mutationDone)
|
||||
switch operation {
|
||||
case "delete":
|
||||
_, mutationErr = clientService.Delete(inbounds, record.Id, false)
|
||||
case "rename":
|
||||
updated := clients[0]
|
||||
updated.Email = "renamed@example.test"
|
||||
_, mutationErr = clientService.Update(inbounds, record.Id, updated, 0)
|
||||
case "bulk_delete":
|
||||
result, _, err := clientService.BulkDelete(inbounds, []string{secondTarget, target}, false)
|
||||
mutationErr = err
|
||||
if err == nil && (result.Deleted != len(removed) || len(result.Skipped) != 0) {
|
||||
mutationErr = fmt.Errorf("bulk delete did not commit: %+v", result)
|
||||
}
|
||||
}
|
||||
}()
|
||||
mutation := waitNodeIPTestValue(t, ctx, mutationLocked, "mutation holds flat IP row")
|
||||
if mutation.Err != nil {
|
||||
t.Fatal(mutation.Err)
|
||||
}
|
||||
reportStarted = true
|
||||
payloadRows := make([]model.InboundClientIps, 0, len(nodeEmails))
|
||||
for _, email := range nodeEmails {
|
||||
payloadRows = append(payloadRows, model.InboundClientIps{ClientEmail: email, Ips: payload})
|
||||
}
|
||||
go func() {
|
||||
defer close(reportDone)
|
||||
reportErr = inbounds.MergePolledNodeClientIps(reportCtx, &node, payloadRows)
|
||||
}()
|
||||
report := waitNodeIPTestValue(t, ctx, reportWriting, "report attempts flat IP write")
|
||||
if report.Err != nil {
|
||||
t.Fatal(report.Err)
|
||||
}
|
||||
waitNodeIPBlocked(t, ctx, db, report.PID, mutation.PID)
|
||||
|
||||
healthyCtx, stopHealthy := context.WithTimeout(ctx, 2*time.Second)
|
||||
err = inbounds.MergePolledNodeClientIps(healthyCtx, &healthy, []model.InboundClientIps{{ClientEmail: healthyEmail, Ips: payload}})
|
||||
stopHealthy()
|
||||
if err != nil {
|
||||
t.Fatalf("independent reporter stalled: %v", err)
|
||||
}
|
||||
releaseMutation()
|
||||
logNodeIPWaitCycle(t, ctx, db, mutation, report, mutationDone, reportDone)
|
||||
|
||||
for name, err := range map[string]error{"mutation": mutationErr, "report": reportErr} {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "40P01" {
|
||||
t.Errorf("%s SQLSTATE %s: %s\n%s", name, pgErr.Code, pgErr.Detail, pgErr.Where)
|
||||
} else if err != nil {
|
||||
t.Errorf("%s: %v", name, err)
|
||||
}
|
||||
}
|
||||
if t.Failed() {
|
||||
return
|
||||
}
|
||||
var records int64
|
||||
if err := db.Model(&model.ClientRecord{}).Where("email IN ?", removed).Count(&records).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, email := range removed {
|
||||
if _, exists := readClientIps(t, email); exists || records != 0 {
|
||||
t.Fatalf("obsolete email %s survived: IP row=%t, client records=%d", email, exists, records)
|
||||
}
|
||||
}
|
||||
if operation != "rename" {
|
||||
var pending int64
|
||||
if err := db.Model(&model.NodePendingClientDelete{}).Where("node_id = ? AND email IN ?", node.Id, removed).
|
||||
Count(&pending).Error; err != nil || pending != int64(len(removed)) {
|
||||
t.Fatalf("permanent-delete outbox count = %d, want %d: %v", pending, len(removed), err)
|
||||
}
|
||||
}
|
||||
if operation == "rename" {
|
||||
got, exists := readClientIps(t, "renamed@example.test")
|
||||
if !exists || !maps.Equal(got, map[string]int64{before.IP: before.Timestamp}) {
|
||||
t.Fatalf("rename should move only the committed history: %v", got)
|
||||
}
|
||||
}
|
||||
_, _, dirty, generation, err := (&NodeService{}).NodeSyncState(node.Id)
|
||||
if err != nil || !dirty || generation <= node.ConfigDirtyAt {
|
||||
t.Fatalf("dirty generation after %s: dirty=%t generation=%d err=%v", operation, dirty, generation, err)
|
||||
}
|
||||
want := map[string]int64{refreshed.IP: refreshed.Timestamp, fresh.IP: fresh.Timestamp}
|
||||
for _, email := range []string{survivor, healthyEmail} {
|
||||
if got, _ := readClientIps(t, email); !maps.Equal(got, want) {
|
||||
t.Errorf("%s: IP union = %v, want %v", email, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func logNodeIPWaitCycle(t *testing.T, ctx context.Context, db *gorm.DB, mutation, report nodeIPLockEvent, mutationDone, reportDone <-chan struct{}) {
|
||||
t.Helper()
|
||||
ticker := time.NewTicker(10 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-mutationDone:
|
||||
waitNodeIPTestValue(t, ctx, reportDone, "report completion")
|
||||
return
|
||||
case <-reportDone:
|
||||
waitNodeIPTestValue(t, ctx, mutationDone, "mutation completion")
|
||||
return
|
||||
case <-ticker.C:
|
||||
cycle, err := nodeIPBlocker(db.WithContext(ctx), mutation.PID, report.PID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !cycle {
|
||||
continue
|
||||
}
|
||||
var queries []struct {
|
||||
PID int `gorm:"column:pid"`
|
||||
Query string
|
||||
WaitEvent string
|
||||
}
|
||||
if err := db.WithContext(ctx).Raw(
|
||||
"SELECT pid, query, wait_event FROM pg_stat_activity WHERE pid IN (?, ?) ORDER BY pid",
|
||||
mutation.PID, report.PID,
|
||||
).Scan(&queries).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("mutual PostgreSQL blockers: %+v; first mutation: %s", queries, mutation.SQL)
|
||||
var ungranted []struct {
|
||||
PID int `gorm:"column:pid"`
|
||||
Mode string
|
||||
Type string
|
||||
}
|
||||
if err := db.WithContext(ctx).Raw(
|
||||
"SELECT pid, mode, locktype AS type FROM pg_locks WHERE pid IN (?, ?) AND NOT granted ORDER BY pid",
|
||||
mutation.PID, report.PID,
|
||||
).Scan(&ungranted).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Logf("ungranted PostgreSQL locks: %+v", ungranted)
|
||||
waitNodeIPTestValue(t, ctx, mutationDone, "deadlock victim releases mutation")
|
||||
waitNodeIPTestValue(t, ctx, reportDone, "deadlock victim releases report")
|
||||
return
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("waiting for database transactions: %v", ctx.Err())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresFlatIPReporterLifecycleCommit(t *testing.T) {
|
||||
if config.GetDBKind() != database.DialectPostgres {
|
||||
t.Skip("requires PostgreSQL row locks")
|
||||
}
|
||||
for _, change := range []string{"disable", "delete", "endpoint", "guid"} {
|
||||
t.Run(change, func(t *testing.T) { testFlatIPReporterLifecycleCommit(t, change) })
|
||||
}
|
||||
}
|
||||
|
||||
func testFlatIPReporterLifecycleCommit(t *testing.T, change string) {
|
||||
t.Helper()
|
||||
setupClientIpTestDB(t)
|
||||
db := database.GetDB()
|
||||
const first, second = "a@example.test", "z@example.test"
|
||||
node, _ := seedNodeIPLockFixture(t, "replaced-edge", 23083, first, second)
|
||||
now := time.Now().Unix()
|
||||
old := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - 10}
|
||||
fresh := model.ClientIpEntry{IP: "192.0.2.2", Timestamp: now - 1}
|
||||
var rows []model.InboundClientIps
|
||||
for _, email := range []string{first, second} {
|
||||
rows = append(rows, model.InboundClientIps{ClientEmail: email, Ips: marshalIps(t, old)})
|
||||
}
|
||||
if err := db.Create(&rows).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&model.NodeClientIp{NodeGuid: node.Guid, Email: first, Ips: rows[0].Ips}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
payload := marshalIps(t, fresh)
|
||||
for i := range rows {
|
||||
rows[i].Ips = payload
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
reportCtx := context.WithValue(ctx, nodeIPLockReportKey{}, true)
|
||||
staged, resume := make(chan struct{}), make(chan struct{})
|
||||
unblock := sync.OnceFunc(func() { close(resume) })
|
||||
writes := 0
|
||||
const cb = "test:flat_ip_lifecycle_commit"
|
||||
if err := db.Callback().Update().After("gorm:update").Register(cb, func(tx *gorm.DB) {
|
||||
if tx.Statement.Table == "inbound_client_ips" && tx.Statement.Context.Value(nodeIPLockReportKey{}) != nil && tx.RowsAffected == 1 {
|
||||
writes++
|
||||
if writes == len(rows) {
|
||||
close(staged)
|
||||
<-resume
|
||||
}
|
||||
}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Callback().Update().Remove(cb) })
|
||||
inbounds, nodes := &InboundService{}, &NodeService{}
|
||||
reportDone := make(chan error, 1)
|
||||
var reportExited bool
|
||||
defer func() {
|
||||
unblock()
|
||||
if !reportExited {
|
||||
<-reportDone
|
||||
}
|
||||
}()
|
||||
go func() { reportDone <- inbounds.MergePolledNodeClientIps(reportCtx, &node, rows) }()
|
||||
waitNodeIPTestValue(t, ctx, staged, "flat report staged both rows")
|
||||
|
||||
mutationDone := make(chan error, 1)
|
||||
go func() {
|
||||
switch change {
|
||||
case "disable":
|
||||
mutationDone <- nodes.SetEnable(node.Id, false)
|
||||
case "delete":
|
||||
var row model.Inbound
|
||||
if err := db.WithContext(ctx).Where("node_id = ?", node.Id).Take(&row).Error; err != nil {
|
||||
mutationDone <- err
|
||||
return
|
||||
}
|
||||
if _, err := inbounds.DelInbound(row.Id); err != nil {
|
||||
mutationDone <- err
|
||||
return
|
||||
}
|
||||
mutationDone <- nodes.Delete(node.Id)
|
||||
case "endpoint":
|
||||
replacement := node
|
||||
replacement.ApiToken = ""
|
||||
replacement.Port++
|
||||
mutationDone <- nodes.Update(node.Id, &replacement)
|
||||
case "guid":
|
||||
mutationDone <- nodes.UpdateHeartbeat(node.Id, HeartbeatPatch{Guid: "new-guid", Status: "online", LastHeartbeat: now})
|
||||
}
|
||||
}()
|
||||
var mutationExited bool
|
||||
defer func() {
|
||||
unblock()
|
||||
if !mutationExited {
|
||||
<-mutationDone
|
||||
}
|
||||
}()
|
||||
mutationCtx, stopMutation := context.WithTimeout(ctx, 3*time.Second)
|
||||
defer stopMutation()
|
||||
err := waitNodeIPTestValue(t, mutationCtx, mutationDone, "lifecycle update completes while flat rows are staged")
|
||||
mutationExited = true
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unblock()
|
||||
err = waitNodeIPTestValue(t, ctx, reportDone, "obsolete report rolls back")
|
||||
reportExited = true
|
||||
if !errors.Is(err, ErrIneligibleNodeIPReport) {
|
||||
t.Fatalf("report error = %v, want ineligible reporter", err)
|
||||
}
|
||||
for _, email := range []string{first, second} {
|
||||
got, _ := readClientIps(t, email)
|
||||
if !maps.Equal(got, map[string]int64{old.IP: old.Timestamp}) {
|
||||
t.Errorf("%s committed some of the obsolete report: %v", email, got)
|
||||
}
|
||||
}
|
||||
if change == "delete" {
|
||||
var count int64
|
||||
if err := db.Model(&model.NodeClientIp{}).Where("node_guid = ?", node.Guid).Count(&count).Error; err != nil || count != 0 {
|
||||
t.Fatalf("deleted reporter left %d attribution rows: %v", count, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPostgresPolledAttributionSurvivesConcurrentPrune(t *testing.T) {
|
||||
if config.GetDBKind() != database.DialectPostgres {
|
||||
t.Skip("requires PostgreSQL")
|
||||
}
|
||||
setupClientIpTestDB(t)
|
||||
db := database.GetDB()
|
||||
const email = "a@example.test"
|
||||
node, _ := seedNodeIPLockFixture(t, "prune-edge", 23084, email)
|
||||
now := time.Now().Unix()
|
||||
stale := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - clientIpStaleAfterSeconds - 60}
|
||||
renewed := model.ClientIpEntry{IP: stale.IP, Timestamp: now - 1}
|
||||
fresh := model.ClientIpEntry{IP: "192.0.2.2", Timestamp: now}
|
||||
if err := db.Create(&model.NodeClientIp{NodeGuid: node.Guid, Email: email, Ips: marshalIps(t, stale)}).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
read, resume := make(chan struct{}), make(chan struct{})
|
||||
unblock := sync.OnceFunc(func() { close(resume) })
|
||||
var readStale atomic.Bool
|
||||
const cb = "test:park_attribution_prune"
|
||||
if err := db.Callback().Query().After("gorm:query").Register(cb, func(tx *gorm.DB) {
|
||||
if tx.Statement.Table == "node_client_ips" && readStale.CompareAndSwap(false, true) {
|
||||
close(read)
|
||||
<-resume
|
||||
}
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Callback().Query().Remove(cb) })
|
||||
inbounds := &InboundService{}
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second)
|
||||
defer cancel()
|
||||
pruneDone := make(chan error, 1)
|
||||
go func() { pruneDone <- inbounds.PruneStaleClientIps() }()
|
||||
var pruneExited bool
|
||||
defer func() {
|
||||
unblock()
|
||||
if !pruneExited {
|
||||
<-pruneDone
|
||||
}
|
||||
}()
|
||||
waitNodeIPTestValue(t, ctx, read, "pruner has stale attribution snapshot")
|
||||
want := []model.ClientIpEntry{renewed, fresh}
|
||||
if err := inbounds.MergePolledClientIpsByGuid(ctx, &node, map[string]map[string][]model.ClientIpEntry{
|
||||
node.Guid: {email: slices.Clone(want)},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
unblock()
|
||||
err := waitNodeIPTestValue(t, ctx, pruneDone, "stale pruner completes")
|
||||
pruneExited = true
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
trees, err := inbounds.GetClientIpsByGuid()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := trees[node.Guid][email]; !slices.Equal(got, want) {
|
||||
t.Fatalf("pruner lost refreshed attribution: %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user