mirror of
https://github.com/MHSanaei/3x-ui.git
synced 2026-11-19 11:34:59 +03:00
fix(service): serialize client/inbound writes to prevent Postgres deadlock
Client/inbound mutations opened their own transactions that locked client_traffics before inbounds, while the @every 5s traffic poll (AddTraffic, already serialized through the traffic writer) locks them in the opposite order. Concurrently these formed an ABBA lock cycle that Postgres aborted as "deadlock detected" (SQLSTATE 40P01), failing client updates. Route those DB writes through the same single-goroutine traffic writer via a new runSerializedTx helper, so they can never run concurrently with the poll. For the client-edit paths the runtime (node) push is moved after the commit, keeping network I/O out of the serialized section. UpdateInbound keeps its push inside the transaction because EnsureInboundTagAllowed must reach the node before the central row is committed. Covers UpdateInboundClient/addInboundClient/DelInboundClientByEmail/ delInboundClients, the bulk adjust/delete transactions, and UpdateInbound.
This commit is contained in:
@@ -7,7 +7,10 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/database"
|
||||
"github.com/mhsanaei/3x-ui/v3/internal/logger"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -109,6 +112,23 @@ func runTrafficWriter(ctx context.Context, queue chan *trafficWriteRequest, done
|
||||
}
|
||||
}
|
||||
|
||||
// runSerializedTx runs fn inside one DB transaction on the shared serial
|
||||
// traffic-writer goroutine, so it can never execute concurrently with the
|
||||
// @every 5s traffic poll (AddTraffic). Both touch the hot client_traffics and
|
||||
// inbounds rows, and they acquire them in opposite order (the poll locks
|
||||
// inbounds then client_traffics; an admin client/inbound mutation does the
|
||||
// reverse), which Postgres aborts as a deadlock (SQLSTATE 40P01). Routing every
|
||||
// such mutation through this single writer removes that contention entirely.
|
||||
//
|
||||
// Keep network I/O (node pushes) OUT of fn: holding the single writer across a
|
||||
// remote node call would stall all traffic accounting for up to the remote
|
||||
// timeout. Apply runtime changes after this returns.
|
||||
func runSerializedTx(fn func(tx *gorm.DB) error) error {
|
||||
return submitTrafficWrite(func() error {
|
||||
return database.GetDB().Transaction(fn)
|
||||
})
|
||||
}
|
||||
|
||||
func safeApply(fn func() error) (err error) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
|
||||
Reference in New Issue
Block a user