diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cd6827ab2..9639a7fc8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -147,10 +147,10 @@ jobs: - name: PostgreSQL node client push ordering run: | set -o pipefail - go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush)$' -count=1 -v | tee /tmp/postgres-node-client-order.log + go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeClientCapacityPreservesPermanentDelete|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush)$' -count=1 -v | tee /tmp/postgres-node-client-order.log passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-client-order.log || true) - if [ "$passed" -ne 7 ]; then - echo "expected 7 passing PostgreSQL node client ordering tests, got $passed" >&2 + if [ "$passed" -ne 8 ]; then + echo "expected 8 passing PostgreSQL node client ordering tests, got $passed" >&2 exit 1 fi diff --git a/docs/architecture.md b/docs/architecture.md index 06e27193c..33d3f3781 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -390,6 +390,19 @@ merged with GUID-based baselines to avoid double counting after resets. `model.NodeClientTraffic`, `model.ClientGlobalTraffic` (cross-master totals). A client reset is queued per hosting node in `model.NodePendingReset` (`service/node_reset_queue.go`) and replayed by the node sync until the node accepts it. + +Client mutations reserve node dispatch turns when their local transactions commit. The writer and +inbound mutex are released before dispatch waits. Conflicting inbounds are ordered, independent +inbounds can use any of four live slots on a node, and full deletion and reconciliation use an +exclusive node turn. Each live push waits up to four seconds for its turn and then receives up to +four seconds for the whole RPC batch. A saturated delta is left dirty for reconciliation. Full +deletions are stored in the transactional node outbox and retried until the direct peer confirms +deletion or absence. HTTP requests can also include validation, writer waits and multiple waves of +inbound work. A direct acknowledgment can report downstream work pending alongside these results. + +Node traffic polls run independently within the shared worker limit. The publisher sums the latest +valid speed sample from every eligible node. Display samples expire after two five-second windows +and leave the cumulative counter baseline available for the next poll. Periodic resets: `job/periodic_traffic_reset_job.go` (keyed off `Inbound.TrafficReset`). Cross-panel totals are stored per master GUID and hosted email, separately from local diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index 8c344b2ce..725bcacf2 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -812,6 +812,16 @@ _openapi: (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: create-a-new-client-and-attach-it-to-one-or-more-inbounds-in-a-single-call-body-is-json-per-protocol-secrets-are-generated-server-side-when-omitted-so-callers-can-send-only-the-universal-fields - content: Uses the same calendar and catch-up calculation as auto-renew in the panel timezone. resetWeekday is 1 (Monday) to 7 (Sunday), 0 disables @@ -823,7 +833,8 @@ _openapi: preview is informational and does not reserve an allowance or guarantee node availability. heading: preview-client-auto-renewal-dates-without-saving-or-resetting-anything - - content: 'An omitted `flow` leaves every attached inbound on its own flow. Send + - content: >- + An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. @@ -834,9 +845,20 @@ _openapi: still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in - place.' + place. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below - - content: 'Query-parameter alias for the path endpoint. Use email=. or email=.. + - content: >- + Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, @@ -849,9 +871,20 @@ _openapi: still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in - place.' + place. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: update-an-existing-client-by-email-changes-propagate-to-every-attached-inbound-body-is-the-json-client-payload-omitted-fields-keep-their-current-values-and-an-explicit-zero-empty-or-null-value-clears-a-field-except-as-noted-below-1 - - content: 'The inbounds are applied concurrently and independently: one that + - content: >- + The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can @@ -859,9 +892,20 @@ _openapi: record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` - prefix and leaves the client already removed from every inbound.' + prefix and leaves the client already removed from every inbound. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed - - content: 'Query-parameter alias for the path endpoint. Use email=. or email=.. + - content: >- + Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the @@ -871,23 +915,55 @@ _openapi: record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` - prefix and leaves the client already removed from every inbound.' + prefix and leaves the client already removed from every inbound. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: delete-a-client-by-email-removes-it-from-every-attached-inbound-and-drops-its-traffic-record-unless-keeptraffic1-is-passed-1 - - content: 'A WireGuard client brings its stored `allowedIPs` into the new inbound + - content: >- + A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still - attached and a `success:false` response can be partial.' + attached and a `success:false` response can be partial. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: attach-an-existing-client-to-one-or-more-additional-inbounds-body-is-json - - content: 'The inbounds are applied concurrently and independently: one that + - content: >- + The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing - beyond the inbounds, so every error carries the prefix.' + beyond the inbounds, so every error carries the prefix. + + + For node-backed inbounds, `obj.nodeResults` reports each affected + node. `applied` means the direct peer acknowledged the change with no + reported downstream work, `pending` means a locally saved change still + needs reconciliation, and `failed` means a local inbound write failed. + For several inbounds on one node, the least complete result is + reported. `obj.nodePending` is true when any local change still needs + reconciliation. The outer `success` continues to report local save + success. `obj` is null when no node result is available. heading: detach-a-client-from-one-or-more-inbounds-without-deleting-the-client - content: The original credentials remain the primary device. Additional devices share their parent client email, traffic quota, expiry and enable @@ -909,6 +985,41 @@ _openapi: previously downloaded configuration loses access after the configuration is applied. heading: delete-an-additional-wireguard-device-and-release-its-address + - content: 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. + 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 + direct acknowledgment with downstream work pending still allows the + batch to continue. + heading: enable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-add-each-user-note-that-enabling-a-client-whose-quota-is-exhausted-or-whose-expiry-has-passed-only-flips-the-flag--the-traffic-loop-will-disable-it-again-on-the-next-tick-returns-the-changed-count-and-per-email-skip-reasons + - content: 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. + heading: disable-many-clients-in-one-call-emails-are-grouped-by-inbound-and-applied-with-a-single-read-modify-write-per-inbound-the-running-xray-local-or-remote-node-is-updated-to-remove-each-user-returns-the-changed-count-and-per-email-skip-reasons + - content: 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. + heading: delete-many-clients-in-one-call-the-server-processes-the-list-sequentially-so-each-delete-sees-the-committed-state-of-the-previous-one--avoids-the-race-the-per-email-fan-out-had-on-the-panel-side-pass-keeptraffictrue-to-retain-the-xray_client_traffic-rows-after-deletion + - content: 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. + heading: create-many-clients-in-one-call-body-is-a-json-array-of-client-inboundids-payloads--the-same-shape-add-accepts-items-are-processed-sequentially-per-email-skip-reasons-are-returned-for-items-that-fail-eg-duplicate-email-triggers-a-single-xray-restart-at-the-end-if-any-inbound-was-running + - content: 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. + heading: attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-explicit-email-requests-return-per-email-lists-alternatively-submit-selection-with-explicit-clientids-or-a-frozen-allmatching-scopetoken-plus-excludedclientids-and-the-search-and-group-it-was-frozen-under-scoped-requests-start-a-background-job-and-return-jobid-poll-get-bulkattachid-for-counts-or-a-stale-selection-error-newer-ids-stay-outside-the-frozen-scope-changes-to-the-frozen-membership-are-rejected-before-applying-changes-triggers-a-single-xray-restart-if-any-target-inbound-was-running + - content: 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. + heading: mirror-of-bulkattach-detach-many-existing-clients-from-many-inbounds-in-one-call-for-each-email-intersects-the-clients-current-inbounds-with-the-requested-set-and-detaches-from-those-only-email-inbound-pairs-where-the-client-is-not-currently-attached-are-silently-no-ops-emails-not-attached-to-any-of-the-requested-inbounds-are-reported-under-skipped-client-records-are-kept-even-if-they-become-orphaned--use-bulkdel-for-full-removal-returns-per-email-detachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running --- {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 4877ccf2d..fee39fb9a 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -2114,6 +2114,16 @@ ], "nullable": true }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, "skipped": { "example": [], "items": { @@ -2127,6 +2137,170 @@ ], "type": "object" }, + "BulkAttachResult": { + "description": "BulkAttachResult reports the outcome of a bulk attach across target inbounds.", + "properties": { + "attached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, + "BulkCreateReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkCreateResult": { + "description": "BulkCreateResult mirrors BulkAdjustResult for the create flow.", + "properties": { + "created": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkCreateReport" + }, + "type": "array" + } + }, + "required": [ + "created" + ], + "type": "object" + }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, + "BulkDetachResult": { + "description": "BulkDetachResult reports the outcome of a bulk detach across target inbounds.", + "properties": { + "detached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -2149,6 +2323,48 @@ ], "type": "object" }, + "BulkSetEnableReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkSetEnableResult": { + "properties": { + "changed": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkSetEnableReport" + }, + "type": "array" + } + }, + "required": [ + "changed" + ], + "type": "object" + }, "Client": { "description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.", "properties": { @@ -2419,6 +2635,42 @@ ], "type": "object" }, + "ClientNodeApplyOutcome": { + "properties": { + "nodeId": { + "example": 7, + "type": "integer" + }, + "reason": { + "example": "timeout", + "type": "string" + }, + "status": { + "example": "pending", + "type": "string" + } + }, + "required": [ + "nodeId", + "status" + ], + "type": "object" + }, + "ClientNodeApplyResponse": { + "properties": { + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + } + }, + "type": "object" + }, "ClientNodeUsage": { "description": "ClientNodeUsage is one node's counters for a client since its last reset.", "properties": { @@ -10552,7 +10804,7 @@ ], "summary": "Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.", "operationId": "post_panel_api_clients_add", - "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.", + "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "requestBody": { "required": true, "content": { @@ -10609,12 +10861,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client added" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10720,7 +10994,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update_email", - "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10764,12 +11038,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10784,7 +11080,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10828,12 +11124,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10848,7 +11166,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del_email", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10883,12 +11201,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10903,7 +11243,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10938,12 +11278,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10958,7 +11320,7 @@ ], "summary": "Attach an existing client to one or more additional inbounds. Body is JSON.", "operationId": "post_panel_api_clients_email_attach", - "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.", + "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11012,11 +11374,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11031,7 +11416,7 @@ ], "summary": "Detach a client from one or more inbounds without deleting the client.", "operationId": "post_panel_api_clients_email_detach", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11084,11 +11469,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11862,6 +12270,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.", "requestBody": { "required": true, "content": { @@ -11953,6 +12362,14 @@ "obj": { "adjusted": 2, "externalLinks": null, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [] } } @@ -11969,6 +12386,7 @@ ], "summary": "Enable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to add each user. Note that enabling a client whose quota is exhausted or whose expiry has passed only flips the flag — the traffic loop will disable it again on the next tick. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkEnable", + "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.", "requestBody": { "required": true, "content": { @@ -11999,17 +12417,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12027,6 +12455,7 @@ ], "summary": "Disable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkDisable", + "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.", "requestBody": { "required": true, "content": { @@ -12057,17 +12486,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12085,6 +12524,7 @@ ], "summary": "Delete many clients in one call. The server processes the list sequentially so each delete sees the committed state of the previous one — avoids the race the per-email fan-out had on the panel side. Pass keepTraffic=true to retain the xray_client_traffic rows after deletion.", "operationId": "post_panel_api_clients_bulkDel", + "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.", "requestBody": { "required": true, "content": { @@ -12116,17 +12556,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDeleteResult" + } } }, "example": { "success": true, "obj": { - "deleted": 2, + "deleted": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12144,6 +12594,7 @@ ], "summary": "Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed sequentially; per-email skip reasons are returned for items that fail (e.g., duplicate email). Triggers a single Xray restart at the end if any inbound was running.", "operationId": "post_panel_api_clients_bulkCreate", + "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.", "requestBody": { "required": true, "content": { @@ -12195,17 +12646,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkCreateResult" + } } }, "example": { "success": true, "obj": { - "created": 2, + "created": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "alice@example.com", - "reason": "email already in use" + "email": "", + "reason": "" } ] } @@ -12328,6 +12789,7 @@ ], "summary": "Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkAttach", + "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.", "requestBody": { "required": true, "content": { @@ -12385,20 +12847,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkAttachResult" + } } }, "example": { "success": true, "obj": { "attached": [ - "alice", - "bob" + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } ], "skipped": [ - "bob" - ], - "errors": [] + "" + ] } } } @@ -12466,6 +12939,7 @@ ], "summary": "Mirror of bulkAttach: detach many existing clients from many inbounds in one call. For each email, intersects the client's current inbounds with the requested set and detaches from those only; (email, inbound) pairs where the client is not currently attached are silently no-ops. Emails not attached to any of the requested inbounds are reported under skipped. Client records are kept even if they become orphaned — use bulkDel for full removal. Returns per-email detached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkDetach", + "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.", "requestBody": { "required": true, "content": { @@ -12520,18 +12994,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDetachResult" + } } }, "example": { "success": true, "obj": { "detached": [ - "alice", - "bob" + "" ], - "skipped": [], - "errors": [] + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] } } } diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 4877ccf2d..fee39fb9a 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -2114,6 +2114,16 @@ ], "nullable": true }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, "skipped": { "example": [], "items": { @@ -2127,6 +2137,170 @@ ], "type": "object" }, + "BulkAttachResult": { + "description": "BulkAttachResult reports the outcome of a bulk attach across target inbounds.", + "properties": { + "attached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, + "BulkCreateReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkCreateResult": { + "description": "BulkCreateResult mirrors BulkAdjustResult for the create flow.", + "properties": { + "created": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkCreateReport" + }, + "type": "array" + } + }, + "required": [ + "created" + ], + "type": "object" + }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, + "BulkDetachResult": { + "description": "BulkDetachResult reports the outcome of a bulk detach across target inbounds.", + "properties": { + "detached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -2149,6 +2323,48 @@ ], "type": "object" }, + "BulkSetEnableReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkSetEnableResult": { + "properties": { + "changed": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkSetEnableReport" + }, + "type": "array" + } + }, + "required": [ + "changed" + ], + "type": "object" + }, "Client": { "description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.", "properties": { @@ -2419,6 +2635,42 @@ ], "type": "object" }, + "ClientNodeApplyOutcome": { + "properties": { + "nodeId": { + "example": 7, + "type": "integer" + }, + "reason": { + "example": "timeout", + "type": "string" + }, + "status": { + "example": "pending", + "type": "string" + } + }, + "required": [ + "nodeId", + "status" + ], + "type": "object" + }, + "ClientNodeApplyResponse": { + "properties": { + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + } + }, + "type": "object" + }, "ClientNodeUsage": { "description": "ClientNodeUsage is one node's counters for a client since its last reset.", "properties": { @@ -10552,7 +10804,7 @@ ], "summary": "Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.", "operationId": "post_panel_api_clients_add", - "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.", + "description": "Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "requestBody": { "required": true, "content": { @@ -10609,12 +10861,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client added" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10720,7 +10994,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update_email", - "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10764,12 +11038,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10784,7 +11080,7 @@ ], "summary": "Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.", "operationId": "post_panel_api_clients_update", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `\"reverse\": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10828,12 +11124,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client updated" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10848,7 +11166,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del_email", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10883,12 +11201,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10903,7 +11243,7 @@ ], "summary": "Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.", "operationId": "post_panel_api_clients_del", - "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.", + "description": "Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -10938,12 +11278,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { "success": true, - "msg": "Client deleted" + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -10958,7 +11320,7 @@ ], "summary": "Attach an existing client to one or more additional inbounds. Body is JSON.", "operationId": "post_panel_api_clients_email_attach", - "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.", + "description": "A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11012,11 +11374,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11031,7 +11416,7 @@ ], "summary": "Detach a client from one or more inbounds without deleting the client.", "operationId": "post_panel_api_clients_email_detach", - "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.", + "description": "The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.", "parameters": [ { "name": "email", @@ -11084,11 +11469,34 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "oneOf": [ + { + "$ref": "#/components/schemas/ClientNodeApplyResponse" + }, + { + "type": "object", + "nullable": true, + "enum": [ + null + ] + } + ] + } } }, "example": { - "success": true + "success": true, + "obj": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + } } } } @@ -11862,6 +12270,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.", "requestBody": { "required": true, "content": { @@ -11953,6 +12362,14 @@ "obj": { "adjusted": 2, "externalLinks": null, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [] } } @@ -11969,6 +12386,7 @@ ], "summary": "Enable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to add each user. Note that enabling a client whose quota is exhausted or whose expiry has passed only flips the flag — the traffic loop will disable it again on the next tick. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkEnable", + "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.", "requestBody": { "required": true, "content": { @@ -11999,17 +12417,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12027,6 +12455,7 @@ ], "summary": "Disable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons.", "operationId": "post_panel_api_clients_bulkDisable", + "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.", "requestBody": { "required": true, "content": { @@ -12057,17 +12486,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkSetEnableResult" + } } }, "example": { "success": true, "obj": { - "changed": 2, + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12085,6 +12524,7 @@ ], "summary": "Delete many clients in one call. The server processes the list sequentially so each delete sees the committed state of the previous one — avoids the race the per-email fan-out had on the panel side. Pass keepTraffic=true to retain the xray_client_traffic rows after deletion.", "operationId": "post_panel_api_clients_bulkDel", + "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.", "requestBody": { "required": true, "content": { @@ -12116,17 +12556,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDeleteResult" + } } }, "example": { "success": true, "obj": { - "deleted": 2, + "deleted": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "carol", - "reason": "client not found" + "email": "", + "reason": "" } ] } @@ -12144,6 +12594,7 @@ ], "summary": "Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed sequentially; per-email skip reasons are returned for items that fail (e.g., duplicate email). Triggers a single Xray restart at the end if any inbound was running.", "operationId": "post_panel_api_clients_bulkCreate", + "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.", "requestBody": { "required": true, "content": { @@ -12195,17 +12646,27 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkCreateResult" + } } }, "example": { "success": true, "obj": { - "created": 2, + "created": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [ { - "email": "alice@example.com", - "reason": "email already in use" + "email": "", + "reason": "" } ] } @@ -12328,6 +12789,7 @@ ], "summary": "Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkAttach", + "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.", "requestBody": { "required": true, "content": { @@ -12385,20 +12847,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkAttachResult" + } } }, "example": { "success": true, "obj": { "attached": [ - "alice", - "bob" + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } ], "skipped": [ - "bob" - ], - "errors": [] + "" + ] } } } @@ -12466,6 +12939,7 @@ ], "summary": "Mirror of bulkAttach: detach many existing clients from many inbounds in one call. For each email, intersects the client's current inbounds with the requested set and detaches from those only; (email, inbound) pairs where the client is not currently attached are silently no-ops. Emails not attached to any of the requested inbounds are reported under skipped. Client records are kept even if they become orphaned — use bulkDel for full removal. Returns per-email detached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.", "operationId": "post_panel_api_clients_bulkDetach", + "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.", "requestBody": { "required": true, "content": { @@ -12520,18 +12994,31 @@ "msg": { "type": "string" }, - "obj": {} + "obj": { + "$ref": "#/components/schemas/BulkDetachResult" + } } }, "example": { "success": true, "obj": { "detached": [ - "alice", - "bob" + "" ], - "skipped": [], - "errors": [] + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] } } } diff --git a/frontend/scripts/build-openapi.mjs b/frontend/scripts/build-openapi.mjs index e2b4e5d2e..69e0688d5 100644 --- a/frontend/scripts/build-openapi.mjs +++ b/frontend/scripts/build-openapi.mjs @@ -266,7 +266,9 @@ function buildOperation(ep, tag) { ...(ep.responseSchemaArrayNullable ? { nullable: true } : {}), items: ref, } - : ref; + : ep.responseSchemaNullable + ? { oneOf: [ref, { type: 'object', nullable: true, enum: [null] }] } + : ref; if (successExample === undefined) { successExample = { success: true, obj: ep.responseSchemaArray ? [obj] : obj }; } diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 081067ac9..310051ae7 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -509,13 +509,122 @@ export const EXAMPLES: Record = { "BulkAdjustResult": { "adjusted": 2, "externalLinks": null, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], "skipped": [] }, + "BulkAttachResult": { + "attached": [ + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] + }, + "BulkCreateReport": { + "email": "", + "reason": "" + }, + "BulkCreateResult": { + "created": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + { + "email": "", + "reason": "" + } + ] + }, + "BulkDeleteReport": { + "email": "", + "reason": "" + }, + "BulkDeleteResult": { + "deleted": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + { + "email": "", + "reason": "" + } + ] + }, + "BulkDetachResult": { + "detached": [ + "" + ], + "errors": [ + "" + ], + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + "" + ] + }, "BulkExternalLinksResult": { "added": 4, "errors": 0, "skipped": 0 }, + "BulkSetEnableReport": { + "email": "", + "reason": "" + }, + "BulkSetEnableResult": { + "changed": 0, + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ], + "skipped": [ + { + "email": "", + "reason": "" + } + ] + }, "Client": { "adTag": "0123456789abcdef0123456789abcdef", "allowedIPs": [ @@ -585,6 +694,21 @@ export const EXAMPLES: Record = { "flowOverride": "", "inboundId": 0 }, + "ClientNodeApplyOutcome": { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + }, + "ClientNodeApplyResponse": { + "nodePending": true, + "nodeResults": [ + { + "nodeId": 7, + "reason": "timeout", + "status": "pending" + } + ] + }, "ClientNodeUsage": { "down": 2097152, "nodeId": 7, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index e5b7085f6..542b3178d 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -2088,6 +2088,16 @@ export const SCHEMAS: Record = { ], "nullable": true }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, "skipped": { "example": [], "items": { @@ -2101,6 +2111,170 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "BulkAttachResult": { + "description": "BulkAttachResult reports the outcome of a bulk attach across target inbounds.", + "properties": { + "attached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "attached", + "errors", + "skipped" + ], + "type": "object" + }, + "BulkCreateReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkCreateResult": { + "description": "BulkCreateResult mirrors BulkAdjustResult for the create flow.", + "properties": { + "created": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkCreateReport" + }, + "type": "array" + } + }, + "required": [ + "created" + ], + "type": "object" + }, + "BulkDeleteReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkDeleteResult": { + "description": "BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email\nskip reasons when an email could not be processed.", + "properties": { + "deleted": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkDeleteReport" + }, + "type": "array" + } + }, + "required": [ + "deleted" + ], + "type": "object" + }, + "BulkDetachResult": { + "description": "BulkDetachResult reports the outcome of a bulk detach across target inbounds.", + "properties": { + "detached": { + "items": { + "type": "string" + }, + "type": "array" + }, + "errors": { + "items": { + "type": "string" + }, + "type": "array" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "BulkExternalLinksResult": { "properties": { "added": { @@ -2123,6 +2297,48 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "BulkSetEnableReport": { + "properties": { + "email": { + "type": "string" + }, + "reason": { + "type": "string" + } + }, + "required": [ + "email", + "reason" + ], + "type": "object" + }, + "BulkSetEnableResult": { + "properties": { + "changed": { + "type": "integer" + }, + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + }, + "skipped": { + "items": { + "$ref": "#/components/schemas/BulkSetEnableReport" + }, + "type": "array" + } + }, + "required": [ + "changed" + ], + "type": "object" + }, "Client": { "description": "Client represents a client configuration for Xray inbounds with traffic limits and settings.", "properties": { @@ -2393,6 +2609,42 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "ClientNodeApplyOutcome": { + "properties": { + "nodeId": { + "example": 7, + "type": "integer" + }, + "reason": { + "example": "timeout", + "type": "string" + }, + "status": { + "example": "pending", + "type": "string" + } + }, + "required": [ + "nodeId", + "status" + ], + "type": "object" + }, + "ClientNodeApplyResponse": { + "properties": { + "nodePending": { + "example": true, + "type": "boolean" + }, + "nodeResults": { + "items": { + "$ref": "#/components/schemas/ClientNodeApplyOutcome" + }, + "type": "array" + } + }, + "type": "object" + }, "ClientNodeUsage": { "description": "ClientNodeUsage is one node's counters for a client since its last reset.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 5bf30b7ce..62b462e76 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -499,15 +499,69 @@ export interface BulkAdjustReport { export interface BulkAdjustResult { adjusted: number; externalLinks?: BulkExternalLinksResult | null; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; skipped?: BulkAdjustReport[]; } +export interface BulkAttachResult { + attached: string[]; + errors: string[]; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped: string[]; +} + +export interface BulkCreateReport { + email: string; + reason: string; +} + +export interface BulkCreateResult { + created: number; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped?: BulkCreateReport[]; +} + +export interface BulkDeleteReport { + email: string; + reason: string; +} + +export interface BulkDeleteResult { + deleted: number; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped?: BulkDeleteReport[]; +} + +export interface BulkDetachResult { + detached: string[]; + errors: string[]; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped: string[]; +} + export interface BulkExternalLinksResult { added: number; errors: number; skipped: number; } +export interface BulkSetEnableReport { + email: string; + reason: string; +} + +export interface BulkSetEnableResult { + changed: number; + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; + skipped?: BulkSetEnableReport[]; +} + export interface Client { adTag?: string; allowedIPs?: string[]; @@ -563,6 +617,17 @@ export interface ClientInbound { inboundId: number; } +export interface ClientNodeApplyOutcome { + nodeId: number; + reason?: string; + status: string; +} + +export interface ClientNodeApplyResponse { + nodePending?: boolean; + nodeResults?: ClientNodeApplyOutcome[]; +} + export interface ClientNodeUsage { down: number; nodeId: number; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 91489537e..f0a263118 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -522,10 +522,58 @@ export type BulkAdjustReport = z.infer; export const BulkAdjustResultSchema = z.object({ adjusted: z.number().int(), externalLinks: z.lazy(() => BulkExternalLinksResultSchema).nullable().optional(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), skipped: z.array(z.lazy(() => BulkAdjustReportSchema)).optional(), }); export type BulkAdjustResult = z.infer; +export const BulkAttachResultSchema = z.object({ + attached: z.array(z.string()), + errors: z.array(z.string()), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.string()), +}); +export type BulkAttachResult = z.infer; + +export const BulkCreateReportSchema = z.object({ + email: z.string(), + reason: z.string(), +}); +export type BulkCreateReport = z.infer; + +export const BulkCreateResultSchema = z.object({ + created: z.number().int(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.lazy(() => BulkCreateReportSchema)).optional(), +}); +export type BulkCreateResult = z.infer; + +export const BulkDeleteReportSchema = z.object({ + email: z.string(), + reason: z.string(), +}); +export type BulkDeleteReport = z.infer; + +export const BulkDeleteResultSchema = z.object({ + deleted: z.number().int(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.lazy(() => BulkDeleteReportSchema)).optional(), +}); +export type BulkDeleteResult = z.infer; + +export const BulkDetachResultSchema = z.object({ + detached: z.array(z.string()), + errors: z.array(z.string()), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.string()), +}); +export type BulkDetachResult = z.infer; + export const BulkExternalLinksResultSchema = z.object({ added: z.number().int(), errors: z.number().int(), @@ -533,6 +581,20 @@ export const BulkExternalLinksResultSchema = z.object({ }); export type BulkExternalLinksResult = z.infer; +export const BulkSetEnableReportSchema = z.object({ + email: z.string(), + reason: z.string(), +}); +export type BulkSetEnableReport = z.infer; + +export const BulkSetEnableResultSchema = z.object({ + changed: z.number().int(), + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), + skipped: z.array(z.lazy(() => BulkSetEnableReportSchema)).optional(), +}); +export type BulkSetEnableResult = z.infer; + export const ClientSchema = z.object({ adTag: z.string().optional(), allowedIPs: z.array(z.string()).optional(), @@ -591,6 +653,19 @@ export const ClientInboundSchema = z.object({ }); export type ClientInbound = z.infer; +export const ClientNodeApplyOutcomeSchema = z.object({ + nodeId: z.number().int(), + reason: z.string().optional(), + status: z.string(), +}); +export type ClientNodeApplyOutcome = z.infer; + +export const ClientNodeApplyResponseSchema = z.object({ + nodePending: z.boolean().optional(), + nodeResults: z.array(z.lazy(() => ClientNodeApplyOutcomeSchema)).optional(), +}); +export type ClientNodeApplyResponse = z.infer; + export const ClientNodeUsageSchema = z.object({ down: z.number().int(), nodeId: z.number().int(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index 8eb435b29..8e41e0bf9 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -45,6 +45,7 @@ export interface Endpoint { requestSchema?: Record; bodyRequiredOneOf?: string[]; responseSchema?: string; + responseSchemaNullable?: boolean; responseSchemaArray?: boolean; responseSchemaArrayNullable?: boolean; responseObjectSchema?: Record; @@ -65,6 +66,17 @@ export interface Section { endpoints: Endpoint[]; } +const clientNodeApplyResponse = { + responseSchema: 'ClientNodeApplyResponse', + responseSchemaNullable: true, +} satisfies Partial; + +const clientNodeApplyDescription = + '\n\nFor node-backed inbounds, `obj.nodeResults` reports each affected node. `applied` means the direct peer acknowledged the change with no reported downstream work, `pending` means a locally saved change still needs reconciliation, and `failed` means a local inbound write failed. For several inbounds on one node, the least complete result is reported. `obj.nodePending` is true when any local change still needs reconciliation. The outer `success` continues to report local save success. `obj` is null when no node result is available.'; + +const bulkClientNodeApplyDescription = + '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.'; + // /inbounds/update replaces the whole row, so it takes the same payload as /add. const inboundBody = '{\n "enable": true,\n "remark": "VLESS-443",\n "listen": "",\n "port": 443,\n "protocol": "vless",\n "expiryTime": 0,\n "total": 0,\n "settings": {\n "clients": [{ "id": "...", "email": "user1" }],\n "decryption": "none"\n },\n "streamSettings": {\n "network": "tcp",\n "security": "reality",\n "realitySettings": { "show": false, "dest": "..." }\n },\n "sniffing": {\n "enabled": true,\n "destOverride": ["http", "tls"]\n }\n}'; @@ -1309,7 +1321,8 @@ export const sections: readonly Section[] = [ summary: 'Create a new client and attach it to one or more inbounds in a single call. Body is JSON. Per-protocol secrets are generated server-side when omitted, so callers can send only the universal fields.', description: - 'Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.', + 'Client email must not be exactly `.` or `..`. Existing reserved-name clients can be read, renamed to a valid name, or deleted using the query-parameter /get, /update and /del aliases. Fields the server fills in when they are omitted — a valid value sent by the caller is never overwritten. Re-adding an email that already exists, with its stored `subId`, reuses the stored `id`, `password`, `auth` and `secret` instead of minting new ones, so the identity stays in sync across its inbounds.\n\n- **VLESS / VMess** — `id`, a fresh UUID\n- **Trojan** — `password`\n- **Shadowsocks** — `password`. On a `2022-blake3-*` inbound a supplied password that does not base64-decode to the key length of the cipher (16 or 32 bytes) is replaced by a generated key and the call still succeeds, so read the client back if you did not let the server pick. Legacy ciphers keep any non-empty password\n- **Hysteria** — `auth`\n- **mtproto** — `secret`, a FakeTLS secret derived from the fronting domain of the inbound, or from `www.cloudflare.com` when it has none\n- **WireGuard** — `privateKey` and `publicKey` when both are blank, or `publicKey` alone when only a `privateKey` was sent, plus `allowedIPs`: one free `/32` taken from the /24 the existing peers of that inbound already sit in, or from `10.0.0.0/24` when it has none\n\nAccepted on the same body but never generated: `preSharedKey` and `keepAlive` (WireGuard), `adTag` (mtproto).\n\nWireGuard is the only one of these that can fail. Allocation widens the search to the containing /16 before giving up with `inbound : wireguard: no free address available in `, and an `allowedIPs` supplied by the caller is validated instead of allocated: `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of that same inbound holds, or `... used by a client on ` when the holder sits on another WireGuard or AmneziaWG inbound. Ranges are compared, not strings, so `10.0.0.9/24` collides with `10.0.0.5/32`; a `/0` entry collides with every address of its family another client holds, and only a `0.0.0.0/0` or `::/0` default route that is already stored (legacy peers) keeps nobody out. Allocation likewise skips every address inside a prefix another client holds. The same validation runs on POST /panel/api/clients/{email}/attach, where a client that already carries an address brings it along.\n\nAn `inboundIds` entry that names no existing inbound rejects the whole call before anything is written. Past that, the inbounds are applied concurrently and independently: one that fails no longer stops the others, so a `success:false` response can still have created the client on the rest. Every error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. `limitHwid` is applied only when every inbound succeeded, so re-run the call after fixing the failure.' + + clientNodeApplyDescription, params: [ { name: 'client', @@ -1325,7 +1338,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "client": {\n "email": "alice@example.com",\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "tgId": 0,\n "limitIp": 0,\n "limitHwid": 0,\n "enable": true\n },\n "inboundIds": [3, 5]\n}', - response: '{\n "success": true,\n "msg": "Client added"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1379,7 +1392,8 @@ export const sections: readonly Section[] = [ summary: 'Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.', description: - 'An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.', + 'An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.' + + clientNodeApplyDescription, params: [ { name: 'email', @@ -1389,7 +1403,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "email": "alice@example.com",\n "totalGB": 107374182400,\n "expiryTime": 1767225600000,\n "limitHwid": 2,\n "tgId": 123456789,\n "enable": true\n}', - response: '{\n "success": true,\n "msg": "Client updated"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1397,7 +1411,8 @@ export const sections: readonly Section[] = [ summary: 'Update an existing client by email. Changes propagate to every attached inbound. Body is the JSON client payload: omitted fields keep their current values, and an explicit zero, empty or null value clears a field, except as noted below.', description: - 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.', + 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. An omitted `flow` leaves every attached inbound on its own flow. Send `"reverse": null` to remove the reverse tag. Credentials (`id`, `password`, `auth`, `secret`, `subId`) and WireGuard/AmneziaWG `allowedIPs` are never cleared: an empty value keeps the stored one. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have applied the edit to the remaining inbounds. The client record is written after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the inbound edits in place.' + + clientNodeApplyDescription, params: [ { name: 'email', @@ -1407,7 +1422,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "email": "alice@example.com",\n "totalGB": 107374182400,\n "expiryTime": 1767225600000,\n "limitHwid": 2,\n "tgId": 123456789,\n "enable": true\n}', - response: '{\n "success": true,\n "msg": "Client updated"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1415,7 +1430,8 @@ export const sections: readonly Section[] = [ summary: 'Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.', description: - 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.', + 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'path', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1426,7 +1442,7 @@ export const sections: readonly Section[] = [ optional: true, }, ], - response: '{\n "success": true,\n "msg": "Client deleted"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1434,7 +1450,8 @@ export const sections: readonly Section[] = [ summary: 'Delete a client by email. Removes it from every attached inbound and drops its traffic record unless keepTraffic=1 is passed.', description: - 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.', + 'Query-parameter alias for the path endpoint. Use email=. or email=.. to manage legacy reserved names without URL dot-segment normalization. The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have removed the client from the remaining inbounds; the client record is kept in that case, so re-running the call retries exactly the leftovers. The record and traffic rows are dropped after the inbounds, so a failure there is reported without an `inbound :` prefix and leaves the client already removed from every inbound.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'query', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1445,14 +1462,15 @@ export const sections: readonly Section[] = [ optional: true, }, ], - response: '{\n "success": true,\n "msg": "Client deleted"\n}', + ...clientNodeApplyResponse, }, { method: 'POST', path: '/panel/api/clients/:email/attach', summary: 'Attach an existing client to one or more additional inbounds. Body is JSON.', description: - 'A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.', + 'A WireGuard client brings its stored `allowedIPs` into the new inbound instead of being given a fresh address, so the call fails with `inbound : wireguard: allowedIPs entry overlaps
used by another client` when its range overlaps an address or prefix a different client of the target inbound holds. Free the address on that inbound first — see POST /panel/api/clients/add for the full rule. Inbounds are applied independently, so the remaining ones are still attached and a `success:false` response can be partial.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'path', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1463,14 +1481,15 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "inboundIds": [7, 9]\n}', - response: '{\n "success": true\n}', + ...clientNodeApplyResponse, }, { method: 'POST', path: '/panel/api/clients/:email/detach', summary: 'Detach a client from one or more inbounds without deleting the client.', description: - 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.', + 'The inbounds are applied concurrently and independently: one that fails no longer stops the others. Every inbound error names the inbound it came from (`inbound 7: `), and several failures are reported together, one per line. So a `success:false` response can still have detached the remaining inbounds. Detach writes nothing beyond the inbounds, so every error carries the prefix.' + + clientNodeApplyDescription, params: [ { name: 'email', in: 'path', type: 'string', desc: 'Client email (unique identifier).' }, { @@ -1481,7 +1500,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "inboundIds": [5]\n}', - response: '{\n "success": true\n}', + ...clientNodeApplyResponse, }, { method: 'POST', @@ -1631,6 +1650,7 @@ export const sections: readonly Section[] = [ { method: 'POST', path: '/panel/api/clients/bulkAdjust', + description: bulkClientNodeApplyDescription, 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.', requestSchema: { @@ -1678,38 +1698,38 @@ export const sections: readonly Section[] = [ { method: 'POST', path: '/panel/api/clients/bulkEnable', + description: bulkClientNodeApplyDescription, summary: 'Enable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to add each user. Note that enabling a client whose quota is exhausted or whose expiry has passed only flips the flag — the traffic loop will disable it again on the next tick. Returns the changed count and per-email skip reasons.', body: '{\n "emails": ["alice", "bob"]\n}', - response: - '{\n "success": true,\n "obj": {\n "changed": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}', + responseSchema: 'BulkSetEnableResult', }, { method: 'POST', path: '/panel/api/clients/bulkDisable', + description: bulkClientNodeApplyDescription, summary: 'Disable many clients in one call. Emails are grouped by inbound and applied with a single read-modify-write per inbound; the running Xray (local or remote node) is updated to remove each user. Returns the changed count and per-email skip reasons.', body: '{\n "emails": ["alice", "bob"]\n}', - response: - '{\n "success": true,\n "obj": {\n "changed": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}', + responseSchema: 'BulkSetEnableResult', }, { method: 'POST', path: '/panel/api/clients/bulkDel', + description: bulkClientNodeApplyDescription, summary: 'Delete many clients in one call. The server processes the list sequentially so each delete sees the committed state of the previous one — avoids the race the per-email fan-out had on the panel side. Pass keepTraffic=true to retain the xray_client_traffic rows after deletion.', body: '{\n "emails": ["alice", "bob"],\n "keepTraffic": false\n}', - response: - '{\n "success": true,\n "obj": {\n "deleted": 2,\n "skipped": [\n { "email": "carol", "reason": "client not found" }\n ]\n }\n}', + responseSchema: 'BulkDeleteResult', }, { method: 'POST', path: '/panel/api/clients/bulkCreate', + description: bulkClientNodeApplyDescription, summary: 'Create many clients in one call. Body is a JSON array of {client, inboundIds} payloads — the same shape /add accepts. Items are processed sequentially; per-email skip reasons are returned for items that fail (e.g., duplicate email). Triggers a single Xray restart at the end if any inbound was running.', body: '[\n {\n "client": {\n "email": "alice@example.com",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "limitHwid": 2,\n "enable": true\n },\n "inboundIds": [7]\n },\n {\n "client": {\n "email": "bob@example.com",\n "totalGB": 53687091200,\n "expiryTime": 0,\n "limitHwid": 0,\n "enable": true\n },\n "inboundIds": [7, 9]\n }\n]', - response: - '{\n "success": true,\n "obj": {\n "created": 2,\n "skipped": [\n { "email": "alice@example.com", "reason": "email already in use" }\n ]\n }\n}', + responseSchema: 'BulkCreateResult', }, { method: 'POST', @@ -1730,6 +1750,7 @@ export const sections: readonly Section[] = [ { method: 'POST', path: '/panel/api/clients/bulkAttach', + description: bulkClientNodeApplyDescription, summary: 'Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.', params: [ @@ -1755,8 +1776,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "emails": ["alice", "bob"],\n "inboundIds": [7, 9]\n}', - response: - '{\n "success": true,\n "obj": {\n "attached": ["alice", "bob"],\n "skipped": ["bob"],\n "errors": []\n }\n}', + responseSchema: 'BulkAttachResult', }, { method: 'GET', @@ -1776,6 +1796,7 @@ export const sections: readonly Section[] = [ { method: 'POST', path: '/panel/api/clients/bulkDetach', + description: bulkClientNodeApplyDescription, summary: "Mirror of bulkAttach: detach many existing clients from many inbounds in one call. For each email, intersects the client's current inbounds with the requested set and detaches from those only; (email, inbound) pairs where the client is not currently attached are silently no-ops. Emails not attached to any of the requested inbounds are reported under skipped. Client records are kept even if they become orphaned — use bulkDel for full removal. Returns per-email detached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.", params: [ @@ -1793,8 +1814,7 @@ export const sections: readonly Section[] = [ }, ], body: '{\n "emails": ["alice", "bob"],\n "inboundIds": [7, 9]\n}', - response: - '{\n "success": true,\n "obj": {\n "detached": ["alice", "bob"],\n "skipped": [],\n "errors": []\n }\n}', + responseSchema: 'BulkDetachResult', }, { method: 'POST', diff --git a/frontend/src/test/clients-summary.test.tsx b/frontend/src/test/clients-summary.test.tsx index 22362e74e..a6407ace1 100644 --- a/frontend/src/test/clients-summary.test.tsx +++ b/frontend/src/test/clients-summary.test.tsx @@ -167,18 +167,28 @@ describe('client summary always reflects the server, never a client_stats recomp }); expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 100, down: 200 }); + // The next staggered publication contains both the fresh and retained node samples. + act(() => { + result.current.applyTrafficEvent({ + clientTrafficSource: 'node', + clientTrafficIntervalMs: 5_000, + clientTraffics: [{ email: 'shared@example.test', up: 750, down: 1_250 }], + }); + }); + expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 150, down: 250 }); + // A local Xray poll with no movement must not wipe the node sample. act(() => { result.current.applyTrafficEvent({ clientTraffics: [] }); }); - expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 100, down: 200 }); + expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 150, down: 250 }); act(() => { result.current.applyTrafficEvent({ clientTraffics: [{ email: 'shared@example.test', up: 50, down: 50 }], }); }); - expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 110, down: 210 }); + expect(result.current.clientSpeed['shared@example.test']).toEqual({ up: 160, down: 260 }); act(() => { result.current.applyTrafficEvent({ diff --git a/frontend/src/utils/index.ts b/frontend/src/utils/index.ts index 89a670765..622514ccc 100644 --- a/frontend/src/utils/index.ts +++ b/frontend/src/utils/index.ts @@ -45,7 +45,7 @@ export class HttpUtil { typeof msg.obj === 'object' && (msg.obj as { nodePending?: unknown }).nodePending === true ) { - getMessage().warning(i18next.t('pages.inbounds.toasts.savedNodeOfflineWillSync')); + getMessage().warning(i18next.t('pages.inbounds.toasts.savedNodeApplyPending')); } return; } diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go index 9380e28df..1287fa777 100644 --- a/internal/web/controller/client.go +++ b/internal/web/controller/client.go @@ -268,7 +268,8 @@ func (a *ClientController) create(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - needRestart, err := a.clientService.Create(&a.inboundService, &payload) + clientSvc := a.clientService.TrackNodeApplies() + needRestart, err := clientSvc.Create(&a.inboundService, &payload) // Flagged before the error check: a partly-applied create leaves clients // committed on the inbounds that succeeded, and those still need the restart. if needRestart { @@ -280,10 +281,10 @@ func (a *ClientController) create(c *gin.Context) { notifyClientsChanged() } if err != nil { - jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err) return } - jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(payload.InboundIds)), nil) + jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), clientSvc.NodeApplyResponse(), nil) } func (a *ClientController) update(c *gin.Context) { @@ -297,7 +298,8 @@ func (a *ClientController) update(c *gin.Context) { return } inboundFilter := parseInboundIdsQuery(c.Query("inboundIds")) - needRestart, err := a.clientService.UpdateByEmailJSON(&a.inboundService, email, body, inboundFilter...) + clientSvc := a.clientService.TrackNodeApplies() + needRestart, err := clientSvc.UpdateByEmailJSON(&a.inboundService, email, body, inboundFilter...) // Flagged before the error check: a partly-applied edit leaves the change // committed on the inbounds that succeeded, and those still need the restart. if needRestart { @@ -309,10 +311,10 @@ func (a *ClientController) update(c *gin.Context) { notifyClientsChanged() } if err != nil { - jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err) return } - jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), pendingNodeObj(a.clientService.HasPendingNode(&a.inboundService, email)), nil) + jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientUpdateSuccess"), clientSvc.NodeApplyResponse(), nil) } func (a *ClientController) delete(c *gin.Context) { @@ -321,7 +323,8 @@ func (a *ClientController) delete(c *gin.Context) { return } keepTraffic := c.Query("keepTraffic") == "1" - needRestart, err := a.clientService.DeleteByEmail(&a.inboundService, email, keepTraffic) + clientSvc := a.clientService.TrackNodeApplies() + needRestart, err := clientSvc.DeleteByEmail(&a.inboundService, email, keepTraffic) // Flagged before the error check: a partly-applied delete already removed // the client from the inbounds that succeeded, and those need the restart. if needRestart { @@ -333,10 +336,10 @@ func (a *ClientController) delete(c *gin.Context) { notifyClientsChanged() } if err != nil { - jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err) return } - jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), nil) + jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), clientSvc.NodeApplyResponse(), nil) } type attachDetachBody struct { @@ -354,7 +357,8 @@ func (a *ClientController) attach(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - needRestart, err := a.clientService.AttachByEmail(&a.inboundService, email, body.InboundIds) + clientSvc := a.clientService.TrackNodeApplies() + needRestart, err := clientSvc.AttachByEmail(&a.inboundService, email, body.InboundIds) if needRestart { a.xrayService.SetToNeedRestart() } @@ -364,10 +368,10 @@ func (a *ClientController) attach(c *gin.Context) { notifyClientsChanged() } if err != nil { - jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err) return } - jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(body.InboundIds)), nil) + jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientAddSuccess"), clientSvc.NodeApplyResponse(), nil) } func (a *ClientController) setExternalLinks(c *gin.Context) { @@ -414,6 +418,7 @@ func (a *ClientController) bulkAdjust(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + clientSvc := a.clientService.TrackNodeApplies() var result service.BulkAdjustResult var needRestart bool var err error @@ -424,12 +429,15 @@ func (a *ClientController) bulkAdjust(c *gin.Context) { } result, err = a.clientService.BulkAppendExternalLinks(req.Emails, req.ExternalLinks) } else { - result, needRestart, err = a.clientService.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag) + result, needRestart, err = clientSvc.BulkAdjust(&a.inboundService, req.Emails, req.AddDays, req.AddBytes, req.Flow, req.LimitHwid, req.AdTag) } if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -462,11 +470,15 @@ func (a *ClientController) bulkAttach(c *gin.Context) { a.beginBulkAttach(c, req.InboundIds, *req.Selection) return } - result, needRestart, err := a.clientService.BulkAttach(&a.inboundService, req.Emails, req.InboundIds) + clientSvc := a.clientService.TrackNodeApplies() + result, needRestart, err := clientSvc.BulkAttach(&a.inboundService, req.Emails, req.InboundIds) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -485,11 +497,15 @@ func (a *ClientController) bulkDetach(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - result, needRestart, err := a.clientService.BulkDetach(&a.inboundService, req.Emails, req.InboundIds) + clientSvc := a.clientService.TrackNodeApplies() + result, needRestart, err := clientSvc.BulkDetach(&a.inboundService, req.Emails, req.InboundIds) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -503,11 +519,15 @@ func (a *ClientController) bulkDelete(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - result, needRestart, err := a.clientService.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic) + clientSvc := a.clientService.TrackNodeApplies() + result, needRestart, err := clientSvc.BulkDelete(&a.inboundService, req.Emails, req.KeepTraffic) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -533,11 +553,15 @@ func (a *ClientController) bulkSetEnable(c *gin.Context, enable bool) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - result, needRestart, err := a.clientService.BulkSetEnable(&a.inboundService, req.Emails, enable) + clientSvc := a.clientService.TrackNodeApplies() + result, needRestart, err := clientSvc.BulkSetEnable(&a.inboundService, req.Emails, enable) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -551,11 +575,15 @@ func (a *ClientController) bulkCreate(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - result, needRestart, err := a.clientService.BulkCreate(&a.inboundService, payloads) + clientSvc := a.clientService.TrackNodeApplies() + result, needRestart, err := clientSvc.BulkCreate(&a.inboundService, payloads) if err != nil { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if report := clientSvc.NodeApplyResponse(); report != nil { + result.ClientNodeApplyResponse = *report + } jsonObj(c, result, nil) if needRestart { a.xrayService.SetToNeedRestart() @@ -811,7 +839,8 @@ func (a *ClientController) detach(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } - needRestart, err := a.clientService.DetachByEmailMany(&a.inboundService, email, body.InboundIds) + clientSvc := a.clientService.TrackNodeApplies() + needRestart, err := clientSvc.DetachByEmailMany(&a.inboundService, email, body.InboundIds) // Flagged before the error check: a partly-applied detach already removed // the client from the inbounds that succeeded, and those need the restart. if needRestart { @@ -823,10 +852,10 @@ func (a *ClientController) detach(c *gin.Context) { notifyClientsChanged() } if err != nil { - jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + jsonMsgObj(c, I18nWeb(c, "somethingWentWrong"), clientSvc.NodeApplyResponse(), err) return } - jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), pendingNodeObj(a.inboundService.AnyNodePending(body.InboundIds)), nil) + jsonMsgObj(c, I18nWeb(c, "pages.inbounds.toasts.inboundClientDeleteSuccess"), clientSvc.NodeApplyResponse(), nil) } type bulkResetRequest struct { diff --git a/internal/web/controller/client_node_apply_test.go b/internal/web/controller/client_node_apply_test.go new file mode 100644 index 000000000..ad305a1e2 --- /dev/null +++ b/internal/web/controller/client_node_apply_test.go @@ -0,0 +1,199 @@ +package controller + +import ( + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "strconv" + "strings" + "sync/atomic" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +func TestClientUpdateReportsTimedOutOnlineNodeAndKeepsLocalSave(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db")) + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + + const email = "partial-node@example.test" + db := database.GetDB() + var nodes []model.Node + var inbounds []model.Inbound + const ( + timeout = iota + downstream + recovered + ) + var slowMode atomic.Int32 + slowStarted := make(chan struct{}, 1) + healthyApplied := make(chan struct{}, 1) + for index, slow := range []bool{false, true} { + tag := fmt.Sprintf("in-%d", 15110+index) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + if strings.HasSuffix(r.URL.Path, "/inbounds/list") { + fmt.Fprintf(w, "{\"success\":true,\"obj\":[{\"id\":1,\"tag\":%q}]}", tag) + } else if strings.Contains(r.URL.Path, "/clients/update/") { + if slow { + switch slowMode.Load() { + case timeout: + _, _ = io.Copy(io.Discard, r.Body) + slowStarted <- struct{}{} + <-r.Context().Done() + return + case downstream: + fmt.Fprint(w, "{\"success\":true,\"obj\":{\"nodePending\":true}}") + return + } + } else { + select { + case healthyApplied <- struct{}{}: + default: + } + } + fmt.Fprint(w, "{\"success\":true}") + } else { + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + parsed, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(parsed.Port()) + if err != nil { + t.Fatal(err) + } + node := model.Node{ + Name: fmt.Sprintf("slow=%t", slow), Address: parsed.Hostname(), Port: port, + Scheme: "http", BasePath: "/", ApiToken: "fixture", TlsVerifyMode: "verify", + AllowPrivateAddress: true, Enable: true, Status: "online", + } + if err := db.Create(&node).Error; err != nil { + t.Fatal(err) + } + inbound := model.Inbound{ + UserId: 1, Enable: true, Tag: tag, Port: 15110 + index, + Protocol: model.VLESS, Settings: "{\"clients\":[],\"decryption\":\"none\"}", StreamSettings: "{\"network\":\"tcp\",\"security\":\"none\"}", + } + if err := db.Create(&inbound).Error; err != nil { + t.Fatal(err) + } + nodes = append(nodes, node) + inbounds = append(inbounds, inbound) + } + clientSvc, inboundSvc := &service.ClientService{}, &service.InboundService{} + if _, err := clientSvc.Create(inboundSvc, &service.ClientCreatePayload{ + Client: model.Client{Email: email, ID: "11111111-2222-4333-8444-555555555555", Enable: true}, + InboundIds: []int{inbounds[0].Id, inbounds[1].Id}, + }); err != nil { + t.Fatal(err) + } + for i, inbound := range inbounds { + if err := db.Model(&model.Inbound{}).Where("id = ?", inbound.Id).Update("node_id", nodes[i].Id).Error; err != nil { + t.Fatal(err) + } + } + + gin.SetMode(gin.TestMode) + router := gin.New() + NewClientController(router.Group("/panel/api/clients")) + type applyEnvelope struct { + Success bool + Obj service.ClientNodeApplyResponse + } + request := func(comment string) *httptest.ResponseRecorder { + body := fmt.Sprintf("{\"comment\":%q}", comment) + req := httptest.NewRequest(http.MethodPost, "/panel/api/clients/update/"+email, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + response := httptest.NewRecorder() + router.ServeHTTP(response, req) + return response + } + decode := func(response *httptest.ResponseRecorder) applyEnvelope { + t.Helper() + var msg applyEnvelope + if err := json.Unmarshal(response.Body.Bytes(), &msg); err != nil { + t.Fatal(err) + } + if !msg.Success || len(msg.Obj.NodeResults) != 2 { + t.Fatalf("expected local success and both node results, got %s", response.Body.String()) + } + return msg + } + started := time.Now() + done := make(chan *httptest.ResponseRecorder, 1) + finished := make(chan struct{}) + go func() { + defer close(finished) + done <- request("saved locally") + }() + t.Cleanup(func() { <-finished }) + wait := func(ch <-chan struct{}) { + t.Helper() + select { + case <-ch: + case <-time.After(3 * time.Second): + t.Fatal("expected RPC did not start before the slow node's deadline") + } + } + wait(slowStarted) + wait(healthyApplied) + writerStarted := time.Now() + if _, _, err := inboundSvc.AddTraffic(nil, nil); err != nil { + t.Fatal(err) + } + t.Logf("fixture writer barrier while RPC in flight: %s", time.Since(writerStarted)) + select { + case <-done: + t.Fatal("unrelated writer work was held behind the slow RPC") + default: + } + msg := decode(<-done) + t.Logf("fixture timed-out request: %s", time.Since(started)) + if got := msg.Obj.NodeResults[0]; got.NodeID != nodes[0].Id || got.Status != "applied" { + t.Fatalf("healthy node outcome: %+v", got) + } + if got := msg.Obj.NodeResults[1]; !msg.Obj.NodePending || got.NodeID != nodes[1].Id || got.Status != "pending" || got.Reason != "timeout" { + t.Fatalf("slow node outcome: %+v", got) + } + if stored, err := clientSvc.GetRecordByEmail(nil, email); err != nil || stored.Comment != "saved locally" { + t.Fatalf("local edit not persisted: record=%+v error=%v", stored, err) + } + if err := db.First(&nodes[1], nodes[1].Id).Error; err != nil { + t.Fatal(err) + } + if !nodes[1].ConfigDirty || nodes[1].Status != "online" { + t.Fatalf("timed-out online node lost its durable reconcile flag: %+v", nodes[1]) + } + + slowMode.Store(downstream) + msg = decode(request("downstream pending")) + if got := msg.Obj.NodeResults[1]; !msg.Obj.NodePending || got.Status != "pending" || got.Reason != "downstream_pending" { + t.Fatalf("forwarded pending result was lost: %+v", msg.Obj) + } + + slowMode.Store(recovered) + started = time.Now() + msg = decode(request("both acknowledged")) + t.Logf("fixture healthy request: %s", time.Since(started)) + if got := msg.Obj.NodeResults[1]; msg.Obj.NodePending || got.Status != "applied" || got.Reason != "" { + t.Fatalf("recovered node outcome: %+v", msg.Obj) + } +} diff --git a/internal/web/controller/util.go b/internal/web/controller/util.go index 527b3845c..c054dabc4 100644 --- a/internal/web/controller/util.go +++ b/internal/web/controller/util.go @@ -102,16 +102,6 @@ func jsonMsgObj(c *gin.Context, msg string, obj any, err error) { c.JSON(http.StatusOK, m) } -// pendingNodeObj returns a response object flagging that the save committed -// locally but a backing node was offline/disabled, so the change will be -// mirrored to the node once it reconnects. Returns nil when nothing is pending. -func pendingNodeObj(pending bool) any { - if pending { - return gin.H{"nodePending": true} - } - return nil -} - // pureJsonMsg sends a pure JSON message response with custom status code. func pureJsonMsg(c *gin.Context, statusCode int, success bool, msg string) { c.JSON(statusCode, entity.Msg{ diff --git a/internal/web/job/node_client_speed_test.go b/internal/web/job/node_client_speed_test.go index 5b082c6f9..5aa2cfc1d 100644 --- a/internal/web/job/node_client_speed_test.go +++ b/internal/web/job/node_client_speed_test.go @@ -2,6 +2,7 @@ package job import ( "testing" + "time" "github.com/mhsanaei/3x-ui/v3/internal/database/model" "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" @@ -76,13 +77,55 @@ func TestRecordNodeClientSpeed_PerNodeBaselinesAndPrune(t *testing.T) { {ClientStats: []xray.ClientTraffic{{Email: "a@x", Up: up, Down: down}}}, }} } - j.recordNodeClientSpeed(1, mk(0, 0)) - j.recordNodeClientSpeed(2, mk(1_000_000, 1_000_000)) - if len(j.tickClientSpeed) != 0 || len(j.prevClientTotals) != 2 { - t.Fatalf("baselines: tick=%v prev=%v", j.tickClientSpeed, j.prevClientTotals) + j.recordNodeClientSpeed(t.Context(), 1, mk(0, 0), time.Now()) + j.recordNodeClientSpeed(t.Context(), 2, mk(1_000_000, 1_000_000), time.Now()) + if len(j.clientSamples[1].speed) != 0 || len(j.clientSamples[2].speed) != 0 || len(j.prevClientTotals) != 2 { + t.Fatalf("baselines: tick=%v prev=%v", j.clientSamples, j.prevClientTotals) } j.pruneClientSpeedNodes([]*model.Node{{Id: 1}}) if _, ok := j.prevClientTotals[2]; ok || len(j.prevClientTotals) != 1 { t.Fatalf("deleted node not pruned: %v", j.prevClientTotals) } } + +func TestNodeClientSpeedRetainsStaggeredSamples(t *testing.T) { + j := NewNodeTrafficSyncJob() + now := time.Now() + snapshot := func(up int64) *runtime.TrafficSnapshot { + return &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{ + {ClientStats: []xray.ClientTraffic{{Email: "shared@example.test", Up: up}}}, + }} + } + j.recordNodeClientSpeed(t.Context(), 1, snapshot(0), now) + j.recordNodeClientSpeed(t.Context(), 2, snapshot(0), now.Add(time.Second)) + j.recordNodeClientSpeed(t.Context(), 1, snapshot(500), now.Add(5*time.Second)) + j.recordNodeClientSpeed(t.Context(), 2, snapshot(300), now.Add(6*time.Second)) + + for _, elapsed := range []time.Duration{7 * time.Second, 12 * time.Second} { + _, speed := j.clientSpeedSnapshot(now.Add(elapsed)) + if len(speed) != 1 || speed[0].Email != "shared@example.test" || speed[0].Up != 800 { + t.Fatalf("publication at %s lost one node's latest contribution: %+v", elapsed, speed) + } + } + j.recordNodeClientSpeed(t.Context(), 2, snapshot(300), now.Add(13*time.Second)) + _, speed := j.clientSpeedSnapshot(now.Add(14 * time.Second)) + if len(speed) != 1 || speed[0].Up != 500 { + t.Fatalf("an idle poll must replace that node's nonzero sample: %+v", speed) + } + _, speed = j.clientSpeedSnapshot(now.Add(24 * time.Second)) + if speed == nil || len(speed) != 0 { + t.Fatalf("expired samples must publish an explicit empty array: %+v", speed) + } + + j.recordNodeClientSpeed(t.Context(), 1, snapshot(2500), now.Add(25*time.Second)) + _, speed = j.clientSpeedSnapshot(now.Add(25 * time.Second)) + if len(speed) != 1 || speed[0].Up != 500 { + t.Fatalf("display expiry lost the cumulative baseline: %+v", speed) + } + + j.pruneClientSpeedNodes(nil) + _, speed = j.clientSpeedSnapshot(now.Add(25 * time.Second)) + if speed == nil || len(speed) != 0 { + t.Fatalf("removing the last node must clear its contribution: %+v", speed) + } +} diff --git a/internal/web/job/node_reset_replay_test.go b/internal/web/job/node_reset_replay_test.go index 961b67969..f356239ae 100644 --- a/internal/web/job/node_reset_replay_test.go +++ b/internal/web/job/node_reset_replay_test.go @@ -62,7 +62,10 @@ func TestNodeTrafficSyncReplaysOwedResetBeforeSnapshot(t *testing.T) { t.Fatalf("seed pending reset: %v", err) } - NewNodeTrafficSyncJob().Run() + job := NewNodeTrafficSyncJob() + job.Run() + job.workers.Wait() + job.Close() mu.Lock() got := slices.Clone(calls) diff --git a/internal/web/job/node_sync_operational_query_test.go b/internal/web/job/node_sync_operational_query_test.go index 615558dbc..a33944514 100644 --- a/internal/web/job/node_sync_operational_query_test.go +++ b/internal/web/job/node_sync_operational_query_test.go @@ -3,6 +3,7 @@ package job import ( "path/filepath" "strings" + "sync" "testing" "github.com/op/go-logging" @@ -45,10 +46,13 @@ func TestBackgroundNodeJobs_SkipNodeDashboardStatQueries(t *testing.T) { t.Fatalf("create client_traffic: %v", err) } + var mu sync.Mutex var queries []string recordSQL := func(tx *gorm.DB) { if sql := tx.Statement.SQL.String(); sql != "" { + mu.Lock() queries = append(queries, sql) + mu.Unlock() } } const cbName = "test:job-node-enum-sql" @@ -67,7 +71,10 @@ func TestBackgroundNodeJobs_SkipNodeDashboardStatQueries(t *testing.T) { _ = db.Callback().Raw().Remove(cbName) }) - NewNodeTrafficSyncJob().Run() + job := NewNodeTrafficSyncJob() + job.Run() + job.workers.Wait() + job.Close() NewNodeHeartbeatJob().Run() for _, q := range queries { diff --git a/internal/web/job/node_traffic_isolation_test.go b/internal/web/job/node_traffic_isolation_test.go new file mode 100644 index 000000000..68bed06a1 --- /dev/null +++ b/internal/web/job/node_traffic_isolation_test.go @@ -0,0 +1,389 @@ +package job + +import ( + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "net/url" + "path/filepath" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/dbtest" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +func TestNodeTrafficSyncAllowsHealthyNextTickDuringSlowReconcile(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db")) + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + + release := make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + slowRequests := make(chan struct{}, 8) + fastRequests := make(chan struct{}, 8) + var slowReconciles atomic.Int32 + var slowID int + for _, slow := range []bool{true, false} { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") { + slowReconciles.Add(1) + slowRequests <- struct{}{} + <-release + } else if !slow && strings.HasSuffix(r.URL.Path, "/inbounds/list") { + fastRequests <- struct{}{} + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, "{\"success\":true,\"obj\":[]}") + })) + t.Cleanup(srv.Close) + parsed, err := url.Parse(srv.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(parsed.Port()) + if err != nil { + t.Fatal(err) + } + node := model.Node{ + Name: fmt.Sprintf("slow=%t", slow), Address: parsed.Hostname(), Port: port, + Scheme: "http", BasePath: "/", ApiToken: "fixture", TlsVerifyMode: "verify", + AllowPrivateAddress: true, Enable: true, Status: "online", ConfigDirty: slow, + } + if err := database.GetDB().Create(&node).Error; err != nil { + t.Fatal(err) + } + if slow { + slowID = node.Id + } + } + j := NewNodeTrafficSyncJob() + first := make(chan struct{}) + go func() { defer close(first); j.Run() }() + t.Cleanup(func() { unblock(); <-first; j.Close() }) + wait := func(ch <-chan struct{}, which string) { + t.Helper() + select { + case <-ch: + case <-time.After(2 * time.Second): + t.Fatalf("%s did not start", which) + } + } + wait(slowRequests, "blocked reconcile") + wait(fastRequests, "first healthy snapshot") + + deadline := time.After(2 * time.Second) + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() +waiting: + for { + select { + case <-ticker.C: + j.Run() + case <-fastRequests: + if got := slowReconciles.Load(); got != 1 { + t.Fatalf("slow reconcile started %d times while blocked, want 1", got) + } + break waiting + case <-deadline: + t.Fatal("the next healthy snapshot was blocked behind a different node's reconciliation") + } + } + unblock() + wait(slowRequests, "recovered node snapshot") + if _, _, dirty, _, err := (&service.NodeService{}).NodeSyncState(slowID); err != nil || dirty { + t.Fatalf("reconcile did not clear the recovered node's dirty flag: dirty=%t err=%v", dirty, err) + } +} + +func TestNodeTrafficSyncDispatchesWhileTrafficWriterIsBusy(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db")) + db := database.GetDB() + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + + fetched := make(chan struct{}, 1) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch r.URL.Path { + case "/panel/api/inbounds/list": + select { + case fetched <- struct{}{}: + default: + } + case "/panel/api/clients/onlinesByGuid", "/panel/api/clients/lastOnline", + "/panel/api/clients/activeInbounds", "/panel/api/clients/clientIpsByGuid": + fmt.Fprint(w, `{"success":true,"obj":{}}`) + return + } + fmt.Fprint(w, `{"success":true,"obj":[]}`) + })) + t.Cleanup(server.Close) + address, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(address.Port()) + if err != nil { + t.Fatal(err) + } + healthy := model.Node{ + Name: "healthy", Scheme: "http", Address: address.Hostname(), Port: port, + BasePath: "/", ApiToken: "fixture", AllowPrivateAddress: true, Enable: true, Status: "online", + } + writerNode := model.Node{Name: "writer peer", Address: "192.0.2.1", Port: 2053, Enable: true, Status: "offline"} + for _, node := range []*model.Node{&healthy, &writerNode} { + if err := db.Create(node).Error; err != nil { + t.Fatal(err) + } + } + + parked, release := make(chan struct{}), make(chan struct{}) + var parkOnce atomic.Bool + const callback = "test:park-node-traffic-writer" + if err := db.Callback().Query().Before("gorm:query").Register(callback, func(tx *gorm.DB) { + if tx.Statement.Table == "nodes" && parkOnce.CompareAndSwap(false, true) { + close(parked) + <-release + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) }) + + j := NewNodeTrafficSyncJob() + writerDone := make(chan struct{}) + var writerErr error + go func() { + defer close(writerDone) + _, writerErr = (&service.InboundService{}).SetRemoteTraffic(writerNode.Id, &runtime.TrafficSnapshot{}, true, false) + }() + var runDone chan struct{} + var releaseOnce sync.Once + unblock := func() { releaseOnce.Do(func() { close(release) }) } + t.Cleanup(func() { + unblock() + <-writerDone + if runDone != nil { + <-runDone + } + j.Close() + }) + + wait := func(c <-chan struct{}, message string) { + t.Helper() + select { + case <-c: + case <-time.After(3 * time.Second): + t.Fatal(message) + } + } + wait(parked, "the node merge did not occupy the traffic writer") + runDone = make(chan struct{}) + go func() { + defer close(runDone) + j.Run() + }() + wait(fetched, "cache pruning blocked the healthy node's snapshot request behind the writer") + wait(runDone, "the dispatcher did not return while the writer was blocked") + unblock() + wait(writerDone, "the node merge did not finish after the writer was released") + if writerErr != nil { + t.Fatal(writerErr) + } +} + +func TestNodeTrafficSyncAdmitsNextNodeAtCapacityAndCancelsOnClose(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db")) + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + + const count = nodeTrafficSyncConcurrency + 1 + var calls [count]atomic.Int32 + started := make(chan int, count*2) + release := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + prefix := strings.SplitN(strings.TrimPrefix(r.URL.Path, "/"), "/", 2)[0] + index, err := strconv.Atoi(prefix) + if err != nil || index < 0 || index >= count { + http.NotFound(w, r) + return + } + if strings.HasSuffix(r.URL.Path, "/inbounds/list") { + calls[index].Add(1) + started <- index + if index == 0 { + select { + case <-release: + case <-r.Context().Done(): + return + } + } else { + <-r.Context().Done() + return + } + } + w.Header().Set("Content-Type", "application/json") + fmt.Fprint(w, `{"success":true,"obj":[]}`) + })) + t.Cleanup(server.Close) + addr, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(addr.Port()) + if err != nil { + t.Fatal(err) + } + for i := range count { + node := model.Node{ + Name: fmt.Sprintf("poll-%d", i), Address: addr.Hostname(), Port: port, Scheme: "http", + BasePath: fmt.Sprintf("/%d/", i), ApiToken: "fixture", TlsVerifyMode: "verify", + Enable: true, Status: "online", AllowPrivateAddress: true, + } + if err := database.GetDB().Create(&node).Error; err != nil { + t.Fatal(err) + } + } + job := NewNodeTrafficSyncJob() + t.Cleanup(func() { unblock(); job.Close() }) + job.Run() + deadline := time.After(2 * time.Second) + for range nodeTrafficSyncConcurrency { + select { + case index := <-started: + if index == count-1 { + t.Fatal("node past the concurrency cap started on the first tick") + } + case <-deadline: + t.Fatal("initial poll did not fill its slots") + } + } + unblock() + tick := time.NewTicker(10 * time.Millisecond) + defer tick.Stop() +waiting: + for { + select { + case <-tick.C: + job.Run() + case index := <-started: + if index != count-1 { + t.Fatalf("round-robin skipped the waiting node and launched %d", index) + } + break waiting + case <-deadline: + t.Fatal("waiting node did not get the freed slot") + } + } + + closed := make(chan struct{}) + go func() { job.Close(); close(closed) }() + select { + case <-closed: + case <-time.After(2 * time.Second): + t.Fatal("shutdown waited for the network deadline instead of canceling polls") + } + for i := range count { + if got := calls[i].Load(); got != 1 { + t.Fatalf("node %d received %d polls during admission and shutdown", i, got) + } + } +} + +func TestNodeTrafficSyncRejectsSnapshotWhenNodeBecomesIneligible(t *testing.T) { + for _, action := range []string{"disable", "delete"} { + t.Run(action, func(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "master.db")) + service.StartTrafficWriter() + t.Cleanup(service.StopTrafficWriter) + runtime.SetManager(runtime.NewManager(runtime.LocalDeps{APIPort: func() int { return 0 }, SetNeedRestart: func() {}})) + t.Cleanup(func() { runtime.SetManager(nil) }) + + started, release := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var payload any = []any{} + switch r.URL.Path { + case "/panel/api/inbounds/list": + payload = []*model.Inbound{{ + Id: 1, Tag: "in-29443", Port: 29443, Protocol: model.VLESS, + Settings: `{"clients":[]}`, Enable: true, + }} + case "/panel/api/hosts/list": + close(started) + select { + case <-release: + case <-r.Context().Done(): + return + } + } + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": payload}) + })) + t.Cleanup(server.Close) + addr, err := url.Parse(server.URL) + if err != nil { + t.Fatal(err) + } + port, err := strconv.Atoi(addr.Port()) + if err != nil { + t.Fatal(err) + } + node := model.Node{ + Name: "snapshot-in-flight", Scheme: "http", Address: addr.Hostname(), Port: port, + BasePath: "/", ApiToken: "fixture", TlsVerifyMode: "verify", + Enable: true, Status: "online", AllowPrivateAddress: true, + } + if err := database.GetDB().Create(&node).Error; err != nil { + t.Fatal(err) + } + job := NewNodeTrafficSyncJob() + t.Cleanup(func() { unblock(); job.Close() }) + job.Run() + select { + case <-started: + case <-time.After(2 * time.Second): + t.Fatal("snapshot never passed the initial eligibility check") + } + + nodes := &service.NodeService{} + if action == "disable" { + err = nodes.SetEnable(node.Id, false) + } else { + err = nodes.Delete(node.Id) + } + if err != nil { + t.Fatal(err) + } + unblock() + job.workers.Wait() + + var adopted int64 + if err := database.GetDB().Model(&model.Inbound{}).Where("node_id = ?", node.Id).Count(&adopted).Error; err != nil { + t.Fatal(err) + } + if adopted != 0 || len(job.clientSamples) != 0 { + t.Fatalf("obsolete poll adopted %d inbounds or recorded a speed sample", adopted) + } + }) + } +} diff --git a/internal/web/job/node_traffic_sync_ip_push_test.go b/internal/web/job/node_traffic_sync_ip_push_test.go index 8db156d02..f847008a3 100644 --- a/internal/web/job/node_traffic_sync_ip_push_test.go +++ b/internal/web/job/node_traffic_sync_ip_push_test.go @@ -76,7 +76,10 @@ func TestNodeTrafficSyncPushesOnlyHostedClientIps(t *testing.T) { } } - NewNodeTrafficSyncJob().Run() + job := NewNodeTrafficSyncJob() + job.Run() + job.workers.Wait() + job.Close() for _, email := range []string{"a@node", "b@node"} { if got := pushed[email]; !slices.Equal(got, []string{email}) { diff --git a/internal/web/job/node_traffic_sync_job.go b/internal/web/job/node_traffic_sync_job.go index 50be79292..5dee54ab4 100644 --- a/internal/web/job/node_traffic_sync_job.go +++ b/internal/web/job/node_traffic_sync_job.go @@ -2,6 +2,7 @@ package job import ( "context" + "maps" "strings" "sync" "time" @@ -24,6 +25,8 @@ const ( nodeClientIpSyncInterval = 10 * time.Second nodeClientIpSyncTimeout = 6 * time.Second nodeGlobalPushInterval = 30 * time.Second + // Match the UI speed expiry: two normal five-second polling windows. + nodeClientSampleTTL = 10 * time.Second // nodeInboundSpeedWindowMs is the poll window node-inbound speed deltas are // normalized to; it MUST match the dashboard's TRAFFIC_POLL_INTERVAL_S (5s), // the fixed divisor the frontend applies to turn a delta into a rate. @@ -36,31 +39,41 @@ type inboundSample struct { up, down, at int64 } +type nodePollState struct { + busy bool + cancel context.CancelFunc + lastIP, lastGlobals time.Time +} + +type nodeClientSample struct { + at time.Time + emails []string + speed []*xray.ClientTraffic +} + type NodeTrafficSyncJob struct { nodeService service.NodeService inboundService service.InboundService settingService service.SettingService xrayService service.XrayService - running sync.Mutex - structural atomicBool - ipSyncMu sync.Mutex - lastIpSync int64 - globalPushMu sync.Mutex - lastGlobalPush int64 - // noGuidIpEndpoint tracks nodes (by id) whose client-IP attribution endpoint - // returned 404, so an old-build node is noted once instead of every cycle. + + ctx context.Context + cancel context.CancelFunc + dispatch sync.Mutex + closed bool + workers sync.WaitGroup + polls map[int]*nodePollState + inFlight, nextNode int + maintaining, publishing bool + hadNodes bool + + structural atomicBool noGuidIpEndpoint sync.Map - // prevInboundTotals holds the previous poll's cumulative up/down (and the time - // the counter last changed) per node inbound tag, so the next poll can derive - // a per-inbound speed delta — node inbounds have no local Xray poll. Touched - // only from Run (serialized). + // Only the publisher touches the inbound speed baseline. prevInboundTotals map[string]inboundSample - // Per-client counterpart keyed node id -> email, so a client on several nodes - // gets a baseline per node; guarded by clientSpeedMu as syncOne runs in parallel. - clientSpeedMu sync.Mutex - prevClientTotals map[int]map[string]inboundSample - // This tick's normalized per-client deltas from every synced node. - tickClientSpeed []*xray.ClientTraffic + clientSpeedMu sync.Mutex + prevClientTotals map[int]map[string]inboundSample + clientSamples map[int]nodeClientSample } type atomicBool struct { @@ -83,76 +96,145 @@ func (a *atomicBool) takeAndReset() bool { } func NewNodeTrafficSyncJob() *NodeTrafficSyncJob { - return &NodeTrafficSyncJob{} + ctx, cancel := context.WithCancel(context.Background()) + return &NodeTrafficSyncJob{ctx: ctx, cancel: cancel, polls: make(map[int]*nodePollState)} +} + +// Close drains polls and publication before the panel stops its traffic writer. +func (j *NodeTrafficSyncJob) Close() { + j.dispatch.Lock() + j.closed = true + j.cancel() + j.dispatch.Unlock() + j.workers.Wait() } func (j *NodeTrafficSyncJob) Run() { - if !j.running.TryLock() { + if !j.dispatch.TryLock() { return } - defer j.running.Unlock() - + defer j.dispatch.Unlock() mgr := runtime.GetManager() - if mgr == nil { + if j.closed || mgr == nil { return } - nodes, err := j.nodeService.ListOperational() if err != nil { logger.Warning("node traffic sync: load nodes failed:", err) return } j.inboundService.RetainSyncedNodeOnlineClients(nodes) - if err := j.inboundService.RetainNodeSnapshotCaches(nodes); err != nil { - logger.Warning("node traffic sync: prune snapshot caches failed:", err) - } - if len(nodes) == 0 { - return - } - // Decide once per tick whether this run also syncs client IPs, and stamp the - // clock before the loop so two back-to-back 5s ticks can't both qualify. - doIpSync := false - j.ipSyncMu.Lock() - if now := time.Now().Unix(); now-j.lastIpSync >= int64(nodeClientIpSyncInterval/time.Second) { - doIpSync = true - j.lastIpSync = now + present := make(map[int]*model.Node, len(nodes)) + for _, node := range nodes { + present[node.Id] = node + } + for id, poll := range j.polls { + node := present[id] + if poll.busy && (node == nil || !node.Enable || node.Status != "online") { + poll.cancel() + } + if !poll.busy && node == nil { + delete(j.polls, id) + j.noGuidIpEndpoint.Delete(id) + } } - j.ipSyncMu.Unlock() - j.clientSpeedMu.Lock() - j.tickClientSpeed = make([]*xray.ClientTraffic, 0) j.pruneClientSpeedNodes(nodes) j.clientSpeedMu.Unlock() + // Cache pruning waits on the traffic writer, so keep it off the dispatch path. + j.startPeriodicWorker("node-traffic-maintenance", &j.maintaining, func() { + j.maintainTraffic(nodes) + }) + if len(nodes) == 0 { + if j.hadNodes && !j.publishing { + j.startPeriodicWorker("node-traffic-publish", &j.publishing, j.publishTraffic) + j.hadNodes = false + } + return + } + j.hadNodes = true fetchTimeout, err := j.settingService.GetNodeTrafficFetchTimeout() if err != nil || fetchTimeout < time.Second || fetchTimeout > 30*time.Second { fetchTimeout = nodeTrafficSyncRequestTimeout } - sem := make(chan struct{}, nodeTrafficSyncConcurrency) - var wg sync.WaitGroup - var activeMu sync.Mutex - var activeEmails []string - for _, n := range nodes { - if !n.Enable || n.Status != "online" { + now := time.Now() + for remaining := len(nodes); remaining > 0 && j.inFlight < nodeTrafficSyncConcurrency; remaining-- { + j.nextNode %= len(nodes) + node := nodes[j.nextNode] + j.nextNode++ + if !node.Enable || node.Status != "online" { continue } - wg.Add(1) - sem <- struct{}{} - n := n - common.GoRecover("node-traffic-sync:"+n.Name, func() { - defer wg.Done() - defer func() { <-sem }() - if emails := j.syncOne(mgr, n, doIpSync, fetchTimeout); len(emails) > 0 { - activeMu.Lock() - activeEmails = append(activeEmails, emails...) - activeMu.Unlock() - } + state := j.polls[node.Id] + if state == nil { + state = &nodePollState{} + j.polls[node.Id] = state + } + if state.busy { + continue + } + doIPSync := now.Sub(state.lastIP) >= nodeClientIpSyncInterval + if doIPSync { + state.lastIP = now + } + pushGlobals := now.Sub(state.lastGlobals) >= nodeGlobalPushInterval + if pushGlobals { + state.lastGlobals = now + } + pollCtx, cancel := context.WithCancel(j.ctx) + state.busy = true + state.cancel = cancel + j.inFlight++ + j.startWorker("node-traffic-sync:"+node.Name, func() { + defer func() { + cancel() + j.dispatch.Lock() + state.busy = false + state.cancel = nil + j.inFlight-- + j.dispatch.Unlock() + }() + j.syncOne(pollCtx, mgr, node, doIPSync, pushGlobals, fetchTimeout) }) } - wg.Wait() + j.startPeriodicWorker("node-traffic-publish", &j.publishing, j.publishTraffic) +} + +// Worker admission is serialized with Close. The cron wrapper only sees dispatch. +func (j *NodeTrafficSyncJob) startWorker(name string, work func()) { + j.workers.Add(1) + common.GoRecover(name, func() { + defer j.workers.Done() + work() + }) +} + +func (j *NodeTrafficSyncJob) startPeriodicWorker(name string, busy *bool, work func()) { + if *busy { + return + } + *busy = true + j.startWorker(name, func() { + defer func() { + j.dispatch.Lock() + *busy = false + j.dispatch.Unlock() + }() + work() + }) +} + +func (j *NodeTrafficSyncJob) maintainTraffic(nodes []*model.Node) { + if err := j.inboundService.RetainNodeSnapshotCaches(nodes); err != nil { + logger.Warning("node traffic sync: prune snapshot caches failed:", err) + } + if len(nodes) == 0 { + return + } _, clientsDisabled, err := j.inboundService.AddTraffic(nil, nil) if err != nil { logger.Warning("node traffic sync: depletion check failed:", err) @@ -161,9 +243,9 @@ func (j *NodeTrafficSyncJob) Run() { j.xrayService.ApplyPendingDepletionRestart() j.structural.set() } +} - j.maybePushGlobals(mgr, nodes) - +func (j *NodeTrafficSyncJob) publishTraffic() { // Prune stale local-online entries (no local active emails or inbound tags // to add here — only the local xray poll feeds those) so a stopped local // xray's clients and inbounds still age out between traffic polls. @@ -177,6 +259,8 @@ func (j *NodeTrafficSyncJob) Run() { return } + activeEmails, clientSpeed := j.clientSpeedSnapshot(time.Now()) + // Same snapshot-vs-delta split as the local traffic job: above the // threshold a full snapshot would be dropped by the hub's payload cap, so // send only the rows for clients online on the synced nodes this tick. @@ -235,9 +319,6 @@ func (j *NodeTrafficSyncJob) Run() { // Own source so the clients page adds it to local Xray/TUIC speed instead of // overwriting it; sent even when empty so idle clients clear. - j.clientSpeedMu.Lock() - clientSpeed := j.tickClientSpeed - j.clientSpeedMu.Unlock() websocket.BroadcastTraffic(map[string]any{ "clientTraffics": clientSpeed, "clientTrafficSource": "node", @@ -356,113 +437,132 @@ func diffClientTotals(prev map[string]inboundSample, cur map[string][2]int64, no return next, deltas } -func (j *NodeTrafficSyncJob) recordNodeClientSpeed(nodeID int, snap *runtime.TrafficSnapshot) { +func (j *NodeTrafficSyncJob) recordNodeClientSpeed(ctx context.Context, nodeID int, snap *runtime.TrafficSnapshot, now time.Time) { cur := nodeClientTotals(snap) - now := time.Now().UnixMilli() + j.clientSpeedMu.Lock() + previous := j.prevClientTotals[nodeID] + j.clientSpeedMu.Unlock() + next, deltas := diffClientTotals(previous, cur, now.UnixMilli()) + var emails []string + if snap != nil { + emails = append(emails, snap.OnlineEmails...) + for _, online := range snap.OnlineTree { + emails = append(emails, online...) + } + } j.clientSpeedMu.Lock() defer j.clientSpeedMu.Unlock() + if ctx.Err() != nil { + return + } if j.prevClientTotals == nil { j.prevClientTotals = make(map[int]map[string]inboundSample) } - next, deltas := diffClientTotals(j.prevClientTotals[nodeID], cur, now) j.prevClientTotals[nodeID] = next - j.tickClientSpeed = append(j.tickClientSpeed, deltas...) + if j.clientSamples == nil { + j.clientSamples = make(map[int]nodeClientSample) + } + j.clientSamples[nodeID] = nodeClientSample{at: now, emails: emails, speed: deltas} } -// Offline nodes keep their baselines so the first poll after recovery averages -// over the gap. Caller holds clientSpeedMu. -func (j *NodeTrafficSyncJob) pruneClientSpeedNodes(nodes []*model.Node) { - if len(j.prevClientTotals) == 0 { - return +func (j *NodeTrafficSyncJob) clientSpeedSnapshot(now time.Time) ([]string, []*xray.ClientTraffic) { + j.clientSpeedMu.Lock() + for id, sample := range j.clientSamples { + if now.Sub(sample.at) >= nodeClientSampleTTL { + delete(j.clientSamples, id) + } } + samples := maps.Clone(j.clientSamples) + j.clientSpeedMu.Unlock() + + var activeEmails []string + byEmail := make(map[string]*xray.ClientTraffic) + for _, sample := range samples { + activeEmails = append(activeEmails, sample.emails...) + for _, delta := range sample.speed { + total := byEmail[delta.Email] + if total == nil { + total = &xray.ClientTraffic{Email: delta.Email} + byEmail[delta.Email] = total + } + total.Up += delta.Up + total.Down += delta.Down + } + } + speed := make([]*xray.ClientTraffic, 0, len(byEmail)) + for _, row := range byEmail { + speed = append(speed, row) + } + return activeEmails, speed +} + +// Keep the accounting baseline across temporary outages and presentation expiry. +// Caller holds clientSpeedMu. +func (j *NodeTrafficSyncJob) pruneClientSpeedNodes(nodes []*model.Node) { alive := make(map[int]struct{}, len(nodes)) for _, n := range nodes { if n != nil { alive[n.Id] = struct{}{} + if !n.Enable || n.Status != "online" { + delete(j.clientSamples, n.Id) + } } } for id := range j.prevClientTotals { if _, ok := alive[id]; !ok { delete(j.prevClientTotals, id) + delete(j.clientSamples, id) } } } -// maybePushGlobals broadcasts this panel's aggregated per-client usage to its -// online nodes so each node can display the client's cross-panel total and -// enforce its quota locally (see InboundService.AcceptGlobalTraffic). Scoped -// per node to the clients that node actually hosts, and throttled — the -// aggregates only need to reach nodes on a human timescale, not every poll. -func (j *NodeTrafficSyncJob) maybePushGlobals(mgr *runtime.Manager, nodes []*model.Node) { - j.globalPushMu.Lock() - now := time.Now().Unix() - if now-j.lastGlobalPush < int64(nodeGlobalPushInterval/time.Second) { - j.globalPushMu.Unlock() - return - } - j.lastGlobalPush = now - j.globalPushMu.Unlock() - +func (j *NodeTrafficSyncJob) pushGlobals(pollCtx context.Context, node *model.Node, remote *runtime.Remote) { masterGuid, err := j.settingService.GetPanelGuid() if err != nil || masterGuid == "" { return } - - sem := make(chan struct{}, nodeTrafficSyncConcurrency) - var wg sync.WaitGroup - for _, n := range nodes { - if !n.Enable || n.Status != "online" { - continue - } - remote, err := mgr.RemoteFor(n) - if err != nil { - continue - } - traffics, err := j.inboundService.GetNodeClientTraffics(n.Id) - if err != nil { - logger.Warningf("node traffic sync: load globals for %s failed: %v", n.Name, err) - continue - } - if len(traffics) == 0 { - continue - } - wg.Add(1) - sem <- struct{}{} - n, remote, traffics := n, remote, traffics - common.GoRecover("node-global-push:"+n.Name, func() { - defer wg.Done() - defer func() { <-sem }() - ctx, cancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout) - defer cancel() - if err := remote.PushGlobalClientTraffics(ctx, masterGuid, traffics); err != nil { - // An old-build node without the endpoint answers 404 — not worth a - // warning every cycle. - if strings.Contains(err.Error(), "HTTP 404") { - logger.Debugf("node traffic sync: node %s has no global-traffic endpoint (old build)", n.Name) - } else { - logger.Warningf("node traffic sync: push globals to %s failed: %v", n.Name, err) - } - } - }) + traffics, err := j.inboundService.GetNodeClientTraffics(node.Id) + if err != nil { + logger.Warningf("node traffic sync: load globals for %s failed: %v", node.Name, err) + return + } + if len(traffics) == 0 { + return + } + ctx, cancel := context.WithTimeout(pollCtx, nodeTrafficSyncRequestTimeout) + defer cancel() + if err := remote.PushGlobalClientTraffics(ctx, masterGuid, traffics); err != nil { + if strings.Contains(err.Error(), "HTTP 404") { + logger.Debugf("node traffic sync: node %s has no global-traffic endpoint (old build)", node.Name) + } else { + logger.Warningf("node traffic sync: push globals to %s failed: %v", node.Name, err) + } } - wg.Wait() } -// syncOne pulls one node's traffic snapshot and merges it. It returns the -// emails online on that node this tick, feeding the delta broadcast above the -// snapshot threshold; nil on any failure path. -func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSync bool, fetchTimeout time.Duration) []string { +func (j *NodeTrafficSyncJob) syncOne(pollCtx context.Context, mgr *runtime.Manager, n *model.Node, doIpSync, pushGlobals bool, fetchTimeout time.Duration) { rt, err := mgr.RemoteFor(n) if err != nil { logger.Warningf("node traffic sync: remote lookup failed for %s: %v", n.Name, err) - return nil + return + } + + if pushGlobals { + defer func() { + if pollCtx.Err() == nil { + j.pushGlobals(pollCtx, n, rt) + } + }() } justPushed := false if n.ConfigDirty { - reconcileCtx, reconcileCancel := context.WithTimeout(context.Background(), nodeReconcileTimeout) + reconcileCtx, reconcileCancel := context.WithTimeout(pollCtx, nodeReconcileTimeout) reconcileErr := j.inboundService.ReconcileNode(reconcileCtx, rt, n) reconcileCancel() + if pollCtx.Err() != nil { + return + } if reconcileErr != nil { // The dirty flag stays set so reconcile retries next tick, but traffic // accounting must keep flowing: one rejected inbound used to starve the @@ -480,13 +580,16 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy } // Before the snapshot, so counters a reset just zeroed are what gets merged. - resetCtx, resetCancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout) + resetCtx, resetCancel := context.WithTimeout(pollCtx, nodeTrafficSyncRequestTimeout) if resetErr := j.inboundService.DeliverNodeResets(resetCtx, n.Id, rt); resetErr != nil { logger.Warningf("node traffic sync: reset delivery to %s failed, retrying next tick: %v", n.Name, resetErr) } resetCancel() + if pollCtx.Err() != nil { + return + } - ctx, cancel := context.WithTimeout(context.Background(), fetchTimeout) + ctx, cancel := context.WithTimeout(pollCtx, fetchTimeout) defer cancel() fetchStarted := time.Now() @@ -495,17 +598,21 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy if err != nil { logger.Warningf("node traffic sync: fetch from %s failed after %dms: %v", n.Name, prepareStarted.Sub(fetchStarted).Milliseconds(), err) j.inboundService.ClearNodeOnlineClients(n.Id) - return nil + return } snap.ManagedAliases = rt.AdoptedInboundAliases() syncCanAdopt := syncCanAdoptInbounds(n, snap.ManagedAliases) service.FilterNodeSnapshot(n, snap) - _, _, dirty, _, _ := j.nodeService.NodeSyncState(n.Id) + enabled, status, dirty, _, err := j.nodeService.NodeSyncState(n.Id) + if err != nil || !enabled || status != "online" { + j.inboundService.ClearNodeOnlineClients(n.Id) + return + } if !dirty { if pending, checkErr := j.inboundService.SnapshotHasUnadoptedInbounds(n.Id, snap); checkErr != nil { logger.Warningf("node traffic sync: unadopted-inbound check for %s failed: %v", n.Name, checkErr) } else if pending { - hostCtx, hostCancel := context.WithTimeout(context.Background(), nodeTrafficSyncRequestTimeout) + hostCtx, hostCancel := context.WithTimeout(pollCtx, nodeTrafficSyncRequestTimeout) groups, hgErr := rt.FetchHostGroups(hostCtx) hostCancel() if hgErr != nil { @@ -516,35 +623,34 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy } } mergeStarted := time.Now() - changed, err := j.inboundService.SetRemoteTraffic(n.Id, snap, dirty, justPushed) + changed, err := j.inboundService.MergeOnlineNodeTraffic(pollCtx, n.Id, snap, dirty, justPushed) logger.Debugf("node traffic sync timing: node_id=%d compact=%t fetch_ms=%d prepare_ms=%d merge_ms=%d", n.Id, snap.StructuralRevision != "", prepareStarted.Sub(fetchStarted).Milliseconds(), mergeStarted.Sub(prepareStarted).Milliseconds(), time.Since(mergeStarted).Milliseconds()) if err != nil { logger.Warningf("node traffic sync: merge for %s failed: %v", n.Name, err) - return nil + return } if changed { j.structural.set() } - j.recordNodeClientSpeed(n.Id, snap) + enabled, status, _, _, err = j.nodeService.NodeSyncState(n.Id) + if err != nil || !enabled || status != "online" || pollCtx.Err() != nil { + j.inboundService.ClearNodeOnlineClients(n.Id) + return + } + j.recordNodeClientSpeed(pollCtx, n.Id, snap, time.Now()) if !dirty && n.InboundsAdoptedAt == 0 && syncCanAdopt { if markErr := j.nodeService.MarkNodeInboundsAdopted(n.Id); markErr != nil { logger.Warningf("node traffic sync: mark inbounds adopted for %s failed: %v", n.Name, markErr) } } - active := make([]string, 0, len(snap.OnlineEmails)) - active = append(active, snap.OnlineEmails...) - for _, emails := range snap.OnlineTree { - active = append(active, emails...) - } - if !doIpSync { - return active + return } - ipCtx, ipCancel := context.WithTimeout(context.Background(), nodeClientIpSyncTimeout) + ipCtx, ipCancel := context.WithTimeout(pollCtx, nodeClientIpSyncTimeout) defer ipCancel() nodeIps, err := rt.FetchAllClientIps(ipCtx) @@ -559,7 +665,7 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy masterIps, err := j.inboundService.GetNodeInboundClientIps(n.Id) if err != nil { logger.Warningf("node traffic sync: load client ips for push to %s failed: %v", n.Name, err) - return active + return } if len(masterIps) > 0 { if err := rt.PushAllClientIps(ipCtx, masterIps); err != nil { @@ -587,7 +693,6 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy } } } - return active } // Whether this sync can perform the "first clean adoption" that diff --git a/internal/web/job/node_traffic_sync_online_prune_test.go b/internal/web/job/node_traffic_sync_online_prune_test.go index 29e706627..5d1e111dd 100644 --- a/internal/web/job/node_traffic_sync_online_prune_test.go +++ b/internal/web/job/node_traffic_sync_online_prune_test.go @@ -35,7 +35,10 @@ func TestNodeTrafficSyncDropsOnlineClientsOfUnsyncedNodes(t *testing.T) { process.SetNodeOnlineTree(disabled.Id, map[string][]string{"g-disabled": {"a@x"}}) process.SetNodeOnlineTree(disabled.Id+100, map[string][]string{"g-deleted": {"b@x"}}) - NewNodeTrafficSyncJob().Run() + job := NewNodeTrafficSyncJob() + job.Run() + job.workers.Wait() + job.Close() if got := process.GetMergedNodeTrees(); len(got) != 0 { t.Fatalf("online sets after a sync tick = %v, want none for a disabled or deleted node", got) diff --git a/internal/web/node_contract_test.go b/internal/web/node_contract_test.go index 44c4e9870..a54cb27d5 100644 --- a/internal/web/node_contract_test.go +++ b/internal/web/node_contract_test.go @@ -226,18 +226,20 @@ func TestMasterNodeContract(t *testing.T) { } }}, {"AddClient attaches one client", []string{"AddClient"}, func() error { - return master.AddClient(ctx, masterInbound("updated", false), model.Client{ + _, err := master.AddClient(ctx, masterInbound("updated", false), model.Client{ Email: "c3", ID: "0b6d5c2e-7c1a-4f4e-9d3b-000000000003", SubID: "s-c3", Enable: true, }) + return err }, func(t *testing.T) { if got := nodeEmails(t); !strings.Contains(strings.Join(got, ","), "c3") { t.Fatalf("node clients = %v, want c3 among them", got) } }}, {"UpdateUser changes the client's limits", []string{"UpdateUser"}, func() error { - return master.UpdateUser(ctx, masterInbound("updated", false), "c3", model.Client{ + _, err := master.UpdateUser(ctx, masterInbound("updated", false), "c3", model.Client{ Email: "c3", ID: "0b6d5c2e-7c1a-4f4e-9d3b-000000000003", SubID: "s-c3", Enable: true, TotalGB: 5 << 30, }) + return err }, func(t *testing.T) { var ct xray.ClientTraffic database.GetDB().Where("email = ?", "c3").First(&ct) @@ -357,14 +359,16 @@ func TestMasterNodeContract(t *testing.T) { } }, nil}, {"DeleteUser detaches the client from the inbound", []string{"DeleteUser"}, func() error { - return master.DeleteUser(ctx, masterInbound("updated", false), "c3") + _, err := master.DeleteUser(ctx, masterInbound("updated", false), "c3") + return err }, func(t *testing.T) { if got := nodeEmails(t); strings.Contains(strings.Join(got, ","), "c3") { t.Fatalf("node clients = %v, want c3 gone", got) } }}, {"DeleteClient removes the client everywhere", []string{"DeleteClient"}, func() error { - return master.DeleteClient(ctx, "c2") + _, err := master.DeleteClient(ctx, "c2") + return err }, func(t *testing.T) { if got := nodeEmails(t); strings.Contains(strings.Join(got, ","), "c2") { t.Fatalf("node clients = %v, want c2 gone", got) diff --git a/internal/web/runtime/local.go b/internal/web/runtime/local.go index 1ef764945..72d498113 100644 --- a/internal/web/runtime/local.go +++ b/internal/web/runtime/local.go @@ -363,9 +363,9 @@ func (l *Local) RemoveUser(_ context.Context, ib *model.Inbound, email string) e }) } -func (l *Local) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error { +func (l *Local) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) (ClientApplyResult, error) { if !client.Enable { - return nil + return ClientApplyResult{}, nil } user := map[string]any{ "email": client.Email, @@ -380,34 +380,34 @@ func (l *Local) AddClient(ctx context.Context, ib *model.Inbound, client model.C "keepAlive": wgKeepAlive(client.KeepAliveSeconds()), "wireguardDevices": client.WireguardDevices, } - return l.AddUser(ctx, ib, user) + return ClientApplyResult{}, l.AddUser(ctx, ib, user) } -func (l *Local) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error { +func (l *Local) DeleteUser(ctx context.Context, ib *model.Inbound, email string) (ClientApplyResult, error) { if email == "" { - return nil + return ClientApplyResult{}, nil } if err := l.RemoveUser(ctx, ib, email); err != nil { if strings.Contains(err.Error(), "not found") { - return nil + return ClientApplyResult{}, nil } - return err + return ClientApplyResult{}, err } - return nil + return ClientApplyResult{}, nil } -func (l *Local) DeleteClient(context.Context, string) error { - return nil +func (l *Local) DeleteClient(context.Context, string) (ClientApplyResult, error) { + return ClientApplyResult{}, nil } -func (l *Local) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) error { +func (l *Local) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) (ClientApplyResult, error) { if oldEmail != "" { if err := l.RemoveUser(ctx, ib, oldEmail); err != nil && !strings.Contains(err.Error(), "not found") { - return err + return ClientApplyResult{}, err } } if !payload.Enable { - return nil + return ClientApplyResult{}, nil } user := map[string]any{ "email": payload.Email, @@ -422,7 +422,7 @@ func (l *Local) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail stri "keepAlive": wgKeepAlive(payload.KeepAliveSeconds()), "wireguardDevices": payload.WireguardDevices, } - return l.AddUser(ctx, ib, user) + return ClientApplyResult{}, l.AddUser(ctx, ib, user) } func wgKeepAlive(seconds int) string { diff --git a/internal/web/runtime/local_wireguard_devices_test.go b/internal/web/runtime/local_wireguard_devices_test.go index 95258cbc3..74dfce190 100644 --- a/internal/web/runtime/local_wireguard_devices_test.go +++ b/internal/web/runtime/local_wireguard_devices_test.go @@ -92,7 +92,7 @@ func TestLocalWireguardAddsEveryEnabledDevice(t *testing.T) { } { t.Run(test.name, func(t *testing.T) { local, core := newWireguardDeviceRuntime(t) - if err := local.AddClient(context.Background(), &model.Inbound{Tag: "wg", Protocol: model.WireGuard}, wireguardDeviceClient(test.keepAlive)); err != nil { + if _, err := local.AddClient(context.Background(), &model.Inbound{Tag: "wg", Protocol: model.WireGuard}, wireguardDeviceClient(test.keepAlive)); err != nil { t.Fatal(err) } assertWireguardDevicePeers(t, core, test.want) diff --git a/internal/web/runtime/reconcile_skip_test.go b/internal/web/runtime/reconcile_skip_test.go index 1d7ba96f0..8e225320c 100644 --- a/internal/web/runtime/reconcile_skip_test.go +++ b/internal/web/runtime/reconcile_skip_test.go @@ -81,7 +81,7 @@ func TestDeleteClientInvalidatesOnlyInboundsStampedWithThatClient(t *testing.T) unaffected := &model.Inbound{Tag: "in-2", Protocol: model.VLESS, Settings: `{"clients":[{"email":"keep@example.test"}]}`} r.AdoptInboundAlias(affected, RemoteInboundOption{Tag: "adopted-1", Id: 1}) r.AdoptInboundAlias(unaffected, RemoteInboundOption{Tag: "adopted-2", Id: 2}) - if err := r.DeleteClient(t.Context(), "delete@example.test"); (err != nil) != response.failed { + if _, err := r.DeleteClient(t.Context(), "delete@example.test"); (err != nil) != response.failed { t.Fatalf("unexpected delete result: %v", err) } if pushed, err := r.ReconcileInbound(t.Context(), unaffected, true); err != nil || pushed { @@ -126,19 +126,19 @@ func newCountingNodeServer(t *testing.T, clientsResp string) (*httptest.Server, func perClientMutationCases(client model.Client) []struct { name string - run func(*Remote, *model.Inbound) error + run func(*Remote, *model.Inbound) (ClientApplyResult, error) } { return []struct { name string - run func(*Remote, *model.Inbound) error + run func(*Remote, *model.Inbound) (ClientApplyResult, error) }{ - {"add", func(r *Remote, ib *model.Inbound) error { + {"add", func(r *Remote, ib *model.Inbound) (ClientApplyResult, error) { return r.AddClient(context.Background(), ib, client) }}, - {"delete", func(r *Remote, ib *model.Inbound) error { + {"delete", func(r *Remote, ib *model.Inbound) (ClientApplyResult, error) { return r.DeleteUser(context.Background(), ib, client.Email) }}, - {"update", func(r *Remote, ib *model.Inbound) error { + {"update", func(r *Remote, ib *model.Inbound) (ClientApplyResult, error) { return r.UpdateUser(context.Background(), ib, client.Email, client) }}, } @@ -159,8 +159,8 @@ func TestPerClientMutationsAloneDoNotSeedReconcileFingerprint(t *testing.T) { ib := &model.Inbound{Tag: "in-" + tt.name, Protocol: model.VLESS, Port: 443, Settings: `{"clients":[{"id":"11111111-1111-1111-1111-111111111111","email":"a@x","subId":"s","enable":true}]}`} r.cacheSet(ib.Tag, 7) - if err := tt.run(r, ib); err != nil { - t.Fatalf("%s client mutation: %v", tt.name, err) + if result, err := tt.run(r, ib); err != nil || result.DownstreamPending { + t.Fatalf("%s client mutation: result=%+v err=%v, want legacy ack with no pending flag", tt.name, result, err) } if got := counts.clientMutations.Load(); got != 1 { t.Fatalf("%s client mutation requests=%d, want 1", tt.name, got) @@ -201,7 +201,7 @@ func TestAdvancePushedInboundEnablesReconcileSkip(t *testing.T) { r.cacheSet(ib.Tag, 7) r.recordPushedInbound(prevIb) - if err := tt.run(r, ib); err != nil { + if _, err := tt.run(r, ib); err != nil { t.Fatalf("%s client mutation: %v", tt.name, err) } r.AdvancePushedInbound(prevIb, ib) @@ -229,7 +229,7 @@ func TestAdvancePushedInboundRequiresMatchingPreviousFingerprint(t *testing.T) { r.cacheSet(ib.Tag, 7) r.recordPushedInbound(staleIb) - if err := r.UpdateUser(context.Background(), ib, "a@x", model.Client{Email: "a@x"}); err != nil { + if _, err := r.UpdateUser(context.Background(), ib, "a@x", model.Client{Email: "a@x"}); err != nil { t.Fatalf("client mutation: %v", err) } r.AdvancePushedInbound(prevIb, ib) @@ -256,7 +256,7 @@ func TestAdoptedSerializationChainKeepsReconcileSkip(t *testing.T) { r.recordPushedInbound(pushForm) r.RecordAdoptedInbound(adoptedForm) - if err := r.UpdateUser(context.Background(), edited, "a@x", model.Client{Email: "a@x"}); err != nil { + if _, err := r.UpdateUser(context.Background(), edited, "a@x", model.Client{Email: "a@x"}); err != nil { t.Fatalf("client mutation: %v", err) } r.AdvancePushedInbound(adoptedForm, edited) @@ -275,7 +275,7 @@ func TestDeleteUserNotFoundHandling(t *testing.T) { ib := &model.Inbound{Tag: "in-delete-missing", Protocol: model.VLESS, Port: 443, Settings: `{"clients":[]}`} r.cacheSet(ib.Tag, 7) - if err := r.DeleteUser(context.Background(), ib, "missing@x"); err != nil { + if _, err := r.DeleteUser(context.Background(), ib, "missing@x"); err != nil { t.Fatalf("DeleteUser missing client: %v", err) } if pushed, err := r.ReconcileInbound(context.Background(), ib, true); err != nil || !pushed { @@ -300,7 +300,7 @@ func TestDeleteUserNotFoundHandling(t *testing.T) { ib := &model.Inbound{Tag: "in-delete-404", Protocol: model.VLESS, Port: 443, Settings: `{"clients":[]}`} r.cacheSet(ib.Tag, 7) - err := r.DeleteUser(context.Background(), ib, "missing@x") + _, err := r.DeleteUser(context.Background(), ib, "missing@x") if err == nil || !strings.Contains(err.Error(), "HTTP 404") { t.Fatalf("DeleteUser against old node = %v, want HTTP 404 error", err) } diff --git a/internal/web/runtime/remote.go b/internal/web/runtime/remote.go index 8a2288868..8448cabc1 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -797,80 +797,87 @@ func (r *Remote) RemoveUser(ctx context.Context, ib *model.Inbound, _ string) er return r.UpdateInbound(ctx, ib, ib) } -func (r *Remote) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error { +func remoteClientApplyResult(env *envelope, err error) (ClientApplyResult, error) { + if err != nil || env == nil { + return ClientApplyResult{}, err + } + var result struct { + NodePending bool `json:"nodePending"` + } + pending := json.Unmarshal(env.Obj, &result) == nil && result.NodePending + return ClientApplyResult{DownstreamPending: pending}, nil +} + +func (r *Remote) AddClient(ctx context.Context, ib *model.Inbound, client model.Client) (ClientApplyResult, error) { id, err := r.resolveRemoteID(ctx, ib.Tag) if err != nil { - return fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err) + return ClientApplyResult{}, fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err) } payload := map[string]any{ "client": client, "inboundIds": []int{id}, } - if _, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload); err != nil { - return err - } - return nil + env, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload) + return remoteClientApplyResult(env, err) } -func (r *Remote) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error { +func (r *Remote) DeleteUser(ctx context.Context, ib *model.Inbound, email string) (ClientApplyResult, error) { if email == "" { - return nil + return ClientApplyResult{}, nil } id, err := r.resolveRemoteID(ctx, ib.Tag) if err != nil { // Can't confirm the delete reached the node — surface it so the caller // marks the node dirty and a reconcile converges, instead of silently // dropping the delete and letting the next snapshot resurrect the client. - return fmt.Errorf("remote DeleteUser: resolve tag %q: %w", ib.Tag, err) + return ClientApplyResult{}, fmt.Errorf("remote DeleteUser: resolve tag %q: %w", ib.Tag, err) } body := map[string]any{"inboundIds": []int{id}} - _, err = r.do(ctx, http.MethodPost, + env, err := r.do(ctx, http.MethodPost, "panel/api/clients/"+url.PathEscape(email)+"/detach", body) if err == nil { - return nil + return remoteClientApplyResult(env, nil) } var apiErr *remoteAPIError if errors.As(err, &apiErr) && strings.Contains(strings.ToLower(apiErr.msg), "not found") { - return nil + return ClientApplyResult{}, nil } - return err + return ClientApplyResult{}, err } -func (r *Remote) DeleteClient(ctx context.Context, email string) error { +func (r *Remote) DeleteClient(ctx context.Context, email string) (ClientApplyResult, error) { if email == "" { - return nil + return ClientApplyResult{}, nil } - _, err := r.do(ctx, http.MethodPost, + env, err := r.do(ctx, http.MethodPost, "panel/api/clients/del/"+url.PathEscape(email), nil) r.forgetPushedClient(email) if err == nil { - return nil + return remoteClientApplyResult(env, nil) } var apiErr *remoteAPIError if errors.As(err, &apiErr) { absent := fmt.Sprintf("client %q not found in any inbound or client record", email) message := strings.TrimSpace(apiErr.msg) if message == absent || strings.HasSuffix(message, " ("+absent+")") { - return nil + return ClientApplyResult{}, nil } } - return err + return ClientApplyResult{}, err } -func (r *Remote) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) error { +func (r *Remote) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, payload model.Client) (ClientApplyResult, error) { if oldEmail == "" { oldEmail = payload.Email } id, err := r.resolveRemoteID(ctx, ib.Tag) if err != nil { - return err + return ClientApplyResult{}, err } path := "panel/api/clients/update/" + url.PathEscape(oldEmail) + "?inboundIds=" + strconv.Itoa(id) - if _, err := r.do(ctx, http.MethodPost, path, payload); err != nil { - return err - } - return nil + env, err := r.do(ctx, http.MethodPost, path, payload) + return remoteClientApplyResult(env, err) } func (r *Remote) RestartXray(ctx context.Context) error { diff --git a/internal/web/runtime/runtime.go b/internal/web/runtime/runtime.go index d0540055c..4d871c414 100644 --- a/internal/web/runtime/runtime.go +++ b/internal/web/runtime/runtime.go @@ -6,6 +6,11 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/database/model" ) +// ClientApplyResult describes an acknowledged mutation. The direct peer retries its own downstream nodes. +type ClientApplyResult struct { + DownstreamPending bool +} + type Runtime interface { Name() string @@ -19,16 +24,16 @@ type Runtime interface { // Per-client operations that route through the node's clients API on // Remote (instead of pushing the whole inbound) so the node applies // per-user xray API calls without a DelInbound+AddInbound cycle. - UpdateUser(ctx context.Context, ib *model.Inbound, email string, payload model.Client) error - DeleteUser(ctx context.Context, ib *model.Inbound, email string) error - AddClient(ctx context.Context, ib *model.Inbound, client model.Client) error + UpdateUser(ctx context.Context, ib *model.Inbound, email string, payload model.Client) (ClientApplyResult, error) + DeleteUser(ctx context.Context, ib *model.Inbound, email string) (ClientApplyResult, error) + AddClient(ctx context.Context, ib *model.Inbound, client model.Client) (ClientApplyResult, error) // DeleteClient removes the client identified by email entirely from the // runtime's own store: on Remote it hits the node's full-delete endpoint // (record, attachments, traffic), unlike DeleteUser which only detaches // from one inbound and leaves the node's client record behind. Local has // no client store of its own, so it is a no-op there. - DeleteClient(ctx context.Context, email string) error + DeleteClient(ctx context.Context, email string) (ClientApplyResult, error) RestartXray(ctx context.Context) error diff --git a/internal/web/service/client.go b/internal/web/service/client.go index 7429f4bee..4fd2625e1 100644 --- a/internal/web/service/client.go +++ b/internal/web/service/client.go @@ -57,7 +57,9 @@ func (c ClientWithAttachments) MarshalJSON() ([]byte, error) { return out, nil } -type ClientService struct{} +type ClientService struct { + nodeApplies *clientNodeApplyReport +} // ErrClientNotInInbound is returned (wrapped) when a client cannot be located // in an inbound's settings during deletion. Deletion treats it as non-fatal so diff --git a/internal/web/service/client_bulk.go b/internal/web/service/client_bulk.go index 5bb9050eb..371a1cd88 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -21,6 +21,7 @@ import ( // BulkAttachResult reports the outcome of a bulk attach across target inbounds. type BulkAttachResult struct { + ClientNodeApplyResponse Attached []string `json:"attached"` Skipped []string `json:"skipped"` Errors []string `json:"errors"` @@ -145,7 +146,7 @@ func (s *ClientService) bulkAttachRecords(inboundSvc *InboundService, records [] attachClients = append(attachClients, clientsToAdd) } - attachResults, attachPanics := fanoutInboundResults(attachIds, addFanoutLimit(attachAnyTunnel), func(i int) inboundApplyOutcome { + attachResults, attachPanics := fanoutClientInboundResults(attachIds, addFanoutLimit(attachAnyTunnel), func(i int) inboundApplyOutcome { nr, err := s.AddInboundClient(inboundSvc, &model.Inbound{Id: attachIds[i], Settings: attachPayloads[i]}) return inboundApplyOutcome{needRestart: nr, err: err} }) @@ -174,6 +175,7 @@ func (s *ClientService) bulkAttachRecords(inboundSvc *InboundService, records [] // BulkDetachResult reports the outcome of a bulk detach across target inbounds. type BulkDetachResult struct { + ClientNodeApplyResponse Detached []string `json:"detached"` Skipped []string `json:"skipped"` Errors []string `json:"errors"` @@ -255,7 +257,7 @@ func (s *ClientService) BulkDetach(inboundSvc *InboundService, emails []string, detachIds = append(detachIds, ibId) detachRecs = append(detachRecs, recs) } - detachResults, detachPanics := fanoutInboundResults(detachIds, inboundFanoutConcurrency, func(i int) inboundApplyOutcome { + detachResults, detachPanics := fanoutClientInboundResults(detachIds, inboundFanoutConcurrency, func(i int) inboundApplyOutcome { nr, err := s.delInboundClients(inboundSvc, detachIds[i], detachRecs[i], true) return inboundApplyOutcome{needRestart: nr, err: err} }) @@ -297,6 +299,7 @@ type inboundApplyOutcome struct { // BulkAdjustResult reports changed clients and per-client skip reasons. // ExternalLinks contains row counts only for append requests. type BulkAdjustResult struct { + ClientNodeApplyResponse Adjusted int `json:"adjusted" example:"2"` Skipped []BulkAdjustReport `json:"skipped,omitempty" example:"[]"` ExternalLinks *BulkExternalLinksResult `json:"externalLinks,omitempty"` @@ -480,7 +483,7 @@ func (s *ClientService) BulkAdjust(inboundSvc *InboundService, emails []string, adTagIneligible := map[string]bool{} execFailed := map[string]bool{} adjustIds := sortedInboundIds(emailsByInbound) - adjustResults, adjustPanics := fanoutInboundResults(adjustIds, inboundFanoutConcurrency, func(i int) bulkInboundAdjustResult { + adjustResults, adjustPanics := fanoutClientInboundResults(adjustIds, inboundFanoutConcurrency, func(i int) bulkInboundAdjustResult { return s.bulkAdjustInboundClients(inboundSvc, adjustIds[i], emailsByInbound[adjustIds[i]], plan, flow, adTag) }) for i, ibRes := range adjustResults { @@ -696,6 +699,7 @@ func (s *ClientService) bulkAdjustInboundClients( var settings map[string]any if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &err) for _, e := range emails { res.perEmailSkipped[e] = err.Error() } @@ -832,6 +836,7 @@ func (s *ClientService) bulkAdjustInboundClients( return nil }) if txErr != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &txErr) for email := range foundEmails { if _, skip := res.perEmailSkipped[email]; !skip { res.perEmailSkipped[email] = txErr.Error() @@ -846,7 +851,7 @@ func (s *ClientService) bulkAdjustInboundClients( if perr != nil { logger.Warning("BulkAdjust: node runtime lookup after commit failed:", perr) } else if push { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { for email := range foundEmails { entry := plan[email] updated := *entry.record.ToClient() @@ -860,15 +865,18 @@ func (s *ClientService) bulkAdjustInboundClients( updated.AdTag = wantAdTag } updated.UpdatedAt = nowMs - err := rt.UpdateUser(ctx, oldInbound, email, updated) - if err != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err) + if !batch.acknowledge(rt.UpdateUser(ctx, oldInbound, email, updated)) { return false } } return true }) } + if perr != nil || !push { + s.recordClientNodeDeferred(oldInbound.NodeID) + } + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } } @@ -878,6 +886,7 @@ func (s *ClientService) bulkAdjustInboundClients( // BulkDeleteResult mirrors BulkAdjustResult: total deleted plus per-email // skip reasons when an email could not be processed. type BulkDeleteResult struct { + ClientNodeApplyResponse Deleted int `json:"deleted"` Skipped []BulkDeleteReport `json:"skipped,omitempty"` } @@ -951,7 +960,7 @@ func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, needRestart := false delIds := sortedInboundIds(emailsByInbound) - delResults, delPanics := fanoutInboundResults(delIds, inboundFanoutConcurrency, func(i int) bulkInboundDeleteResult { + delResults, delPanics := fanoutClientInboundResults(delIds, inboundFanoutConcurrency, func(i int) bulkInboundDeleteResult { return s.bulkDelInboundClients(inboundSvc, delIds[i], emailsByInbound[delIds[i]], recordsByEmail, keepTraffic) }) for i, ibResult := range delResults { @@ -1070,6 +1079,7 @@ func (s *ClientService) bulkDelInboundClients( var settings map[string]any if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &err) for _, e := range emails { res.perEmailSkipped[e] = err.Error() } @@ -1215,6 +1225,7 @@ func (s *ClientService) bulkDelInboundClients( return err }) if txErr != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &txErr) for email := range wantedEmails { if _, skip := res.perEmailSkipped[email]; !skip { res.perEmailSkipped[email] = txErr.Error() @@ -1245,22 +1256,28 @@ func (s *ClientService) bulkDelInboundClients( } } else { if len(pending) == 0 || len(pending) > nodeBulkPushThreshold { + s.recordClientNodeDeferred(oldInbound.NodeID) return res } rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) if perr != nil { logger.Warning("BulkDelete: node runtime lookup after commit failed:", perr) } else if push { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { + complete := true for _, row := range pending { - if err := applyNodeClientDelete(ctx, rt, row); err != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err) + result, attempted, err := applyNodeClientDelete(ctx, rt, row) + if !batch.acknowledge(result, err) { return false } + complete = complete && attempted } - return true + return complete }) } + if perr != nil || !push { + s.recordClientNodeDeferred(oldInbound.NodeID) + } } return res @@ -1268,6 +1285,7 @@ func (s *ClientService) bulkDelInboundClients( // BulkCreateResult mirrors BulkAdjustResult for the create flow. type BulkCreateResult struct { + ClientNodeApplyResponse Created int `json:"created"` Skipped []BulkCreateReport `json:"skipped,omitempty"` } @@ -1480,7 +1498,7 @@ func (s *ClientService) bulkCreate(inboundSvc *InboundService, payloads []Client } needRestart := false - createResults, createPanics := fanoutInboundResults(inboundOrder, addFanoutLimit(createAnyTunnel), func(i int) inboundApplyOutcome { + createResults, createPanics := fanoutClientInboundResults(inboundOrder, addFanoutLimit(createAnyTunnel), func(i int) inboundApplyOutcome { ibId := inboundOrder[i] payload, e := json.Marshal(map[string][]model.Client{"clients": byInbound[ibId]}) if e != nil { @@ -1566,6 +1584,7 @@ func (s *ClientService) DelDepleted(inboundSvc *InboundService) (int, bool, erro } type BulkSetEnableResult struct { + ClientNodeApplyResponse Changed int `json:"changed"` Skipped []BulkSetEnableReport `json:"skipped,omitempty"` } @@ -1626,7 +1645,7 @@ func (s *ClientService) BulkSetEnable(inboundSvc *InboundService, emails []strin needRestart := false enableIds := sortedInboundIds(emailsByInbound) - enableResults, enablePanics := fanoutInboundResults(enableIds, inboundFanoutConcurrency, func(i int) bulkSetEnableInboundResult { + enableResults, enablePanics := fanoutClientInboundResults(enableIds, inboundFanoutConcurrency, func(i int) bulkSetEnableInboundResult { return s.bulkSetEnableInboundClients(inboundSvc, enableIds[i], emailsByInbound[enableIds[i]], enable) }) for i, ibRes := range enableResults { @@ -1725,6 +1744,7 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, var settings map[string]any if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &err) for _, e := range emails { res.perEmailSkipped[e] = err.Error() } @@ -1826,6 +1846,7 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, return nil }) if txErr != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &txErr) for _, ch := range changed { res.perEmailSkipped[ch.email] = txErr.Error() } @@ -1858,19 +1879,19 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, } } } else if push { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { for _, ch := range changed { updated := ch.client updated.UpdatedAt = nowMs - err := rt.UpdateUser(ctx, oldInbound, ch.email, updated) - if err != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err) + if !batch.acknowledge(rt.UpdateUser(ctx, oldInbound, ch.email, updated)) { return false } } advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) return true }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } return res diff --git a/internal/web/service/client_create_fanout_test.go b/internal/web/service/client_create_fanout_test.go index 1d7dc57bc..4b8ada29c 100644 --- a/internal/web/service/client_create_fanout_test.go +++ b/internal/web/service/client_create_fanout_test.go @@ -110,7 +110,7 @@ func (b *barrierNodeRuntime) free() { } } -func (b *barrierNodeRuntime) AddClient(ctx context.Context, ib *model.Inbound, c model.Client) error { +func (b *barrierNodeRuntime) AddClient(ctx context.Context, ib *model.Inbound, c model.Client) (runtime.ClientApplyResult, error) { n := b.inFlight.Add(1) for { peak := b.maxPar.Load() diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 3646889e0..687f45f01 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -315,7 +315,7 @@ func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreate if mErr != nil { return false, fmt.Errorf("inbound %d: %w", ibId, mErr) } - adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload)}) + adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload), NodeID: inbound.NodeID}) } needRestart, fanoutErr := s.fanoutInboundClientAdds(inboundSvc, adds) if fanoutErr != nil { @@ -340,8 +340,9 @@ const inboundFanoutConcurrency = 4 // inboundApply is one inbound's share of a client op, ready to run. type inboundApply struct { - id int - run func() (bool, error) + id int + nodeID *int + run func() (bool, error) } // fanoutInboundApplies runs the applies with the node pushes overlapping, so a @@ -350,8 +351,9 @@ func fanoutInboundApplies(applies []inboundApply) (bool, error) { var needRestart atomic.Bool errs := make([]error, len(applies)) sem := make(chan struct{}, inboundFanoutConcurrency) + indices := nodeFairOrder(len(applies), func(i int) *int { return applies[i].nodeID }) var wg sync.WaitGroup - for i := range applies { + for _, i := range indices { wg.Add(1) sem <- struct{}{} go func() { @@ -386,18 +388,57 @@ func fanoutInboundApplies(applies []inboundApply) (bool, error) { func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound) (bool, error) { applies := make([]inboundApply, 0, len(adds)) for _, add := range adds { - applies = append(applies, inboundApply{id: add.Id, run: func() (bool, error) { + applies = append(applies, inboundApply{id: add.Id, nodeID: add.NodeID, run: func() (bool, error) { return s.AddInboundClient(inboundSvc, add) }}) } return fanoutInboundApplies(applies) } +// Give each node a turn before admitting a second inbound from any node. +func nodeFairOrder(count int, nodeAt func(int) *int) []int { + indices := make([]int, count) + order := make([]int, count) + seen := make(map[int]int) + for i := range indices { + indices[i] = i + nodeID := 0 + if id := nodeAt(i); id != nil { + nodeID = *id + } + order[i] = seen[nodeID] + seen[nodeID]++ + } + slices.SortStableFunc(indices, func(i, k int) int { return order[i] - order[k] }) + return indices +} + +func fanoutClientInboundResults[T any](inboundIDs []int, limit int, run func(int) T) ([]T, []error) { + if limit < 2 || len(inboundIDs) <= limit { + return fanoutInboundResults(inboundIDs, limit, run) + } + db := database.GetDB() + nodes := make(map[int]*int, len(inboundIDs)) + for _, batch := range chunkInts(inboundIDs, sqlInChunk) { + var rows []model.Inbound + if err := db.Select("id", "node_id").Where("id IN ?", batch).Find(&rows).Error; err != nil { + logger.Warning("Cannot order bulk client applies across nodes:", err) + return fanoutInboundResults(inboundIDs, limit, run) + } + for _, row := range rows { + nodes[row.Id] = row.NodeID + } + } + return fanoutInboundResults(inboundIDs, limit, run, nodeFairOrder(len(inboundIDs), func(i int) *int { + return nodes[inboundIDs[i]] + })...) +} + // fanoutInboundResults runs one job per inbound with the node pushes // overlapping, so a bulk op costs one RPC round-trip instead of one per node. // limit is the caller's own cap: an op that allocates tunnel addresses passes 1, // because allocation reads a cross-inbound used-set before it writes. -func fanoutInboundResults[T any](inboundIds []int, limit int, run func(i int) T) ([]T, []error) { +func fanoutInboundResults[T any](inboundIds []int, limit int, run func(i int) T, order ...int) ([]T, []error) { if limit < 1 { limit = 1 } @@ -405,7 +446,11 @@ func fanoutInboundResults[T any](inboundIds []int, limit int, run func(i int) T) errs := make([]error, len(inboundIds)) sem := make(chan struct{}, limit) var wg sync.WaitGroup - for i := range inboundIds { + for pos := range inboundIds { + i := pos + if len(order) != 0 { + i = order[pos] + } wg.Add(1) sem <- struct{}{} go func() { @@ -895,7 +940,7 @@ func (s *ClientService) update(inboundSvc *InboundService, id int, updated model return false, mErr } data := &model.Inbound{Id: ibId, Settings: string(settingsPayload)} - applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) { + applies = append(applies, inboundApply{id: ibId, nodeID: inbound.NodeID, run: func() (bool, error) { return s.UpdateInboundClient(inboundSvc, data, existing.Email) }}) } @@ -1059,7 +1104,8 @@ func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic b applies := make([]inboundApply, 0, len(inboundIds)) var delErrs []error for _, ibId := range inboundIds { - if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil { + inbound, getErr := inboundSvc.GetInbound(ibId) + if getErr != nil { if errors.Is(getErr, gorm.ErrRecordNotFound) { continue } @@ -1074,7 +1120,7 @@ func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic b if existing.Email == "" { continue } - applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) { + applies = append(applies, inboundApply{id: ibId, nodeID: inbound.NodeID, run: func() (bool, error) { nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, keepTraffic, true) // The client is already absent from this inbound (data drift or a // retried delete). Skip it — deletion stays idempotent. @@ -1271,7 +1317,7 @@ func (s *ClientService) Attach(inboundSvc *InboundService, id int, inboundIds [] if mErr != nil { return false, fmt.Errorf("inbound %d: %w", ibId, mErr) } - adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload)}) + adds = append(adds, &model.Inbound{Id: ibId, Settings: string(settingsPayload), NodeID: inbound.NodeID}) } return s.fanoutInboundClientAdds(inboundSvc, adds) } @@ -1396,14 +1442,15 @@ func (s *ClientService) Detach(inboundSvc *InboundService, id int, inboundIds [] if _, attached := have[ibId]; !attached { continue } - if _, getErr := inboundSvc.GetInbound(ibId); getErr != nil { + inbound, getErr := inboundSvc.GetInbound(ibId) + if getErr != nil { return false, getErr } // Detach by email — the client's stable identity (see Delete). if existing.Email == "" { continue } - applies = append(applies, inboundApply{id: ibId, run: func() (bool, error) { + applies = append(applies, inboundApply{id: ibId, nodeID: inbound.NodeID, run: func() (bool, error) { nr, delErr := s.DelInboundClientByEmail(inboundSvc, ibId, existing.Email, true, false) if errors.Is(delErr, ErrClientNotInInbound) { return nr, nil diff --git a/internal/web/service/client_edit_node_dirty_test.go b/internal/web/service/client_edit_node_dirty_test.go index c42a95f8f..26133182d 100644 --- a/internal/web/service/client_edit_node_dirty_test.go +++ b/internal/web/service/client_edit_node_dirty_test.go @@ -7,6 +7,7 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/database" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) // dirtyProbeRuntime reads a node's config_dirty flag at the moment an inbound @@ -18,7 +19,7 @@ type dirtyProbeRuntime struct { probed atomic.Bool } -func (d *dirtyProbeRuntime) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, c model.Client) error { +func (d *dirtyProbeRuntime) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, c model.Client) (runtime.ClientApplyResult, error) { var node model.Node if err := database.GetDB().Where("id = ?", d.watch).First(&node).Error; err == nil { d.sawSet.Store(node.ConfigDirty) diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index 2ee15e988..f805aa233 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -135,7 +135,7 @@ func advancePushedInbound(rt runtime.Runtime, prevSettings, pushedSettings strin // 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. -func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId int, recs []*model.ClientRecord, keepTraffic bool) (bool, error) { +func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId int, recs []*model.ClientRecord, keepTraffic bool) (restartNeeded bool, saveErr error) { defer InvalidateSubData() if len(recs) == 0 { return false, nil @@ -148,6 +148,7 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId logger.Error("Load Old Data Error") return false, err } + defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) var settings map[string]any if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil { @@ -285,23 +286,25 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId if oldInbound.NodeID != nil { rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) if perr != nil { - return needRestart, perr + logger.Warning("Node client detach deferred:", perr) + s.recordClientNodeDeferred(oldInbound.NodeID) + return needRestart, nil } if push && len(targets) <= nodeBulkPushThreshold { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { for _, target := range targets { if target.email == "" { continue } - err := rt.DeleteUser(ctx, oldInbound, target.email) - if err != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err) + if !batch.acknowledge(rt.DeleteUser(ctx, oldInbound, target.email)) { return false } } advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) return true }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } return needRestart, nil } @@ -392,7 +395,7 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c return "", nil } -func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) { +func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (restartNeeded bool, saveErr error) { defer InvalidateSubData() mutation := beginInboundClientMutation(data.Id) defer mutation.close() @@ -449,6 +452,7 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model if err != nil { return false, err } + defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil { return false, err } @@ -707,15 +711,13 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } } } else if push && len(clients) <= nodeBulkPushThreshold { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { for _, client := range clients { // Older nodes coerce enable=true. Reconcile the rest of this batch. if !client.Enable { return false } - err1 := rt.AddClient(ctx, oldInbound, client) - if err1 != nil { - logger.Warning("Error in adding client on", rt.Name(), ":", err1) + if !batch.acknowledge(rt.AddClient(ctx, oldInbound, client)) { return false } } @@ -725,12 +727,14 @@ func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model } return !prunedOrphans }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } return needRestart, nil } -func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (bool, error) { +func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *model.Inbound, oldEmail string) (restartNeeded bool, saveErr error) { defer InvalidateSubData() mutation := beginInboundClientMutation(data.Id) defer mutation.close() @@ -758,6 +762,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if err != nil { return false, err } + defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil { return false, err } @@ -1190,16 +1195,18 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo } } } else if push { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { - if err := rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0]); err != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err) + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { + if !batch.acknowledge(rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0])) { return false } advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) return true }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } } else { + s.recordClientNodeDeferred(oldInbound.NodeID) logger.Debug("Client old email not found") needRestart = true } @@ -1207,7 +1214,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo return needRestart, nil } -func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (bool, error) { +func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inboundId int, email string, keepTraffic bool, fullDelete bool) (restartNeeded bool, saveErr error) { defer InvalidateSubData() mutation := beginInboundClientMutation(inboundId) defer mutation.close() @@ -1217,6 +1224,7 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo logger.Error("Load Old Data Error") return false, err } + defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) var settings map[string]any if err := json.Unmarshal([]byte(oldInbound.Settings), &settings); err != nil { @@ -1367,24 +1375,26 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo // must remove the node's client record too, not just detach it from // this inbound (#5797). if push { - mutation.push(rt, oldInbound, func(ctx context.Context) bool { - var err error + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { if fullDelete { + complete := len(pending) > 0 for _, row := range pending { - err = applyNodeClientDelete(ctx, rt, row) + result, attempted, err := applyNodeClientDelete(ctx, rt, row) + if !batch.acknowledge(result, err) { + return false + } + complete = complete && attempted } - } else { - err = rt.DeleteUser(ctx, oldInbound, email) + return complete } - if err != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err) + if !batch.acknowledge(rt.DeleteUser(ctx, oldInbound, email)) { return false } - if !fullDelete { - advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) return true }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } } } diff --git a/internal/web/service/client_lookup.go b/internal/web/service/client_lookup.go index 391d19563..d80cd99f6 100644 --- a/internal/web/service/client_lookup.go +++ b/internal/web/service/client_lookup.go @@ -237,17 +237,6 @@ func (s *ClientService) List() ([]ClientWithAttachments, error) { return out, nil } -func (s *ClientService) HasPendingNode(inboundSvc *InboundService, email string) bool { - if strings.TrimSpace(email) == "" { - return false - } - ids, err := s.GetInboundIdsForEmail(nil, email) - if err != nil { - return false - } - return inboundSvc.AnyNodePending(ids) -} - const settingsProbeBytes = 64 // findInboundIdsByClientEmail returns every inbound whose settings.clients[] diff --git a/internal/web/service/client_node_apply.go b/internal/web/service/client_node_apply.go new file mode 100644 index 000000000..4c7be4f19 --- /dev/null +++ b/internal/web/service/client_node_apply.go @@ -0,0 +1,106 @@ +package service + +import ( + "context" + "errors" + "sort" + "sync" + + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +type ClientNodeApplyOutcome struct { + NodeID int `json:"nodeId" example:"7"` + Status string `json:"status" enum:"applied,pending,failed" example:"pending"` + Reason string `json:"reason,omitempty" example:"timeout"` +} + +type ClientNodeApplyResponse struct { + NodePending bool `json:"nodePending,omitempty" example:"true"` + NodeResults []ClientNodeApplyOutcome `json:"nodeResults,omitempty"` +} + +type clientNodeApplyReport struct { + mu sync.Mutex + byNode map[int]ClientNodeApplyOutcome + pending bool +} + +var errClientNodePushBusy = errors.New("node client apply capacity reached") + +// TrackNodeApplies gives one request its own outcome collection. +func (s ClientService) TrackNodeApplies() ClientService { + s.nodeApplies = &clientNodeApplyReport{ + byNode: make(map[int]ClientNodeApplyOutcome), + } + return s +} + +func (s *ClientService) NodeApplyResponse() *ClientNodeApplyResponse { + report := s.nodeApplies + if report == nil { + return nil + } + report.mu.Lock() + defer report.mu.Unlock() + if len(report.byNode) == 0 { + return nil + } + result := &ClientNodeApplyResponse{NodePending: report.pending, NodeResults: make([]ClientNodeApplyOutcome, 0, len(report.byNode))} + for _, outcome := range report.byNode { + result.NodeResults = append(result.NodeResults, outcome) + } + sort.Slice(result.NodeResults, func(i, j int) bool { + return result.NodeResults[i].NodeID < result.NodeResults[j].NodeID + }) + return result +} + +func (s *ClientService) recordClientNodeFailure(id *int, err *error) { + if id != nil && *err != nil && !errors.Is(*err, ErrClientNotInInbound) { + s.recordClientNodeApply(*id, "failed", "local_save_failed") + } +} + +func (s *ClientService) recordClientNodePush(id int, attempted bool, result runtime.ClientApplyResult, err error) { + status, reason := "pending", "deferred" + switch { + case !attempted: + case err == nil && result.DownstreamPending: + reason = "downstream_pending" + case err == nil: + status, reason = "applied", "" + case errors.Is(err, context.DeadlineExceeded): + reason = "timeout" + case errors.Is(err, errClientNodePushBusy): + reason = "busy" + default: + reason = "push_failed" + } + s.recordClientNodeApply(id, status, reason) +} + +func (s *ClientService) recordClientNodeApply(id int, status, reason string) { + report := s.nodeApplies + if report == nil { + return + } + report.mu.Lock() + defer report.mu.Unlock() + report.pending = report.pending || status == "pending" + prev := report.byNode[id] + // Keep the most severe result when several inbounds share the same node. + if prev.Status == "failed" || prev.Status == "pending" && status == "applied" { + return + } + if prev.Status == status && prev.Reason != "deferred" && (reason == "deferred" || prev.Reason <= reason) { + return + } + report.byNode[id] = ClientNodeApplyOutcome{NodeID: id, Status: status, Reason: reason} +} + +func (s *ClientService) recordClientNodeDeferred(id *int) { + if id != nil { + s.recordClientNodePush(*id, false, runtime.ClientApplyResult{}, nil) + } +} diff --git a/internal/web/service/client_node_apply_test.go b/internal/web/service/client_node_apply_test.go new file mode 100644 index 000000000..9d69ccbae --- /dev/null +++ b/internal/web/service/client_node_apply_test.go @@ -0,0 +1,86 @@ +package service + +import ( + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestClientFanoutAdmitsHealthyNodeBeforeSlowNodeFillsSlots(t *testing.T) { + slow, healthy := 1, 2 + release := make(chan struct{}) + healthyStarted := make(chan struct{}) + applies := make([]inboundApply, 0, inboundFanoutConcurrency+1) + for i := range inboundFanoutConcurrency { + applies = append(applies, inboundApply{id: i + 1, nodeID: &slow, run: func() (bool, error) { + <-release + return false, nil + }}) + } + applies = append(applies, inboundApply{id: len(applies) + 1, nodeID: &healthy, run: func() (bool, error) { + close(healthyStarted) + return false, nil + }}) + done := make(chan error, 1) + go func() { + _, err := fanoutInboundApplies(applies) + done <- err + }() + defer func() { + close(release) + if err := <-done; err != nil { + t.Error(err) + } + }() + select { + case <-healthyStarted: + case <-time.After(2 * time.Second): + t.Fatal("healthy node waited for a slow node to free a slot") + } +} + +func TestBulkClientFanoutAdmitsHealthyNodeBeforeSlowNodeFillsSlots(t *testing.T) { + setupBulkDB(t) + slow := model.Node{Name: "slow", Address: "127.0.0.1", Port: 8443} + healthy := model.Node{Name: "healthy", Address: "127.0.0.1", Port: 8444} + if err := database.GetDB().Create(&slow).Error; err != nil { + t.Fatal(err) + } + if err := database.GetDB().Create(&healthy).Error; err != nil { + t.Fatal(err) + } + var ids []int + for i := range inboundFanoutConcurrency { + ids = append(ids, nodeInbound(t, slow.Id, 54500+i, nil).Id) + } + ids = append(ids, nodeInbound(t, healthy.Id, 54510, nil).Id) + release, started := make(chan struct{}), make(chan struct{}) + done := make(chan []int, 1) + go func() { + out, _ := fanoutClientInboundResults(ids, inboundFanoutConcurrency, func(i int) int { + if i == len(ids)-1 { + close(started) + } else { + <-release + } + return ids[i] + }) + done <- out + }() + defer func() { + close(release) + out := <-done + for i := range ids { + if out[i] != ids[i] { + t.Errorf("result %d belongs to inbound %d, want %d", i, out[i], ids[i]) + } + } + }() + select { + case <-started: + case <-time.After(time.Second): + t.Fatal("bulk fanout left the healthy inbound behind the slow node") + } +} diff --git a/internal/web/service/client_node_dispatch.go b/internal/web/service/client_node_dispatch.go index b00a47ec2..fc3aae0aa 100644 --- a/internal/web/service/client_node_dispatch.go +++ b/internal/web/service/client_node_dispatch.go @@ -4,10 +4,12 @@ import ( "container/list" "context" "sync" + "time" "gorm.io/gorm" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/logger" "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) @@ -19,6 +21,7 @@ var ( type nodeConfigQueue struct { groups list.List reconciles int + live int } // Inbounds in the same group can push concurrently. A node-wide operation @@ -161,7 +164,10 @@ func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWo return runSerializedTx(write) } nodeID := *inbound.NodeID - return runSerializedTxThen(func(tx *gorm.DB) error { + queuedAt := time.Now() + var startedAt time.Time + err := runSerializedTxThen(func(tx *gorm.DB) error { + startedAt = time.Now() if err := write(tx); err != nil { return err } @@ -169,19 +175,55 @@ func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWo }, func() { m.turn = reserveNodeConfigTurn(nodeID, inbound.Id, work) }) + if !startedAt.IsZero() { + logger.Debugf("client node save: node_id=%d writer_wait_ms=%d tx_ms=%d success=%t", nodeID, + startedAt.Sub(queuedAt).Milliseconds(), time.Since(startedAt).Milliseconds(), err == nil) + } + return err } -func (m *inboundClientMutation) push(rt runtime.Runtime, inbound *model.Inbound, apply func(context.Context) bool) { +type nodeClientBatch struct { + result runtime.ClientApplyResult + err error +} + +func (b *nodeClientBatch) acknowledge(result runtime.ClientApplyResult, err error) bool { + b.result.DownstreamPending = b.result.DownstreamPending || result.DownstreamPending + b.err = err + return err == nil +} + +func (m *inboundClientMutation) push(s *ClientService, rt runtime.Runtime, inbound *model.Inbound, apply func(context.Context, *nodeClientBatch) bool) { m.unlock() if m.turn == nil { + s.recordClientNodeDeferred(inbound.NodeID) return } + nodeID := m.turn.nodeID + queued := time.Now() waitCtx, stopWaiting := nodePushContext() ready := m.turn.wait(waitCtx) + waitErr := waitCtx.Err() stopWaiting() if !ready { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, waitErr) + logger.Debugf("client node apply: node_id=%d queue_wait_ms=%d deferred=timeout", nodeID, time.Since(queued).Milliseconds()) return } + // Conflicting turns wait without consuming a live slot. + nodeConfigDispatchMu.Lock() + if m.turn.queue.live >= inboundFanoutConcurrency { + nodeConfigDispatchMu.Unlock() + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy) + return + } + m.turn.queue.live++ + nodeConfigDispatchMu.Unlock() + defer func() { + nodeConfigDispatchMu.Lock() + m.turn.queue.live-- + nodeConfigDispatchMu.Unlock() + }() ctx, cancel := nodePushContext() defer cancel() complete := false @@ -190,5 +232,13 @@ func (m *inboundClientMutation) push(rt runtime.Runtime, inbound *model.Inbound, remote.ForgetPushedInbound(inbound.Tag) } }() - complete = apply(ctx) + started := time.Now() + var batch nodeClientBatch + complete = apply(ctx, &batch) + s.recordClientNodePush(nodeID, complete || batch.err != nil || batch.result.DownstreamPending, batch.result, batch.err) + if batch.err != nil { + logger.Warning("Error applying clients on", rt.Name(), ":", batch.err) + } + logger.Debugf("client node apply: node_id=%d queue_wait_ms=%d rpc_ms=%d complete=%t downstream_pending=%t", + nodeID, started.Sub(queued).Milliseconds(), time.Since(started).Milliseconds(), complete, batch.result.DownstreamPending) } diff --git a/internal/web/service/client_node_order_test.go b/internal/web/service/client_node_order_test.go index f3f1d1a5b..771867366 100644 --- a/internal/web/service/client_node_order_test.go +++ b/internal/web/service/client_node_order_test.go @@ -32,14 +32,14 @@ type blockedClientPushRuntime struct { expired atomic.Bool } -func (r *blockedClientPushRuntime) AddClient(ctx context.Context, _ *model.Inbound, client model.Client) error { +func (r *blockedClientPushRuntime) AddClient(ctx context.Context, _ *model.Inbound, client model.Client) (runtime.ClientApplyResult, error) { r.calls <- "add " + client.Email if client.Email != r.blockedEmail { - return nil + return runtime.ClientApplyResult{}, nil } if r.waitForTimeout { if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > nodeClientPushTimeout { - return errors.New("push timeout was not enforced") + return runtime.ClientApplyResult{}, errors.New("push timeout was not enforced") } // Give the node a shorter deadline so this case exercises RPC ordering // and the queue-expiry regression can test the separate wait budget. @@ -47,24 +47,24 @@ func (r *blockedClientPushRuntime) AddClient(ctx context.Context, _ *model.Inbou defer cancel() <-call.Done() r.expired.Store(errors.Is(call.Err(), context.DeadlineExceeded)) - return call.Err() + return runtime.ClientApplyResult{}, call.Err() } select { case <-r.release: - return nil + return runtime.ClientApplyResult{}, nil case <-ctx.Done(): - return ctx.Err() + return runtime.ClientApplyResult{}, ctx.Err() } } -func (r *blockedClientPushRuntime) UpdateUser(_ context.Context, _ *model.Inbound, email string, client model.Client) error { +func (r *blockedClientPushRuntime) UpdateUser(_ context.Context, _ *model.Inbound, email string, client model.Client) (runtime.ClientApplyResult, error) { r.calls <- "update " + email + " " + client.Comment - return nil + return runtime.ClientApplyResult{}, nil } -func (r *blockedClientPushRuntime) DeleteUser(_ context.Context, _ *model.Inbound, email string) error { +func (r *blockedClientPushRuntime) DeleteUser(_ context.Context, _ *model.Inbound, email string) (runtime.ClientApplyResult, error) { r.calls <- "detach " + email - return nil + return runtime.ClientApplyResult{}, nil } func (r *blockedClientPushRuntime) UpdateInbound(_ context.Context, _ *model.Inbound, inbound *model.Inbound) error { diff --git a/internal/web/service/client_node_push_test.go b/internal/web/service/client_node_push_test.go index 9d6b135cd..ed2c52513 100644 --- a/internal/web/service/client_node_push_test.go +++ b/internal/web/service/client_node_push_test.go @@ -1,8 +1,10 @@ package service import ( + "fmt" "os" "path/filepath" + "sync" "testing" "time" @@ -116,3 +118,160 @@ func TestBulkDeleteStopsPushingToAHungNode(t *testing.T) { t.Fatalf("delete requests including replay after reopening = %d, want 4 (one timed out, then all three retried)", got) } } + +func TestClientBatchesContinueAfterDownstreamPendingAck(t *testing.T) { + tests := []struct { + name string + path string + run func(*testing.T, *ClientService, *InboundService, *model.Inbound, []string) error + }{ + {"full delete", "/clients/del/", func(_ *testing.T, svc *ClientService, inbounds *InboundService, _ *model.Inbound, emails []string) error { + _, _, err := svc.BulkDelete(inbounds, emails, false) + return err + }}, + {"disable", "/clients/update/", func(_ *testing.T, svc *ClientService, inbounds *InboundService, _ *model.Inbound, emails []string) error { + _, _, err := svc.BulkSetEnable(inbounds, emails, false) + return err + }}, + {"adjust", "/clients/update/", func(_ *testing.T, svc *ClientService, inbounds *InboundService, _ *model.Inbound, emails []string) error { + _, _, err := svc.BulkAdjust(inbounds, emails, 1, 0, "", nil, "") + return err + }}, + {"detach", "/detach", func(t *testing.T, svc *ClientService, inbounds *InboundService, ib *model.Inbound, emails []string) error { + records := make([]*model.ClientRecord, 0, len(emails)) + for _, email := range emails { + record := lookupClientRecord(t, email) + records = append(records, &record) + } + _, err := svc.delInboundClients(inbounds, ib.Id, records, true) + return err + }}, + {"add", "/clients/add", func(t *testing.T, svc *ClientService, inbounds *InboundService, original *model.Inbound, _ []string) error { + target := *original + target.Settings = clientsSettings(t, makeNodeClients(3)) + _, err := svc.AddInboundClient(inbounds, &target) + return err + }}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + setupBulkDB(t) + startSerializedWriter(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + fake.mu.Lock() + fake.pendingClientAcks = 1 + fake.mu.Unlock() + + const batchSize = 3 + clients := makeNodeClients(batchSize) + emails := make([]string, 0, batchSize) + for i := range clients { + clients[i].Email = "seed-" + clients[i].Email + clients[i].SubID = clients[i].Email + clients[i].ExpiryTime = time.Now().Add(24 * time.Hour).UnixMilli() + emails = append(emails, clients[i].Email) + } + inbound := realNodeInbound(t, fake, 53300, clients) + for _, client := range clients { + mkTraffic(t, inbound.Id, client.Email, 0, 0, 0, client.ExpiryTime, true) + } + + svc := (ClientService{}).TrackNodeApplies() + if err := tt.run(t, &svc, &InboundService{}, inbound, emails); err != nil { + t.Fatal(err) + } + if got := fake.hitCount(tt.path); got != batchSize { + t.Errorf("node received %d requests, want %d after acknowledging downstream pending", got, batchSize) + } + result := svc.NodeApplyResponse() + want := ClientNodeApplyOutcome{NodeID: *inbound.NodeID, Status: "pending", Reason: "downstream_pending"} + if result == nil || !result.NodePending || len(result.NodeResults) != 1 || result.NodeResults[0] != want { + t.Errorf("%s report = %+v, want one downstream pending outcome", tt.name, result) + } + }) + } +} + +func TestNodeClientCapacityPreservesPermanentDelete(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + node := newFakeNodeHTTP(t) + const email = "durable-under-load@example.test" + target := realNodeInbound(t, node, 53400, []model.Client{{Email: email, ID: "a820e1e7-7bc8-4cc3-a5e4-cd8805271ea7", Enable: true}}) + nodeID := *target.NodeID + inboundSvc := &InboundService{} + adds := make([]*model.Inbound, 0, inboundFanoutConcurrency+1) + for i := range inboundFanoutConcurrency + 1 { + ib := nodeInbound(t, nodeID, 53401+i, nil) + node.mu.Lock() + node.tags[ib.Tag] = 200 + i + node.mu.Unlock() + adds = append(adds, &model.Inbound{ + Id: ib.Id, Protocol: ib.Protocol, + Settings: clientsSettings(t, []model.Client{{ + Email: fmt.Sprintf("load-%d@example.test", i), + ID: fmt.Sprintf("66666666-1111-2222-3333-%012d", i+1), Enable: true, + }}), + }) + } + node.setHold(true) + errs := make(chan error, inboundFanoutConcurrency) + var wg sync.WaitGroup + t.Cleanup(wg.Wait) + for _, add := range adds[:inboundFanoutConcurrency] { + wg.Go(func() { + _, err := (&ClientService{}).AddInboundClient(inboundSvc, add) + errs <- err + }) + } + deadline := time.Now().Add(2 * time.Second) + for node.hitCount("/clients/add") < inboundFanoutConcurrency { + if time.Now().After(deadline) { + t.Fatal("parallel RPCs did not occupy all live slots") + } + time.Sleep(5 * time.Millisecond) + } + clientSvc := (ClientService{}).TrackNodeApplies() + if _, err := clientSvc.AddInboundClient(inboundSvc, adds[inboundFanoutConcurrency]); err != nil { + t.Fatal(err) + } + report := clientSvc.NodeApplyResponse() + if report == nil || len(report.NodeResults) != 1 || report.NodeResults[0].Reason != "busy" || + node.hitCount("/clients/add") != inboundFanoutConcurrency { + t.Fatalf("saturated delta must save without taking a live slot: %+v", report) + } + + earlier := reserveNodeConfigTurn(nodeID, target.Id, nodeClientDelta) + defer earlier.release() + record := lookupClientRecord(t, email) + deleteSvc := (ClientService{}).TrackNodeApplies() + if _, err := deleteSvc.Delete(inboundSvc, record.Id, false); err != nil { + t.Fatal(err) + } + report = deleteSvc.NodeApplyResponse() + if report == nil || len(report.NodeResults) != 1 || report.NodeResults[0].Reason != "timeout" || + node.hitCount("/clients/del/") != 0 { + t.Fatalf("exclusive delete must defer when its queue wait expires: %+v", report) + } + earlier.release() + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Fatal(err) + } + } + + node.setHold(false) + var row model.Node + if err := database.GetDB().First(&row, nodeID).Error; err != nil { + t.Fatal(err) + } + if err := inboundSvc.ReconcileNode(t.Context(), runtime.NewRemote(&row, nil), &row); err != nil { + t.Fatal(err) + } + if got := node.hitCount("/clients/del/"); got != 1 { + t.Fatalf("reconcile sent %d permanent deletes after saturation, want one", got) + } +} diff --git a/internal/web/service/client_update_fanout_test.go b/internal/web/service/client_update_fanout_test.go index 5efea58b7..455ec5212 100644 --- a/internal/web/service/client_update_fanout_test.go +++ b/internal/web/service/client_update_fanout_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) // applyBarrierRuntime holds every armed node push until fanout of them are @@ -60,12 +61,12 @@ func (b *applyBarrierRuntime) wait() { b.inFlight.Add(-1) } -func (b *applyBarrierRuntime) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, c model.Client) error { +func (b *applyBarrierRuntime) UpdateUser(ctx context.Context, ib *model.Inbound, oldEmail string, c model.Client) (runtime.ClientApplyResult, error) { b.wait() return b.fakeNodeRuntime.UpdateUser(ctx, ib, oldEmail, c) } -func (b *applyBarrierRuntime) AddClient(ctx context.Context, ib *model.Inbound, c model.Client) error { +func (b *applyBarrierRuntime) AddClient(ctx context.Context, ib *model.Inbound, c model.Client) (runtime.ClientApplyResult, error) { b.wait() return b.fakeNodeRuntime.AddClient(ctx, ib, c) } @@ -75,12 +76,12 @@ func (b *applyBarrierRuntime) ResetClientTraffic(ctx context.Context, ib *model. return b.fakeNodeRuntime.ResetClientTraffic(ctx, ib, email) } -func (b *applyBarrierRuntime) DeleteClient(ctx context.Context, email string) error { +func (b *applyBarrierRuntime) DeleteClient(ctx context.Context, email string) (runtime.ClientApplyResult, error) { b.wait() return b.fakeNodeRuntime.DeleteClient(ctx, email) } -func (b *applyBarrierRuntime) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error { +func (b *applyBarrierRuntime) DeleteUser(ctx context.Context, ib *model.Inbound, email string) (runtime.ClientApplyResult, error) { b.wait() return b.fakeNodeRuntime.DeleteUser(ctx, ib, email) } diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 2b4887144..b80d7ea7b 100644 --- a/internal/web/service/inbound_node.go +++ b/internal/web/service/inbound_node.go @@ -111,23 +111,6 @@ func (s *InboundService) NodeIsPending(nodeID *int) bool { return (&NodeService{}).IsNodePending(*nodeID) } -func (s *InboundService) AnyNodePending(inboundIds []int) bool { - if len(inboundIds) == 0 { - return false - } - nodeSvc := NodeService{} - for _, id := range uniqueInts(inboundIds) { - ib, err := s.GetInbound(id) - if err != nil || ib.NodeID == nil { - continue - } - if nodeSvc.IsNodePending(*ib.NodeID) { - return true - } - } - return false -} - // ReconcileNode pushes every inbound and sweeps undesired remote tags even when // individual operations fail, returning the failures joined: one inbound the // node rejects (e.g. a legacy protocol failing validation, #5685) must not @@ -469,11 +452,32 @@ func (s *InboundService) SnapshotHasUnadoptedInbounds(nodeID int, snap *runtime. // SetRemoteTraffic merges a node snapshot. justPushed marks the tick whose // config push just landed, whose snapshot may still predate it (#6228). func (s *InboundService) SetRemoteTraffic(nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) { + return s.mergeNodeTraffic(context.Background(), nodeID, snap, dirty, justPushed, false) +} + +// MergeOnlineNodeTraffic rechecks eligibility inside the serialized writer. +func (s *InboundService) MergeOnlineNodeTraffic(ctx context.Context, nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed bool) (bool, error) { + return s.mergeNodeTraffic(ctx, nodeID, snap, dirty, justPushed, true) +} + +func (s *InboundService) mergeNodeTraffic(ctx context.Context, nodeID int, snap *runtime.TrafficSnapshot, dirty, justPushed, requireOnline bool) (bool, error) { var structuralChange bool queuedAt := time.Now() // Node merges take the background lane: a per-client mutation the operator // is waiting on must not queue behind the next batch of 5s snapshots. err := submitTrafficWriteBackground(func() error { + if err := ctx.Err(); err != nil { + return err + } + if requireOnline { + enabled, status, _, _, err := (&NodeService{}).NodeSyncState(nodeID) + if err != nil { + return err + } + if !enabled || status != "online" { + return context.Canceled + } + } started := time.Now() var inner error structuralChange, inner = s.setRemoteTrafficLocked(nodeID, snap, dirty, justPushed) diff --git a/internal/web/service/node.go b/internal/web/service/node.go index 735448b24..bac491ed1 100644 --- a/internal/web/service/node.go +++ b/internal/web/service/node.go @@ -851,32 +851,19 @@ func FilterNodeSnapshot(n *model.Node, snap *runtime.TrafficSnapshot) { } func (s *NodeService) Delete(id int) error { - db := database.GetDB() - // Refuse to delete a node that still owns inbounds: dropping the node row - // while inbounds keep its node_id leaves orphaned, dangling references that - // confuse node sync, subscriptions and cleanup. The operator must detach or - // remove those inbounds first. (DB-002) - var attached int64 - if err := db.Model(&model.Inbound{}).Where("node_id = ?", id).Count(&attached).Error; err != nil { - return err - } - if attached > 0 { - return common.NewError(fmt.Sprintf("cannot delete node: %d inbound(s) still attached to it; detach or delete them first", attached)) - } - // Capture the node's guid before deleting the row so we can drop its per-node - // IP attribution. NodeClientIp is keyed by the node's attribution key, which - // is its guid normally but its node-unique key for a cloned/ambiguous-guid - // node (see effectiveNodeKey) — so we purge both below. - var guid string - var n model.Node - if err := db.Select("guid").Where("id = ?", id).First(&n).Error; err == nil { - guid = n.Guid - } - // Delete the node row and its per-node child rows atomically. Remove the - // children (traffic baselines, IP attribution) before the parent node row so - // the ordering already matches a future ON DELETE constraint. Delete stays - // tolerant of a missing node row so it can still clean up orphaned baselines. - if err := db.Transaction(func(tx *gorm.DB) error { + // Order the attachment check with snapshot adoption on the shared writer. + if err := runSerializedTx(func(tx *gorm.DB) error { + var attached int64 + if err := tx.Model(&model.Inbound{}).Where("node_id = ?", id).Count(&attached).Error; err != nil { + return err + } + if attached > 0 { + 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 + if err := tx.Select("guid").Where("id = ?", id).First(&n).Error; err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { + return err + } if err := tx.Where("node_id = ?", id).Delete(&model.NodeClientTraffic{}).Error; err != nil { return err } @@ -887,8 +874,8 @@ func (s *NodeService) Delete(id int) error { return err } guids := []string{synthNodeGuid(id)} - if guid != "" { - guids = append(guids, guid) + if n.Guid != "" { + guids = append(guids, n.Guid) } if err := tx.Where("node_guid IN ?", guids).Delete(&model.NodeClientIp{}).Error; err != nil { return err @@ -907,8 +894,9 @@ func (s *NodeService) Delete(id int) error { } func (s *NodeService) SetEnable(id int, enable bool) error { - db := database.GetDB() - if err := db.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error; err != nil { + if err := runSerializedTx(func(tx *gorm.DB) error { + return tx.Model(model.Node{}).Where("id = ?", id).Update("enable", enable).Error + }); err != nil { return err } if mgr := runtime.GetManager(); mgr != nil { diff --git a/internal/web/service/node_bulk_dispatch_test.go b/internal/web/service/node_bulk_dispatch_test.go index 6e33f9702..2f6d89dd2 100644 --- a/internal/web/service/node_bulk_dispatch_test.go +++ b/internal/web/service/node_bulk_dispatch_test.go @@ -54,24 +54,24 @@ func (f *fakeNodeRuntime) AddUser(context.Context, *model.Inbound, map[string]an func (f *fakeNodeRuntime) RemoveUser(context.Context, *model.Inbound, string) error { return nil } -func (f *fakeNodeRuntime) UpdateUser(context.Context, *model.Inbound, string, model.Client) error { +func (f *fakeNodeRuntime) UpdateUser(context.Context, *model.Inbound, string, model.Client) (runtime.ClientApplyResult, error) { f.updateUser.Add(1) - return nil + return runtime.ClientApplyResult{}, nil } -func (f *fakeNodeRuntime) DeleteUser(context.Context, *model.Inbound, string) error { +func (f *fakeNodeRuntime) DeleteUser(context.Context, *model.Inbound, string) (runtime.ClientApplyResult, error) { f.deleteUser.Add(1) - return nil + return runtime.ClientApplyResult{}, nil } -func (f *fakeNodeRuntime) DeleteClient(context.Context, string) error { +func (f *fakeNodeRuntime) DeleteClient(context.Context, string) (runtime.ClientApplyResult, error) { f.deleteClient.Add(1) - return nil + return runtime.ClientApplyResult{}, nil } -func (f *fakeNodeRuntime) AddClient(context.Context, *model.Inbound, model.Client) error { +func (f *fakeNodeRuntime) AddClient(context.Context, *model.Inbound, model.Client) (runtime.ClientApplyResult, error) { f.addClient.Add(1) - return nil + return runtime.ClientApplyResult{}, nil } func (f *fakeNodeRuntime) RestartXray(context.Context) error { return nil } func (f *fakeNodeRuntime) ResetClientTraffic(context.Context, *model.Inbound, string) error { @@ -103,7 +103,7 @@ func useTestRuntimeManager(t *testing.T) *runtime.Manager { // apply path that would otherwise unwind straight out of a fanout goroutine. type panicNodeRuntime struct{ fakeNodeRuntime } -func (p *panicNodeRuntime) AddClient(context.Context, *model.Inbound, model.Client) error { +func (p *panicNodeRuntime) AddClient(context.Context, *model.Inbound, model.Client) (runtime.ClientApplyResult, error) { panic("boom from node runtime") } diff --git a/internal/web/service/node_client_delete_queue.go b/internal/web/service/node_client_delete_queue.go index e494420ed..af466dfe2 100644 --- a/internal/web/service/node_client_delete_queue.go +++ b/internal/web/service/node_client_delete_queue.go @@ -51,7 +51,7 @@ func sameNodeClientDelete(db *gorm.DB, row model.NodePendingClientDelete) *gorm. // applyNodeClientDelete runs under the node-wide turn. Later attached clients // push after this turn or are restored by the dirty generation on reconcile. -func applyNodeClientDelete(ctx context.Context, rt runtime.Runtime, row model.NodePendingClientDelete) error { +func applyNodeClientDelete(ctx context.Context, rt runtime.Runtime, row model.NodePendingClientDelete) (runtime.ClientApplyResult, bool, error) { db := database.GetDB().WithContext(ctx) var target struct { Desired bool @@ -63,16 +63,19 @@ func applyNodeClientDelete(ctx context.Context, rt runtime.Runtime, row model.No Joins("LEFT JOIN clients ON clients.email = node_pending_client_deletes.email"). Limit(1).Scan(&target) if result.Error != nil || result.RowsAffected == 0 { - return result.Error + return runtime.ClientApplyResult{}, false, result.Error } // Only a desired attachment on this node supersedes its pending delete. // Recreating the email elsewhere must not leave the old node record behind. + var applied runtime.ClientApplyResult if !target.Desired { - if err := rt.DeleteClient(ctx, row.Email); err != nil { - return err + var err error + applied, err = rt.DeleteClient(ctx, row.Email) + if err != nil { + return applied, false, err } } - return sameNodeClientDelete(db, row).Delete(&model.NodePendingClientDelete{}).Error + return applied, !target.Desired, sameNodeClientDelete(db, row).Delete(&model.NodePendingClientDelete{}).Error } const nodeClientDeletePage = 200 @@ -93,7 +96,7 @@ func deliverNodeClientDeletes(ctx context.Context, nodeID int, rt runtime.Runtim defer cancel() var firstErr error for _, row := range rows { - if err := applyNodeClientDelete(sendCtx, rt, row); err != nil { + if _, _, err := applyNodeClientDelete(sendCtx, rt, row); err != nil { if firstErr == nil { firstErr = err } diff --git a/internal/web/service/node_dirty_test.go b/internal/web/service/node_dirty_test.go index 111cba574..35a186754 100644 --- a/internal/web/service/node_dirty_test.go +++ b/internal/web/service/node_dirty_test.go @@ -3,6 +3,7 @@ package service import ( "errors" "testing" + "time" "gorm.io/gorm" @@ -11,6 +12,29 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) +func TestMarkNodeDirtyAdvancesRevisionPastCurrentClock(t *testing.T) { + setupConflictDB(t) + node := model.Node{ + Name: "revision", Enable: true, ConfigDirty: true, + ConfigDirtyAt: time.Now().Add(time.Minute).UnixMilli(), + } + db := database.GetDB() + if err := db.Create(&node).Error; err != nil { + t.Fatal(err) + } + svc := &NodeService{} + if err := svc.MarkNodeDirty(node.Id); err != nil { + t.Fatal(err) + } + if err := svc.ClearNodeDirty(node.Id, node.ConfigDirtyAt); err != nil { + t.Fatal(err) + } + _, _, dirty, revision, err := svc.NodeSyncState(node.Id) + if err != nil || !dirty || revision <= node.ConfigDirtyAt { + t.Fatalf("dirty=%t revision=%d, want dirty revision newer than %d: %v", dirty, revision, node.ConfigDirtyAt, err) + } +} + // While a node is config-dirty (a local edit committed before it could be // mirrored to the node), the traffic pull must not overwrite the central // inbound's config columns from the node's stale snapshot — only traffic diff --git a/internal/web/service/node_http_fake_test.go b/internal/web/service/node_http_fake_test.go index 609123e9d..b5ce92530 100644 --- a/internal/web/service/node_http_fake_test.go +++ b/internal/web/service/node_http_fake_test.go @@ -19,11 +19,12 @@ import ( // fakeNodeHTTP emulates a node panel over real HTTP, so the master's Remote // (tag cache, list fetch, per-op RPC, timeouts) runs for real, not a stub. type fakeNodeHTTP struct { - srv *httptest.Server - mu sync.Mutex - tags map[string]int - hits map[string]int - caps string + srv *httptest.Server + mu sync.Mutex + tags map[string]int + hits map[string]int + caps string + pendingClientAcks int // hold makes every non-list request block until the master gives up. hold bool release chan struct{} @@ -56,6 +57,10 @@ func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { f.mu.Lock() f.hits[r.URL.Path]++ hold := f.hold + pending := f.pendingClientAcks > 0 && strings.Contains(r.URL.Path, "/clients/") + if pending { + f.pendingClientAcks-- + } f.mu.Unlock() if hold { // Drain first: the server only notices a client disconnect once the @@ -67,6 +72,10 @@ func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { } return } + if pending { + _, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":true}}`)) + return + } _, _ = w.Write([]byte(`{"success":true,"msg":""}`)) })) t.Cleanup(f.srv.Close) diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index f8766bf36..dd6b04f5f 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "تمت إضافة عميل(عملاء) وارد", "inboundClientDeleteSuccess": "تم حذف عميل وارد", "inboundClientUpdateSuccess": "تم تحديث عميل وارد", - "savedNodeOfflineWillSync": "تم الحفظ محليًا. إحدى العُقد الداعمة غير متصلة أو معطّلة — ستتم مزامنة التغيير بمجرد إعادة الاتصال.", + "savedNodeApplyPending": "تم الحفظ محليًا. لم يُطبَّق التغيير على عقدة واحدة أو أكثر بعد.", "resetAllClientTrafficSuccess": "تم إعادة تعيين كل حركة المرور من العميل", "resetAllTrafficSuccess": "تم إعادة تعيين كل حركة المرور", "resetInboundClientTrafficSuccess": "تم إعادة تعيين حركة المرور", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 24af28443..5457d21d5 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -476,7 +476,7 @@ "inboundClientAddSuccess": "Inbound client(s) have been added.", "inboundClientDeleteSuccess": "Inbound client has been deleted.", "inboundClientUpdateSuccess": "Inbound client has been updated.", - "savedNodeOfflineWillSync": "Saved locally. A backing node is offline or disabled — the change will sync once it reconnects.", + "savedNodeApplyPending": "Saved locally. Applying the change on one or more nodes is pending.", "resetAllClientTrafficSuccess": "Traffic for all clients has been reset.", "resetAllTrafficSuccess": "All traffic has been reset.", "resetInboundClientTrafficSuccess": "Traffic has been reset.", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index 42429f419..f9591939d 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Cliente(s) de entrada añadido(s)", "inboundClientDeleteSuccess": "Cliente de entrada eliminado", "inboundClientUpdateSuccess": "Cliente de entrada actualizado", - "savedNodeOfflineWillSync": "Guardado localmente. Un nodo de respaldo está desconectado o deshabilitado: el cambio se sincronizará cuando vuelva a conectarse.", + "savedNodeApplyPending": "Guardado localmente. El cambio está pendiente de aplicarse en uno o más nodos.", "resetAllClientTrafficSuccess": "Todo el tráfico del cliente ha sido reiniciado", "resetAllTrafficSuccess": "Todo el tráfico ha sido reiniciado", "resetInboundClientTrafficSuccess": "El tráfico ha sido reiniciado", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index 5f8bf7016..32b06d5fe 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "کلاینت(های) ورودی اضافه شدند", "inboundClientDeleteSuccess": "کلاینت ورودی حذف شد", "inboundClientUpdateSuccess": "کلاینت ورودی به‌روزرسانی شد", - "savedNodeOfflineWillSync": "به‌صورت محلی ذخیره شد. یک نود پشتیبان آفلاین یا غیرفعال است — تغییر پس از اتصال مجدد همگام‌سازی می‌شود.", + "savedNodeApplyPending": "به‌صورت محلی ذخیره شد. اعمال تغییر روی یک یا چند نود در انتظار همگام‌سازی است.", "resetAllClientTrafficSuccess": "تمام ترافیک کلاینت بازنشانی شد", "resetAllTrafficSuccess": "تمام ترافیک‌ها بازنشانی شدند", "resetInboundClientTrafficSuccess": "ترافیک بازنشانی شد", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 209bdc64e..e5f93b779 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Klien inbound telah ditambahkan", "inboundClientDeleteSuccess": "Klien inbound telah dihapus", "inboundClientUpdateSuccess": "Klien inbound telah diperbarui", - "savedNodeOfflineWillSync": "Disimpan secara lokal. Node pendukung sedang offline atau dinonaktifkan — perubahan akan disinkronkan setelah terhubung kembali.", + "savedNodeApplyPending": "Disimpan secara lokal. Penerapan perubahan pada satu atau beberapa node masih tertunda.", "resetAllClientTrafficSuccess": "Semua lalu lintas klien telah direset", "resetAllTrafficSuccess": "Semua lalu lintas telah direset", "resetInboundClientTrafficSuccess": "Lalu lintas telah direset", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 58837eb0a..b7980610e 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "インバウンドクライアントが追加されました", "inboundClientDeleteSuccess": "インバウンドクライアントが削除されました", "inboundClientUpdateSuccess": "インバウンドクライアントが更新されました", - "savedNodeOfflineWillSync": "ローカルに保存しました。バックエンドのノードがオフラインまたは無効になっています — 再接続後に変更が同期されます。", + "savedNodeApplyPending": "ローカルに保存しました。1 つ以上のノードへの変更の適用が保留中です。", "resetAllClientTrafficSuccess": "クライアントのすべてのトラフィックがリセットされました", "resetAllTrafficSuccess": "すべてのトラフィックがリセットされました", "resetInboundClientTrafficSuccess": "トラフィックがリセットされました", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index f5454593c..94527b479 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Cliente(s) de entrada adicionado(s)", "inboundClientDeleteSuccess": "Cliente de entrada excluído", "inboundClientUpdateSuccess": "Cliente de entrada atualizado", - "savedNodeOfflineWillSync": "Salvo localmente. Um nó de apoio está offline ou desativado — a alteração será sincronizada assim que reconectar.", + "savedNodeApplyPending": "Salvo localmente. A aplicação da alteração em um ou mais nós está pendente.", "resetAllClientTrafficSuccess": "Todo o tráfego do cliente foi reiniciado", "resetAllTrafficSuccess": "Todo o tráfego foi reiniciado", "resetInboundClientTrafficSuccess": "O tráfego foi reiniciado", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 3e336f3fe..41e5e7bdd 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -476,7 +476,7 @@ "inboundClientAddSuccess": "Клиент(ы) подключения добавлен(ы)", "inboundClientDeleteSuccess": "Клиент подключения удалён", "inboundClientUpdateSuccess": "Клиент подключения обновлён", - "savedNodeOfflineWillSync": "Сохранено локально. Опорный узел отключён или недоступен — изменение синхронизируется после повторного подключения.", + "savedNodeApplyPending": "Сохранено локально. Изменение ещё не применено на одном или нескольких узлах.", "resetAllClientTrafficSuccess": "Весь трафик клиента сброшен", "resetAllTrafficSuccess": "Весь трафик сброшен", "resetInboundClientTrafficSuccess": "Трафик сброшен", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index d564f6aad..15c69af56 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -476,7 +476,7 @@ "inboundClientAddSuccess": "Klienti boli pridaní k vstupu.", "inboundClientDeleteSuccess": "Klient bol odstránený zo vstupu.", "inboundClientUpdateSuccess": "Klient na vstupe bol aktualizovaný.", - "savedNodeOfflineWillSync": "Uložené miestne. Príslušný server je offline alebo vypnutý. Zmena sa zosynchronizuje po jeho opätovnom pripojení.", + "savedNodeApplyPending": "Uložené lokálne. Zmena ešte čaká na uplatnenie na jednom alebo viacerých uzloch.", "resetAllClientTrafficSuccess": "Spotreba všetkých klientov bola vynulovaná.", "resetAllTrafficSuccess": "Všetka spotreba bola vynulovaná.", "resetInboundClientTrafficSuccess": "Spotreba bola vynulovaná.", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index 6baa7a495..b52fa0f09 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Gelen bağlantı kullanıcı(lar)ı eklendi.", "inboundClientDeleteSuccess": "Gelen bağlantı kullanıcısı silindi.", "inboundClientUpdateSuccess": "Gelen bağlantı kullanıcısı güncellendi.", - "savedNodeOfflineWillSync": "Yerel olarak kaydedildi. Destekleyen bir düğüm çevrimdışı veya devre dışı — değişiklik yeniden bağlandığında senkronize edilecek.", + "savedNodeApplyPending": "Yerel olarak kaydedildi. Değişikliğin bir veya daha fazla düğüme uygulanması bekleniyor.", "resetAllClientTrafficSuccess": "Tüm kullanıcıların trafiği sıfırlandı.", "resetAllTrafficSuccess": "Tüm trafik sıfırlandı.", "resetInboundClientTrafficSuccess": "Trafik sıfırlandı.", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index defd6b693..48082a511 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Клієнт(и) вхідного підключення додано", "inboundClientDeleteSuccess": "Клієнта вхідного підключення видалено", "inboundClientUpdateSuccess": "Клієнта вхідного підключення оновлено", - "savedNodeOfflineWillSync": "Збережено локально. Опорний вузол вимкнено або недоступний — зміни синхронізуються після повторного підключення.", + "savedNodeApplyPending": "Збережено локально. Зміна ще очікує застосування на одному чи кількох вузлах.", "resetAllClientTrafficSuccess": "Весь трафік клієнта скинуто", "resetAllTrafficSuccess": "Весь трафік скинуто", "resetInboundClientTrafficSuccess": "Трафік скинуто", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 9ac29d089..a2a7060d0 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "Đã thêm client inbound", "inboundClientDeleteSuccess": "Đã xóa client inbound", "inboundClientUpdateSuccess": "Đã cập nhật client inbound", - "savedNodeOfflineWillSync": "Đã lưu cục bộ. Một nút hỗ trợ đang ngoại tuyến hoặc bị tắt — thay đổi sẽ được đồng bộ khi kết nối lại.", + "savedNodeApplyPending": "Đã lưu cục bộ. Thay đổi đang chờ áp dụng trên một hoặc nhiều nút.", "resetAllClientTrafficSuccess": "Đã đặt lại toàn bộ lưu lượng client", "resetAllTrafficSuccess": "Đã đặt lại toàn bộ lưu lượng", "resetInboundClientTrafficSuccess": "Đã đặt lại lưu lượng", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index fbfd10cd6..fcb7b7535 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "已添加入站客户端", "inboundClientDeleteSuccess": "入站客户端已删除", "inboundClientUpdateSuccess": "入站客户端已更新", - "savedNodeOfflineWillSync": "已在本地保存。某个支撑节点离线或已禁用——重新连接后将同步此更改。", + "savedNodeApplyPending": "已在本地保存。更改尚未应用到一个或多个节点。", "resetAllClientTrafficSuccess": "客户端所有流量已重置", "resetAllTrafficSuccess": "所有流量已重置", "resetInboundClientTrafficSuccess": "流量已重置", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index a1d96b556..04922e8ef 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -475,7 +475,7 @@ "inboundClientAddSuccess": "已新增入站客戶端", "inboundClientDeleteSuccess": "入站客戶端已刪除", "inboundClientUpdateSuccess": "入站客戶端已更新", - "savedNodeOfflineWillSync": "已在本機儲存。某個支撐節點離線或已停用——重新連線後將同步此變更。", + "savedNodeApplyPending": "已在本機儲存。變更尚未套用到一個或多個節點。", "resetAllClientTrafficSuccess": "客戶端所有流量已重置", "resetAllTrafficSuccess": "所有流量已重置", "resetInboundClientTrafficSuccess": "流量已重置", diff --git a/internal/web/web.go b/internal/web/web.go index f00823791..f6c6f388f 100644 --- a/internal/web/web.go +++ b/internal/web/web.go @@ -137,6 +137,7 @@ type Server struct { bus *eventbus.Bus cron *cron.Cron + nodeTrafficJob *job.NodeTrafficSyncJob discordNotifyEntryID cron.EntryID wechatNotifyEntryID cron.EntryID cpuAlarmEntryID cron.EntryID @@ -364,7 +365,8 @@ func (s *Server) startTask(restartXray bool, loc *time.Location) { _, _ = s.cron.AddJob(cadenceNodeHeartbeat, job.NewNodeHeartbeatJob()) - _, _ = s.cron.AddJob(cadenceNodeTraffic, job.NewNodeTrafficSyncJob()) + s.nodeTrafficJob = job.NewNodeTrafficSyncJob() + _, _ = s.cron.AddJob(cadenceNodeTraffic, s.nodeTrafficJob) // Outbound subscription auto-refresh (respects per-sub updateInterval) _, _ = s.cron.AddJob(cadenceOutboundSub, job.NewOutboundSubscriptionJob()) @@ -816,6 +818,12 @@ func (s *Server) stop(ctx context.Context, stopXray bool, stopTgBot bool) error return nil }) } + if s.nodeTrafficJob != nil { + _ = runPanelStopPhase("node traffic drain", func() error { + s.nodeTrafficJob.Close() + return nil + }) + } if stopXray { tuic.GetManager().StopAll() if err := job.NewTuicJob().FlushStoppedTraffic(); err != nil { diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index f40382268..2633d92c0 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -109,6 +109,8 @@ func run(root, outDir string) error { "Status", "HappLinkResult", "ClientSlim", + "ClientNodeApplyResponse", + "ClientNodeApplyOutcome", "ClientRenewalPreviewRequest", "ClientRenewalPreview", "ClientPageResponse", @@ -117,6 +119,14 @@ func run(root, outDir string) error { "AttachSelectionResult", "BulkAdjustResult", "BulkAdjustReport", + "BulkAttachResult", + "BulkDetachResult", + "BulkCreateResult", + "BulkCreateReport", + "BulkDeleteResult", + "BulkDeleteReport", + "BulkSetEnableResult", + "BulkSetEnableReport", "BulkExternalLinksResult", "ExternalLinkInput", "ClientsSummary",