fix(groups): commit adjustment limits with inbound settings

This commit is contained in:
Hamed Sanaei
2026-12-03 12:08:10 +03:30
parent 2aafa4e9b5
commit b0d94724f3
9 changed files with 322 additions and 49 deletions
+3 -3
View File
@@ -201,10 +201,10 @@ jobs:
- name: PostgreSQL frozen group identity
run: |
set -o pipefail
go test ./internal/web/service -run '^TestFrozenGroupBulk(RejectsIdentityAndMembershipChanges|AppliesLinkedTargets)$' -count=1 -v | tee /tmp/postgres-frozen-group-identity.log
go test ./internal/web/service -run '^TestFrozenGroupBulk(RejectsIdentityAndMembershipChanges|AppliesLinkedTargets|AdjustSurvivesMembershipMoveAfterCommit|AdjustRollsBackWhenTrafficWriteFails)$' -count=1 -v | tee /tmp/postgres-frozen-group-identity.log
passed=$(grep -c -- '^--- PASS: TestFrozenGroupBulk' /tmp/postgres-frozen-group-identity.log || true)
if [ "$passed" -ne 2 ]; then
echo "expected 2 passing PostgreSQL frozen group tests, got $passed" >&2
if [ "$passed" -ne 4 ]; then
echo "expected 4 passing PostgreSQL frozen group tests, got $passed" >&2
exit 1
fi
@@ -997,9 +997,10 @@ _openapi:
batch to continue. Send emails for explicit clients or group for
server-resolved members. Optionally send an unfiltered remove
scopeToken from clientPage to reject stale membership while excluding
clients created after the scope was frozen. Clients that leave the
scope during the operation are skipped. Group responses include
skippedCount and at most 20 representative skip records.
clients created after the scope was frozen. Clients are checked before
their first write. If a client changes groups after its first commit,
the adjustment continues for the same client identity. Group responses
include skippedCount and at most 20 representative skip records.
heading: shift-expiry-andor-traffic-quota-for-many-clients-in-one-call-adddaysaddbytes-may-be-negative-clients-with-unlimited-expiry-expirytime0-or-unlimited-traffic-totalgb0-are-skipped-for-the-corresponding-field--bulk-extend-never-converts-unlimited-to-limited-a-client-that-was-auto-disabled-solely-because-it-was-depleted-expired-or-over-quota-is-automatically-re-enabled--locally-and-on-its-node--when-the-adjustment-lifts-it-out-of-depletion-a-manually-disabled-or-still-depleted-client-is-left-disabled-the-optional-flow-directive-sets-the-xtls-flow-on-every-client-none-clears-it-xtls-rprx-visionxtls-rprx-vision-udp443-set-it-where-the-inbound-supports-it-omit-or--to-leave-it-unchanged-the-optional-limithwid-sets-maximum-registered-devices-0--unlimited-the-optional-adtag-sets-mtproto-telegram-sponsor-channel-none-clears-alternatively-send-externallinks-to-append-external-share-links-and-https-subscriptions-to-each-selected-client-in-one-transaction-this-mode-cannot-be-combined-with-other-adjustments-existing-entries-metadata-and-ordering-are-preserved-duplicates-match-kind-value-per-client-including-repeated-input-rows-the-first-entry-wins-missing-clients-are-not-written-and-appear-in-skipped-externallinksadded-counts-inserted-rows-externallinksskipped-counts-duplicate-rows-across-found-clients-externallinkserrors-counts-missing-clients-and-adjusted-counts-clients-receiving-at-least-one-new-row-validation-or-database-failure-aborts-the-whole-append-without-writes-repeating-an-append-is-idempotent-and-does-not-restart-xray
- content: For node-backed changes, the result can include obj.nodeResults and
obj.nodePending alongside the bulk counts and per-email results. A
+1 -1
View File
@@ -12876,7 +12876,7 @@
],
"summary": "Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: \"none\" clears it, \"xtls-rprx-vision\"/\"xtls-rprx-vision-udp443\" set it where the inbound supports it (omit or \"\" to leave it unchanged). The optional limitHwid sets maximum registered devices (0 = unlimited). The optional adTag sets MTProto Telegram sponsor channel (\"none\" clears). Alternatively, send externalLinks to append external share links and http(s) subscriptions to each selected client in one transaction. This mode cannot be combined with other adjustments. Existing entries, metadata, and ordering are preserved. Duplicates match (kind, value) per client, including repeated input rows; the first entry wins. Missing clients are not written and appear in skipped. externalLinks.added counts inserted rows, externalLinks.skipped counts duplicate rows across found clients, externalLinks.errors counts missing clients, and adjusted counts clients receiving at least one new row. Validation or database failure aborts the whole append without writes. Repeating an append is idempotent and does not restart Xray.",
"operationId": "post_panel_api_clients_bulkAdjust",
"description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue. Send emails for explicit clients or group for server-resolved members. Optionally send an unfiltered remove scopeToken from clientPage to reject stale membership while excluding clients created after the scope was frozen. Clients that leave the scope during the operation are skipped. Group responses include skippedCount and at most 20 representative skip records.",
"description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue. Send emails for explicit clients or group for server-resolved members. Optionally send an unfiltered remove scopeToken from clientPage to reject stale membership while excluding clients created after the scope was frozen. Clients are checked before their first write. If a client changes groups after its first commit, the adjustment continues for the same client identity. Group responses include skippedCount and at most 20 representative skip records.",
"requestBody": {
"required": true,
"content": {
+1 -1
View File
@@ -12876,7 +12876,7 @@
],
"summary": "Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: \"none\" clears it, \"xtls-rprx-vision\"/\"xtls-rprx-vision-udp443\" set it where the inbound supports it (omit or \"\" to leave it unchanged). The optional limitHwid sets maximum registered devices (0 = unlimited). The optional adTag sets MTProto Telegram sponsor channel (\"none\" clears). Alternatively, send externalLinks to append external share links and http(s) subscriptions to each selected client in one transaction. This mode cannot be combined with other adjustments. Existing entries, metadata, and ordering are preserved. Duplicates match (kind, value) per client, including repeated input rows; the first entry wins. Missing clients are not written and appear in skipped. externalLinks.added counts inserted rows, externalLinks.skipped counts duplicate rows across found clients, externalLinks.errors counts missing clients, and adjusted counts clients receiving at least one new row. Validation or database failure aborts the whole append without writes. Repeating an append is idempotent and does not restart Xray.",
"operationId": "post_panel_api_clients_bulkAdjust",
"description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue. Send emails for explicit clients or group for server-resolved members. Optionally send an unfiltered remove scopeToken from clientPage to reject stale membership while excluding clients created after the scope was frozen. Clients that leave the scope during the operation are skipped. Group responses include skippedCount and at most 20 representative skip records.",
"description": "For node-backed changes, the result can include obj.nodeResults and obj.nodePending alongside the bulk counts and per-email results. A direct acknowledgment with downstream work pending still allows the batch to continue. Send emails for explicit clients or group for server-resolved members. Optionally send an unfiltered remove scopeToken from clientPage to reject stale membership while excluding clients created after the scope was frozen. Clients are checked before their first write. If a client changes groups after its first commit, the adjustment continues for the same client identity. Group responses include skippedCount and at most 20 representative skip records.",
"requestBody": {
"required": true,
"content": {
+1 -1
View File
@@ -1707,7 +1707,7 @@ export const sections: readonly Section[] = [
'Shift expiry and/or traffic quota for many clients in one call. addDays/addBytes may be negative. Clients with unlimited expiry (expiryTime=0) or unlimited traffic (totalGB=0) are skipped for the corresponding field — bulk extend never converts unlimited to limited. A client that was auto-disabled solely because it was depleted (expired or over quota) is automatically re-enabled — locally and on its node — when the adjustment lifts it out of depletion; a manually-disabled or still-depleted client is left disabled. The optional flow directive sets the XTLS flow on every client: "none" clears it, "xtls-rprx-vision"/"xtls-rprx-vision-udp443" set it where the inbound supports it (omit or "" to leave it unchanged). The optional limitHwid sets maximum registered devices (0 = unlimited). The optional adTag sets MTProto Telegram sponsor channel ("none" clears). Alternatively, send externalLinks to append external share links and http(s) subscriptions to each selected client in one transaction. This mode cannot be combined with other adjustments. Existing entries, metadata, and ordering are preserved. Duplicates match (kind, value) per client, including repeated input rows; the first entry wins. Missing clients are not written and appear in skipped. externalLinks.added counts inserted rows, externalLinks.skipped counts duplicate rows across found clients, externalLinks.errors counts missing clients, and adjusted counts clients receiving at least one new row. Validation or database failure aborts the whole append without writes. Repeating an append is idempotent and does not restart Xray.',
description:
bulkClientNodeApplyDescription +
' Send emails for explicit clients or group for server-resolved members. Optionally send an unfiltered remove scopeToken from clientPage to reject stale membership while excluding clients created after the scope was frozen. Clients that leave the scope during the operation are skipped. Group responses include skippedCount and at most 20 representative skip records.',
' Send emails for explicit clients or group for server-resolved members. Optionally send an unfiltered remove scopeToken from clientPage to reject stale membership while excluding clients created after the scope was frozen. Clients are checked before their first write. If a client changes groups after its first commit, the adjustment continues for the same client identity. Group responses include skippedCount and at most 20 representative skip records.',
requestSchema: {
type: 'object',
oneOf: [{ required: ['emails'] }, { required: ['group'] }],
+123 -23
View File
@@ -325,6 +325,8 @@ type bulkAdjustEntry struct {
// client. The vision values are the only positive flows xray accepts.
const bulkFlowClear = "none"
var errGroupAdjustLimitsChanged = errors.New("client limits changed during the group adjustment")
// bulkFlowAllowed whitelists the flow directives BulkAdjust accepts. Anything
// outside this set is treated as "" (leave flow untouched) so a malformed or
// hostile value can never be injected into a client's settings. The dropdown in
@@ -352,7 +354,9 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string,
}
func (s *ClientService) BulkAdjustGroup(inboundSvc *InboundService, scope *GroupBulkScope, addDays int, addBytes int64, flow string, limitHwid *int, adTag string) (BulkAdjustResult, bool, error) {
return s.bulkAdjust(inboundSvc, scope.emails, scope, addDays, addBytes, flow, limitHwid, adTag)
operation := *scope
operation.committedAdjustments = make(map[string]bool)
return s.bulkAdjust(inboundSvc, scope.emails, &operation, addDays, addBytes, flow, limitHwid, adTag)
}
func (s *ClientService) bulkAdjust(inboundSvc *InboundService, emails []string, scope *GroupBulkScope, addDays int, addBytes int64, flow string, limitHwid *int, adTag string) (BulkAdjustResult, bool, error) {
@@ -493,6 +497,7 @@ func (s *ClientService) bulkAdjust(inboundSvc *InboundService, emails []string,
adTagHonored := map[string]bool{}
adTagIneligible := map[string]bool{}
execFailed := map[string]bool{}
wasDisabledDepleted := map[string]struct{}{}
adjustIds := sortedInboundIds(emailsByInbound)
adjustResults, adjustPanics := fanoutClientInboundResults(adjustIds, inboundFanoutConcurrency, func(i int) bulkInboundAdjustResult {
return s.bulkAdjustInboundClients(inboundSvc, adjustIds[i], emailsByInbound[adjustIds[i]], plan, scope, flow, adTag)
@@ -511,6 +516,9 @@ func (s *ClientService) bulkAdjust(inboundSvc *InboundService, emails []string,
if ibRes.needRestart {
needRestart = true
}
for _, email := range ibRes.disabledDepleted {
wasDisabledDepleted[email] = struct{}{}
}
for email := range ibRes.flowHonored {
flowHonored[email] = true
}
@@ -534,21 +542,16 @@ func (s *ClientService) bulkAdjust(inboundSvc *InboundService, emails []string,
cond, condArgs := depletedCond(db)
candidateEmails := make([]string, 0, len(plan))
for email, entry := range plan {
if entry.applyExpiry || entry.applyTotal {
if (entry.applyExpiry || entry.applyTotal) && (scope == nil || !scope.committedAdjustments[email]) {
candidateEmails = append(candidateEmails, email)
}
}
wasDisabledDepleted := map[string]struct{}{}
for _, batch := range chunkStrings(candidateEmails, sqlInChunk) {
var rows []string
if err := db.Model(xray.ClientTraffic{}).
Where(cond+" AND enable = ? AND email IN ?", append(append([]any{}, condArgs...), false, batch)...).
Pluck("email", &rows).Error; err != nil {
return result, needRestart, err
}
for _, e := range rows {
wasDisabledDepleted[e] = struct{}{}
}
disabled, err := bulkAdjustDisabledDepleted(db, candidateEmails, cond, condArgs)
if err != nil {
return result, needRestart, err
}
for _, email := range disabled {
wasDisabledDepleted[email] = struct{}{}
}
wantAdTag := ""
@@ -557,6 +560,11 @@ func (s *ClientService) bulkAdjust(inboundSvc *InboundService, emails []string,
}
adjusted := map[string]struct{}{}
if scope != nil {
for email := range scope.committedAdjustments {
adjusted[email] = struct{}{}
}
}
apply := func(tx *gorm.DB, email string) (bool, error) {
entry := plan[email]
updates := map[string]any{}
@@ -566,7 +574,7 @@ func (s *ClientService) bulkAdjust(inboundSvc *InboundService, emails []string,
if entry.applyTotal {
updates["total"] = entry.newTotal
}
if len(updates) > 0 {
if len(updates) > 0 && (scope == nil || !scope.committedAdjustments[email]) {
if err := tx.Model(xray.ClientTraffic{}).Where("email = ?", email).Updates(updates).Error; err != nil {
return false, err
}
@@ -595,7 +603,7 @@ func (s *ClientService) bulkAdjust(inboundSvc *InboundService, emails []string,
}
var candidates []string
for email := range plan {
if !execFailed[email] {
if !execFailed[email] && (scope == nil || !scope.committedAdjustments[email] || adjustHwid || adTagHonored[email]) {
candidates = append(candidates, email)
}
}
@@ -642,6 +650,7 @@ func (s *ClientService) bulkAdjust(inboundSvc *InboundService, emails []string,
}
for _, email := range changed {
adjusted[email] = struct{}{}
scope.committedAdjustments[email] = true
}
}
}
@@ -717,8 +726,9 @@ func (s *ClientService) bulkAdjust(inboundSvc *InboundService, emails []string,
}
type bulkInboundAdjustResult struct {
perEmailSkipped map[string]string
flowHonored map[string]bool
perEmailSkipped map[string]string
disabledDepleted []string
flowHonored map[string]bool
// flowIneligible is tracked apart from perEmailSkipped: a flow directive
// that an inbound cannot carry must not suppress the expiry/total write for
// the same client (which would diverge the inbound JSON / ClientRecord from
@@ -889,10 +899,27 @@ func (s *ClientService) bulkAdjustInboundClients(
// Serialize against the traffic poll to avoid the cross-transaction
// lock-order deadlock on inbounds/client_records (runSerializedTx).
txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error {
if err := scope.checkInbound(tx, inboundId, emails); err != nil {
var limited, previouslyDepleted []string
txErr := mutation.commitThen(oldInbound, nodeClientDelta, func(tx *gorm.DB) error {
records, err := scope.inboundRecords(tx, inboundId, emails)
if err != nil {
return err
}
for email, current := range records {
entry := plan[email]
total, expiry := entry.record.TotalGB, entry.record.ExpiryTime
if scope.committedAdjustments[email] {
if entry.applyTotal {
total = entry.newTotal
}
if entry.applyExpiry {
expiry = entry.newExpiry
}
}
if (entry.applyTotal && current.TotalGB != total) || (entry.applyExpiry && current.ExpiryTime != expiry) {
return errGroupAdjustLimitsChanged
}
}
if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil {
return err
}
@@ -903,10 +930,38 @@ func (s *ClientService) bulkAdjustInboundClients(
if err := s.SyncInbound(tx, inboundId, finalClients); err != nil {
return err
}
return nil
if scope == nil {
return nil
}
for email := range foundEmails {
entry := plan[email]
if !scope.committedAdjustments[email] && (entry.applyExpiry || entry.applyTotal) {
limited = append(limited, email)
}
}
if len(limited) == 0 {
return nil
}
// Commit enforcement limits before delivering any runtime changes.
cond, args := depletedCond(tx)
previouslyDepleted, err = bulkAdjustDisabledDepleted(tx, limited, cond, args)
if err != nil {
return err
}
return writeBulkAdjustTrafficLimits(tx, limited, plan)
}, func() {
if scope == nil || scope.committedAdjustments == nil {
return
}
for email := range foundEmails {
entry := plan[email]
if entry.applyExpiry || entry.applyTotal || res.flowHonored[email] || res.adTagHonored[email] {
scope.committedAdjustments[email] = true
}
}
})
if txErr != nil {
if !errors.Is(txErr, errGroupSelectionStale) {
if !errors.Is(txErr, errGroupSelectionStale) && !errors.Is(txErr, errGroupAdjustLimitsChanged) {
s.recordClientNodeFailure(oldInbound.NodeID, &txErr)
}
for email := range foundEmails {
@@ -915,6 +970,7 @@ func (s *ClientService) bulkAdjustInboundClients(
}
}
} else {
res.disabledDepleted = previouslyDepleted
if adTagChanged && oldInbound.Protocol == model.MTProto && oldInbound.NodeID == nil {
inboundSvc.applyLocalMtproto(oldInbound.Id)
}
@@ -1333,7 +1389,7 @@ func (s *ClientService) bulkDelInboundClients(
}
var pending []model.NodePendingClientDelete
txErr := mutation.commit(oldInbound, nodeFullClientDelete, func(tx *gorm.DB) error {
if err := scope.checkInbound(tx, inboundId, emails); err != nil {
if _, err := scope.inboundRecords(tx, inboundId, emails); err != nil {
return err
}
if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil {
@@ -1977,7 +2033,7 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService,
}
txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error {
if err := scope.checkInbound(tx, inboundId, emails); err != nil {
if _, err := scope.inboundRecords(tx, inboundId, emails); err != nil {
return err
}
if e := commitInboundClientSettings(tx, oldInbound, prevSettings); e != nil {
@@ -2045,3 +2101,47 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService,
return res
}
func bulkAdjustDisabledDepleted(tx *gorm.DB, emails []string, cond string, condArgs []any) ([]string, error) {
var disabled []string
for _, batch := range chunkStrings(emails, sqlInChunk) {
var rows []string
if err := tx.Model(xray.ClientTraffic{}).
Where(cond+" AND enable = ? AND email IN ?", append(append([]any{}, condArgs...), false, batch)...).
Pluck("email", &rows).Error; err != nil {
return nil, err
}
disabled = append(disabled, rows...)
}
return disabled, nil
}
// Lock the relevant clients before calling this. The email uniquely identifies the traffic row.
func writeBulkAdjustTrafficLimits(tx *gorm.DB, emails []string, plan map[string]*bulkAdjustEntry) error {
for _, batch := range chunkStrings(emails, sqlInChunk/3) {
var expiryArgs, totalArgs []any
var expiryCases, totalCases strings.Builder
for _, email := range batch {
entry := plan[email]
if entry.applyExpiry {
expiryCases.WriteString(" WHEN ? THEN CAST(? AS BIGINT)")
expiryArgs = append(expiryArgs, email, entry.newExpiry)
}
if entry.applyTotal {
totalCases.WriteString(" WHEN ? THEN CAST(? AS BIGINT)")
totalArgs = append(totalArgs, email, entry.newTotal)
}
}
values := make(map[string]any, 2)
if len(expiryArgs) != 0 {
values["expiry_time"] = gorm.Expr("CASE email"+expiryCases.String()+" ELSE expiry_time END", expiryArgs...)
}
if len(totalArgs) != 0 {
values["total"] = gorm.Expr("CASE email"+totalCases.String()+" ELSE total END", totalArgs...)
}
if err := tx.Model(xray.ClientTraffic{}).Where("email IN ?", batch).UpdateColumns(values).Error; err != nil {
return err
}
}
return nil
}
@@ -20,6 +20,8 @@ type GroupBulkScope struct {
group string
emails []string
ids map[string]int
// Only the adjustment's serialized writer publishes completed inbound mutations.
committedAdjustments map[string]bool
}
func groupClientEmails(rows []groupClientIdentity) []string {
@@ -66,7 +68,10 @@ func (scope *GroupBulkScope) records(db *gorm.DB, emails []string, lock bool) (m
slices.Sort(ids)
matches := make(map[string]*model.ClientRecord, len(ids))
for _, batch := range chunkInts(ids, sqlInChunk) {
q := db.Where("id IN ? AND group_name = ?", batch, scope.group).Order("id")
q := db.Where("id IN ?", batch).Order("id")
if scope.committedAdjustments == nil {
q = q.Where("group_name = ?", scope.group)
}
if lock && db.Name() == database.DialectPostgres {
q = q.Clauses(clause.Locking{Strength: "UPDATE"})
}
@@ -75,7 +80,7 @@ func (scope *GroupBulkScope) records(db *gorm.DB, emails []string, lock bool) (m
return nil, err
}
for i := range rows {
if scope.ids[rows[i].Email] == rows[i].Id {
if scope.ids[rows[i].Email] == rows[i].Id && (rows[i].Group == scope.group || scope.committedAdjustments[rows[i].Email]) {
matches[rows[i].Email] = &rows[i]
}
}
@@ -84,16 +89,16 @@ func (scope *GroupBulkScope) records(db *gorm.DB, emails []string, lock bool) (m
}
// Lock the original records and check the link used to plan this inbound write.
func (scope *GroupBulkScope) checkInbound(tx *gorm.DB, inboundID int, emails []string) error {
func (scope *GroupBulkScope) inboundRecords(tx *gorm.DB, inboundID int, emails []string) (map[string]*model.ClientRecord, error) {
if scope == nil {
return nil
return nil, nil
}
records, err := scope.records(tx, emails, true)
if err != nil {
return err
return nil, err
}
if len(records) != len(emails) {
return errGroupSelectionStale
return nil, errGroupSelectionStale
}
ids := make([]int, 0, len(records))
for _, rec := range records {
@@ -108,13 +113,13 @@ func (scope *GroupBulkScope) checkInbound(tx *gorm.DB, inboundID int, emails []s
q = q.Clauses(clause.Locking{Strength: "UPDATE"})
}
if err := q.Pluck("client_id", &linked).Error; err != nil {
return err
return nil, err
}
if len(linked) != len(batch) {
return errGroupSelectionStale
return nil, errGroupSelectionStale
}
}
return nil
return records, nil
}
func (scope *GroupBulkScope) skipReason() string {
@@ -1,26 +1,36 @@
package service
import (
"context"
"errors"
"fmt"
"sync"
"testing"
"time"
"gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
"github.com/mhsanaei/3x-ui/v3/internal/testpg"
"github.com/mhsanaei/3x-ui/v3/internal/web/runtime"
)
func setupFrozenGroupBulkDB(t *testing.T) {
t.Helper()
cleanup, err := testpg.IsolatePackage("frozen_group_bulk")
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanup)
setupBulkDB(t)
}
func TestFrozenGroupBulkRejectsIdentityAndMembershipChanges(t *testing.T) {
for _, operation := range []string{"adjust", "delete"} {
for _, change := range []string{"replace", "move"} {
t.Run(operation+"/"+change, func(t *testing.T) {
cleanup, err := testpg.IsolatePackage("frozen_group_bulk")
if err != nil {
t.Fatal(err)
}
t.Cleanup(cleanup)
setupBulkDB(t)
setupFrozenGroupBulkDB(t)
db := database.GetDB()
svc, inboundSvc := &ClientService{}, &InboundService{}
client := model.Client{Email: "frozen@example.test", Group: "staff", ID: "11111111-1111-1111-1111-111111111111", TotalGB: 1024, Enable: true}
@@ -110,7 +120,7 @@ func TestFrozenGroupBulkRejectsIdentityAndMembershipChanges(t *testing.T) {
}
func TestFrozenGroupBulkAppliesLinkedTargets(t *testing.T) {
setupBulkDB(t)
setupFrozenGroupBulkDB(t)
svc, inboundSvc := &ClientService{}, &InboundService{}
client := model.Client{Email: "linked-group@example.test", Group: "staff", ID: "11111111-1111-1111-1111-111111111111", TotalGB: 1024, Enable: true}
ib := mkInbound(t, 41001, model.VLESS, clientsSettings(t, []model.Client{client}))
@@ -142,3 +152,153 @@ func TestFrozenGroupBulkAppliesLinkedTargets(t *testing.T) {
t.Fatalf("deleted client still present: %d (%v)", rows, err)
}
}
type groupAdjustBarrierRuntime struct {
fakeNodeRuntime
entered chan struct{}
release chan struct{}
}
func (r *groupAdjustBarrierRuntime) UpdateUser(ctx context.Context, _ *model.Inbound, _ string, _ model.Client) (runtime.ClientApplyResult, error) {
select {
case r.entered <- struct{}{}:
default:
}
select {
case <-r.release:
return runtime.ClientApplyResult{}, nil
case <-ctx.Done():
return runtime.ClientApplyResult{}, ctx.Err()
}
}
func TestFrozenGroupBulkAdjustSurvivesMembershipMoveAfterCommit(t *testing.T) {
setupClientNodeOrderDB(t)
nodeID, _ := setupNodeRuntime(t)
barrier := &groupAdjustBarrierRuntime{entered: make(chan struct{}, 1), release: make(chan struct{})}
runtime.GetManager().SetRuntimeOverride(nodeID, barrier)
const originalTotal = 1024
const newTotal = 2048
oldExpiry := time.Now().Add(48 * time.Hour).UnixMilli()
newExpiry := oldExpiry + reenableDay
client := model.Client{Email: "moving@example.test", Group: "staff", ID: "11111111-1111-1111-1111-111111111111",
TotalGB: originalTotal, ExpiryTime: oldExpiry}
svc, inboundSvc := &ClientService{}, &InboundService{}
remote := nodeInbound(t, nodeID, 41001, []model.Client{client})
local := mkInbound(t, 41002, model.VLESS, clientsSettings(t, []model.Client{client}))
if err := svc.SyncInbound(nil, local.Id, []model.Client{client}); err != nil {
t.Fatal(err)
}
mkTraffic(t, remote.Id, client.Email, originalTotal, 0, originalTotal, oldExpiry, false)
page, err := svc.ListGroupClients(t.Context(), GroupClientPageParams{Group: "staff", Mode: "remove", Freeze: true})
if err != nil || page.Total != 1 {
t.Fatalf("freeze: %+v, %v", page, err)
}
scope, err := ResolveGroupBulkScope(t.Context(), "staff", page.ScopeToken)
if err != nil {
t.Fatal(err)
}
siblingLock := lockInbound(local.Id)
unlockSibling := sync.OnceFunc(siblingLock.Unlock)
releaseNode := sync.OnceFunc(func() { close(barrier.release) })
type outcome struct {
result BulkAdjustResult
err error
}
done := make(chan outcome, 1)
var operation sync.WaitGroup
t.Cleanup(func() {
unlockSibling()
releaseNode()
operation.Wait()
})
operation.Go(func() {
res, _, err := svc.BulkAdjustGroup(inboundSvc, scope, 1, newTotal-originalTotal, "", nil, "")
done <- outcome{res, err}
})
select {
case <-barrier.entered:
case <-time.After(nodeClientPushTimeout):
t.Fatal("adjustment never reached post-commit node delivery")
}
if got := trafficOf(t, client.Email); got.Total != newTotal || got.ExpiryTime != newExpiry {
t.Errorf("traffic limits at the post-commit barrier: %+v", got)
}
if moved, err := svc.AddToGroup([]string{client.Email}, "new-group"); err != nil || moved != 1 {
t.Fatalf("move while node apply waits: %d (%v)", moved, err)
}
unlockSibling()
releaseNode()
applied := <-done
if got := trafficOf(t, client.Email); got.Total != newTotal || got.ExpiryTime != newExpiry || got.Up != originalTotal || !got.Enable {
t.Errorf("traffic after committed adjust and group move: %+v", got)
}
record, err := svc.GetRecordByEmail(nil, client.Email)
if err != nil || record.Group != "new-group" || record.TotalGB != newTotal || record.ExpiryTime != newExpiry || !record.Enable {
t.Errorf("record after committed adjust and group move: %+v (%v)", record, err)
}
for _, attached := range []*model.Inbound{remote, local} {
inbound, err := inboundSvc.GetInbound(attached.Id)
if err != nil {
t.Fatal(err)
}
list, err := inboundSvc.GetClients(inbound)
if err != nil || len(list) != 1 || list[0].Group != "new-group" || list[0].TotalGB != newTotal || list[0].ExpiryTime != newExpiry || !list[0].Enable {
t.Errorf("inbound %d after committed adjust and group move: %+v (%v)", attached.Id, list, err)
}
}
if applied.err != nil || applied.result.Adjusted != 1 || len(applied.result.Skipped) != 0 {
t.Errorf("adjust result: %+v (%v)", applied.result, applied.err)
}
}
func TestFrozenGroupBulkAdjustRollsBackWhenTrafficWriteFails(t *testing.T) {
setupFrozenGroupBulkDB(t)
db := database.GetDB()
svc, inboundSvc := &ClientService{}, &InboundService{}
client := model.Client{Email: "rollback@example.test", Group: "rollback-group", ID: "11111111-1111-1111-1111-111111111111",
TotalGB: 1024, Enable: true}
inbound := mkInbound(t, 41003, model.VLESS, clientsSettings(t, []model.Client{client}))
if err := svc.SyncInbound(nil, inbound.Id, []model.Client{client}); err != nil {
t.Fatal(err)
}
mkTraffic(t, inbound.Id, client.Email, 1, 0, 1024, 0, true)
page, err := svc.ListGroupClients(t.Context(), GroupClientPageParams{Group: client.Group, Mode: "remove", Freeze: true})
if err != nil || page.Total != 1 {
t.Fatalf("freeze: %+v, %v", page, err)
}
scope, err := ResolveGroupBulkScope(t.Context(), client.Group, page.ScopeToken)
if err != nil {
t.Fatal(err)
}
const callback = "test:fail_adjust_traffic_write"
writeErr := errors.New("injected client traffic write failure")
if err := db.Callback().Update().Before("gorm:update").Register(callback, func(tx *gorm.DB) {
if tx.Statement.Table == "client_traffics" {
_ = tx.AddError(writeErr)
}
}); err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) })
result, _, err := svc.BulkAdjustGroup(inboundSvc, scope, 0, 1024, "", nil, "")
if err != nil || result.Adjusted != 0 || len(result.Skipped) != 1 || result.Skipped[0].Reason != writeErr.Error() {
t.Fatalf("expected a rolled-back adjust, got %+v (%v)", result, err)
}
record, err := svc.GetRecordByEmail(nil, client.Email)
if err != nil || record.TotalGB != 1024 {
t.Errorf("normalized quota after rollback: %+v (%v)", record, err)
}
current, err := inboundSvc.GetInbound(inbound.Id)
if err != nil || current.Settings != inbound.Settings {
t.Errorf("inbound settings after rollback: %+v (%v)", current, err)
}
if got := trafficOf(t, client.Email); got.Total != 1024 || got.Up != 1 {
t.Errorf("traffic after rollback: %+v", got)
}
}
+8 -1
View File
@@ -190,8 +190,12 @@ func (m *inboundClientMutation) close() {
}
func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWork, write func(*gorm.DB) error) error {
return m.commitThen(inbound, work, write, nil)
}
func (m *inboundClientMutation) commitThen(inbound *model.Inbound, work nodeConfigWork, write func(*gorm.DB) error, afterCommit func()) error {
if inbound.NodeID == nil {
return runSerializedTx(write)
return runSerializedTxThen(write, afterCommit)
}
nodeID := *inbound.NodeID
queuedAt := time.Now()
@@ -204,6 +208,9 @@ func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWo
return (&NodeService{}).MarkNodeDirtyTx(tx, nodeID)
}, func() {
m.turn = reserveNodeConfigTurn(nodeID, inbound.Id, work)
if afterCommit != nil {
afterCommit()
}
})
if !startedAt.IsZero() {
logger.Debugf("client node save: node_id=%d writer_wait_ms=%d tx_ms=%d success=%t", nodeID,