diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 99def0a71..5d00c7086 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -127,13 +127,24 @@ jobs: - name: PostgreSQL client IP sync regressions run: | set -o pipefail - go test -p=1 ./internal/web/service ./internal/web/job -run '^TestClientIpSyncPostgres(Scanner)?$' -count=1 -v | tee /tmp/postgres-client-ip-sync.log + go test -p=1 ./internal/web/service ./internal/web/job -run '^TestClientIpSyncPostgres(Scanner|Scheduler)?$' -count=1 -v | tee /tmp/postgres-client-ip-sync.log passed=$(grep -c -- '^--- PASS' /tmp/postgres-client-ip-sync.log || true) - if [ "$passed" -ne 2 ]; then - echo "expected 2 passing PostgreSQL client IP sync tests, got $passed" >&2 + if [ "$passed" -ne 3 ]; then + echo "expected 3 passing PostgreSQL client IP sync tests, got $passed" >&2 exit 1 fi + - name: PostgreSQL IP reporter lock order and lifecycle + run: | + set -o pipefail + go test ./internal/web/service -run '^TestPostgres(NodeIPReporterClientLockOrder|FlatIPReporterLifecycleCommit|PolledAttributionSurvivesConcurrentPrune)$' -count=1 -v | tee /tmp/postgres-ip-reporter-locks.log + for test in NodeIPReporterClientLockOrder FlatIPReporterLifecycleCommit PolledAttributionSurvivesConcurrentPrune; do + if ! grep -q -- "^--- PASS: TestPostgres${test} " /tmp/postgres-ip-reporter-locks.log; then + echo "expected PostgreSQL reporter test TestPostgres${test} to pass" >&2 + exit 1 + fi + done + - name: PostgreSQL Xray traffic retry run: | set -o pipefail @@ -144,6 +155,26 @@ jobs: exit 1 fi + - name: PostgreSQL node client push ordering + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(NodeClientMutationsCommitWhileAnEarlierPushIsBlocked|NodeClientQueueTimeoutDefersCommittedDelta|NodeClientCapacityPreservesPermanentDelete|NodeWideDeleteSkipsReattachmentSentByQueuedReconcile|NodeWideDeleteRetriesAfterQueueExpiry|BulkDeleteStopsPushingToAHungNode|ReconcileDoesNotOvertakeCommittedClientState|TrafficDepletionWaitsForEarlierNodeClientPush|Create(GroupsCompatibleInboundsOnOneRemote|SplitsFlowAndSendsResolvedInbounds|UsesEffectiveAllowedIPsOnRemote|DispatchesReadyLaneBeforeBlockedLane|CancellationStopsFurtherNodeWaves)|GroupedCreate(ReconcilesUnsentRebasedSettings|RecoversIndeterminateDelivery|RepairsDeferredTargets|DispatchesIndependentReadyPayload|OrdersLaterClientMutations|ReconcileBarrierDrainsAfterAcknowledgment|KeepsFifthNodeDurablyPendingWhenBudgetExpires|PreservesProtocolCredentials))$' -count=1 -v | tee /tmp/postgres-node-client-order.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-client-order.log || true) + if [ "$passed" -ne 21 ]; then + echo "expected 21 passing PostgreSQL node client ordering tests, got $passed" >&2 + exit 1 + fi + + - name: PostgreSQL client inbound read regressions + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(ClientCreate(ReadsInboundSettingsOnlyForMutation|ClearsFlowOnIneligibleInbound|PreservesSettingsBasedDefaults)|UpdateInboundClientReadsSettingsOnceBeforeCommit|Slim(Create(UsesLockedFlowForGroupedDelivery|HealthyTargetsProgressWithBlockedPeer|ProjectionPreservesNodeIDAndProtocolSettings)|AttachUsesLockedFlowAndPreservesRawAdd|UpdateRebasesConcurrentSettings))$' -count=1 -v | tee /tmp/postgres-client-inbound-reads.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-client-inbound-reads.log || true) + if [ "$passed" -ne 9 ]; then + echo "expected 9 passing PostgreSQL client inbound read tests, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL global-traffic heartbeat regressions run: | set -o pipefail @@ -204,6 +235,22 @@ jobs: exit 1 fi + - name: PostgreSQL node client reconciliation + run: | + set -o pipefail + go test ./internal/web/service -run '^Test(NodeFullReconciliation|NodeMerge(BatchesBaselinesForActiveClients|LetsSubscriptionTouchDuringClientReconciliationPostgres)$)' -count=1 -v | tee /tmp/postgres-node-client-reconciliation.log + passed=$(grep -c -- '^--- PASS: TestNodeFullReconciliation' /tmp/postgres-node-client-reconciliation.log || true) + if [ "$passed" -ne 4 ]; then + echo "expected 4 passing node client reconciliation tests, got $passed" >&2 + exit 1 + fi + for test in TestNodeMergeBatchesBaselinesForActiveClients TestNodeMergeLetsSubscriptionTouchDuringClientReconciliationPostgres; do + if ! grep -q -- "^--- PASS: $test " /tmp/postgres-node-client-reconciliation.log; then + echo "expected PostgreSQL regression to pass: $test" >&2 + exit 1 + fi + done + - name: PostgreSQL node counter reset regressions run: | set -o pipefail @@ -214,6 +261,16 @@ jobs: exit 1 fi + - name: PostgreSQL node merge contention + run: | + set -o pipefail + go test ./internal/web/service -run '^TestNodeMerge(LetsSubscriptionTouchDuringClientReconciliationPostgres|BatchesBaselinesForActiveClients)$' -count=1 -v | tee /tmp/postgres-node-merge-contention.log + passed=$(grep -c -- '^--- PASS' /tmp/postgres-node-merge-contention.log || true) + if [ "$passed" -ne 2 ]; then + echo "expected both PostgreSQL node merge contention tests to pass, got $passed" >&2 + exit 1 + fi + - name: PostgreSQL schema and migration tests run: | set -o pipefail 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/config/reality.mdx b/docs/content/docs/en/config/reality.mdx index 2bd717076..06e1e3c05 100644 --- a/docs/content/docs/en/config/reality.mdx +++ b/docs/content/docs/en/config/reality.mdx @@ -139,6 +139,18 @@ vless://@:443?security=reality&pbk=&sid=&sni +### Import a REALITY subscription into Loon + +Import the raw subscription URL as a Loon remote proxy subscription. The panel +recognizes Loon's default User-Agent and serves its native format. If a custom +User-Agent is in use, add `?format=loon` to the URL (or `&format=loon` if it +already has query parameters). Use `format=raw` to request standard URIs in Loon. + +Eligible raw TCP VLESS REALITY nodes with the post-quantum hint use +`tls-profile=chrome147` and retain their server name, public key, short ID and +Vision flow. Other entries keep their share URIs. See the +[Loon node format](https://nsloon.app/en/docs/Node/) for client support. + ## Generate a config Use the generator below to create a fresh X25519 keypair, UUID, and short ID, diff --git a/docs/content/docs/en/help/troubleshooting.mdx b/docs/content/docs/en/help/troubleshooting.mdx index d9b72d373..014247621 100644 --- a/docs/content/docs/en/help/troubleshooting.mdx +++ b/docs/content/docs/en/help/troubleshooting.mdx @@ -13,6 +13,18 @@ A checklist for the most common issues. When in doubt, raise the log level - Make sure the **panel port isn't already in use** by another service. - Verify the database path is writable (default `/etc/x-ui/x-ui.db`). +## Panel restart takes too long + +The restart action acknowledges that a request was accepted. The service logs +successful completion once the panel and subscription listeners have both started. +A normal panel restart keeps the running Xray process. Each restart has a +75-second budget shared by both listener drains and the other shutdown and startup phases. + +If a phase fails or overruns that budget, the panel exits with an error so its +supervisor can restart it. This recovery can interrupt Xray sessions. On a +systemd installation, inspect `journalctl -u x-ui` for the phase and elapsed +time. Use a supervisor configured to restart the service after failures. + ## 502 / panel unreachable behind a proxy - Confirm the panel is actually listening on the upstream port (e.g. `2053`). 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/content/docs/fa/config/reality.mdx b/docs/content/docs/fa/config/reality.mdx index 87d006845..b6fcc21b9 100644 --- a/docs/content/docs/fa/config/reality.mdx +++ b/docs/content/docs/fa/config/reality.mdx @@ -152,6 +152,20 @@ vless://@:443?security=reality&pbk=&sid=&sni +### وارد کردن اشتراک REALITY در Loon + +URL خام اشتراک را به‌عنوان اشتراک پروکسی راه‌دور (Remote Proxy) در Loon وارد +کنید. پنل User-Agent پیش‌فرض Loon را تشخیص می‌دهد و قالب بومی آن را ارائه +می‌کند. اگر User-Agent سفارشی در کار است، `?format=loon` را به URL اضافه کنید +(یا `&format=loon` اگر URL از قبل پارامتر کوئری دارد). برای دریافت URIهای +استاندارد در Loon از `format=raw` استفاده کنید. + +گره‌های واجد شرایط VLESS REALITY روی TCP خام که راهنمای پساکوانتومی را دارند از +`tls-profile=chrome147` استفاده می‌کنند و نام سرور، کلید عمومی، short ID و جریان +Vision خود را حفظ می‌کنند. سایر ورودی‌ها همان URI اشتراک‌گذاری خود را نگه +می‌دارند. برای پشتیبانی کلاینت، +[قالب گره‌ی Loon](https://nsloon.app/en/docs/Node/) را ببینید. + ## تولید یک پیکربندی از تولیدکننده‌ی زیر برای ساخت یک جفت‌کلید تازه‌ی X25519، UUID و short ID استفاده diff --git a/docs/content/docs/ru/config/reality.mdx b/docs/content/docs/ru/config/reality.mdx index ea364fe47..89a3a0fca 100644 --- a/docs/content/docs/ru/config/reality.mdx +++ b/docs/content/docs/ru/config/reality.mdx @@ -144,6 +144,19 @@ vless://@:443?security=reality&pbk=&sid=&sni +### Импорт подписки REALITY в Loon + +Импортируйте исходный URL подписки в Loon как удалённую подписку на прокси. +Панель распознаёт User-Agent Loon по умолчанию и отдаёт его собственный формат. +Если используется свой User-Agent, добавьте к URL `?format=loon` (или +`&format=loon`, если в нём уже есть параметры запроса). Чтобы получить в Loon +стандартные URI, используйте `format=raw`. + +Подходящие узлы VLESS REALITY на обычном TCP с постквантовой подсказкой получают +`tls-profile=chrome147` и сохраняют имя сервера, открытый ключ, short ID и поток +Vision. Остальные записи остаются ссылками для подключения. О поддержке в +клиенте см. [формат узлов Loon](https://nsloon.app/en/docs/Node/). + ## Сгенерируйте конфигурацию Используйте генератор ниже, чтобы создать новую пару ключей X25519, UUID и short diff --git a/docs/content/docs/zh/config/reality.mdx b/docs/content/docs/zh/config/reality.mdx index 33e779aa9..031569be7 100644 --- a/docs/content/docs/zh/config/reality.mdx +++ b/docs/content/docs/zh/config/reality.mdx @@ -110,6 +110,12 @@ vless://@:443?security=reality&pbk=&sid=&sni +### 将 REALITY 订阅导入 Loon + +将原始订阅 URL 作为远程代理订阅导入 Loon。面板会识别 Loon 的默认 User-Agent 并返回其原生格式。如果使用了自定义 User-Agent,请在 URL 后添加 `?format=loon`(若已有查询参数则添加 `&format=loon`)。如需在 Loon 中获取标准 URI,请使用 `format=raw`。 + +带有后量子提示、符合条件的原始 TCP VLESS REALITY 节点会使用 `tls-profile=chrome147`,并保留其 server name、公钥、short ID 和 Vision 流控。其他条目仍保持为分享链接。客户端支持情况请参阅 [Loon 节点格式](https://nsloon.app/en/docs/Node/)。 + ## 生成配置 使用下面的生成器创建一对全新的 X25519 密钥、UUID 和 short ID,然后复制服务器入站 JSON 和客户端分享链接。 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/api/websocketBridge.ts b/frontend/src/api/websocketBridge.ts index 9394398c8..b475a20a0 100644 --- a/frontend/src/api/websocketBridge.ts +++ b/frontend/src/api/websocketBridge.ts @@ -7,26 +7,27 @@ import { isRecentLocalInvalidate } from '@/api/invalidationTracker'; type Handler = (payload: unknown) => void; -let invalidateTimer: number | null = null; - export function useWebSocketBridge() { const queryClient = useQueryClient(); useEffect(() => { const client = getSharedWebSocketClient(); + const pendingInvalidations = new Set<'inbounds' | 'clients'>(); + let invalidateTimer: number | undefined; const onInvalidate: Handler = (payload) => { const p = payload as { type?: string } | undefined; if (!p || (p.type !== 'inbounds' && p.type !== 'clients')) return; - if (invalidateTimer != null) clearTimeout(invalidateTimer); + pendingInvalidations.add(p.type); + if (invalidateTimer !== undefined) return; invalidateTimer = window.setTimeout(() => { - invalidateTimer = null; - if (isRecentLocalInvalidate()) return; - if (p.type === 'inbounds') { - queryClient.invalidateQueries({ queryKey: ['inbounds'] }); - } else { - queryClient.invalidateQueries({ queryKey: ['clients'] }); + invalidateTimer = undefined; + if (!isRecentLocalInvalidate()) { + for (const type of pendingInvalidations) { + queryClient.invalidateQueries({ queryKey: keys[type].root() }); + } } + pendingInvalidations.clear(); }, 200); }; @@ -56,10 +57,7 @@ export function useWebSocketBridge() { client.off('outbounds', onOutbounds); client.off('nodes', onNodes); client.off('inbounds', onInbounds); - if (invalidateTimer != null) { - clearTimeout(invalidateTimer); - invalidateTimer = null; - } + clearTimeout(invalidateTimer); }; }, [queryClient]); } 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/test/websocket-bridge-inbounds.test.tsx b/frontend/src/test/websocket-bridge-inbounds.test.tsx new file mode 100644 index 000000000..2849f27af --- /dev/null +++ b/frontend/src/test/websocket-bridge-inbounds.test.tsx @@ -0,0 +1,63 @@ +import { act, renderHook, waitFor } from '@testing-library/react'; +import { QueryClientProvider, useQuery } from '@tanstack/react-query'; +import type { ReactNode } from 'react'; +import { expect, it, vi } from 'vitest'; + +import { keys } from '@/api/queryKeys'; +import { getSharedWebSocketClient } from '@/api/websocket'; +import { useWebSocketBridge } from '@/api/websocketBridge'; + +import { makeTestQueryClient } from './test-utils'; + +it('refreshes inbounds and clients when a mutation invalidates both resources', async () => { + const sockets: EventTarget[] = []; + class FixtureSocket extends EventTarget { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + readyState = FixtureSocket.CONNECTING; + constructor() { + super(); + sockets.push(this); + } + close() {} + } + vi.stubGlobal('WebSocket', FixtureSocket); + const queryClient = makeTestQueryClient(); + let rows = [{ id: 1, remark: 'Before update' }]; + const fetchInbounds = vi.fn(async () => rows); + const fetchClients = vi.fn(async () => []); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const { result, unmount } = renderHook( + () => { + useWebSocketBridge(); + useQuery({ queryKey: keys.clients.all(), queryFn: fetchClients }); + return useQuery({ queryKey: keys.inbounds.slim(), queryFn: fetchInbounds }); + }, + { wrapper }, + ); + + try { + await waitFor(() => expect(result.current.data).toEqual(rows)); + const [connected] = sockets; + if (!connected) throw new Error('WebSocket was not connected'); + rows = [{ id: 1, remark: 'After update' }]; + act(() => { + for (const type of ['inbounds', 'inbounds', 'clients']) { + connected.dispatchEvent( + new MessageEvent('message', { + data: JSON.stringify({ type: 'invalidate', payload: { type } }), + }), + ); + } + }); + await waitFor(() => expect(result.current.data).toEqual(rows)); + expect(fetchInbounds).toHaveBeenCalledTimes(2); + expect(fetchClients).toHaveBeenCalledTimes(2); + } finally { + unmount(); + getSharedWebSocketClient().disconnect(); + vi.unstubAllGlobals(); + } +}); 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/database/db.go b/internal/database/db.go index 666f737da..f5f530211 100644 --- a/internal/database/db.go +++ b/internal/database/db.go @@ -91,6 +91,7 @@ func allModels() []any { &model.NodeClientIp{}, &model.ClientGlobalTraffic{}, &model.NodePendingReset{}, + &model.NodePendingClientDelete{}, &model.OutboundSubscription{}, &model.SubBalancer{}, &model.TuicTrafficReceipt{}, diff --git a/internal/database/migrate_data.go b/internal/database/migrate_data.go index b9e840104..0f7bf68e8 100644 --- a/internal/database/migrate_data.go +++ b/internal/database/migrate_data.go @@ -8,6 +8,7 @@ import ( "os" "path" "reflect" + "slices" "strings" "time" @@ -59,6 +60,7 @@ func migrationModels() []any { &model.NodeClientIp{}, &model.ClientGlobalTraffic{}, &model.NodePendingReset{}, + &model.NodePendingClientDelete{}, &model.OutboundSubscription{}, &model.SubBalancer{}, &model.TuicTrafficReceipt{}, @@ -225,6 +227,16 @@ func copyTable(src, dst *gorm.DB, mdl any) (int, error) { } order := strings.Join(stmt.Schema.PrimaryFieldDBNames, ", ") table := stmt.Schema.Table + if _, optional := mdl.(*model.NodePendingClientDelete); optional { + // Backups predating the outbox have no pending deletes to copy. + tables, err := src.Migrator().GetTables() + if err != nil { + return 0, err + } + if !slices.Contains(tables, table) { + return 0, nil + } + } columns := stmt.Schema.DBNames ctx := context.Background() diff --git a/internal/database/migrate_data_test.go b/internal/database/migrate_data_test.go index 685463dd0..16d959a17 100644 --- a/internal/database/migrate_data_test.go +++ b/internal/database/migrate_data_test.go @@ -18,13 +18,16 @@ func TestMigrateData_CompositeKeyTableLargerThanBatch(t *testing.T) { t.Skip("set XUI_TEST_PG_DSN to a reachable Postgres to run this test") } - // Seed a SQLite source with the full schema and >500 client_inbounds rows. + // Seed a pre-outbox SQLite source with >500 client_inbounds rows. srcPath := t.TempDir() + "/x-ui.db" src, err := gorm.Open(sqlite.Open(srcPath), &gorm.Config{Logger: logger.Discard}) if err != nil { t.Fatalf("open sqlite: %v", err) } for _, m := range migrationModels() { + if _, pending := m.(*model.NodePendingClientDelete); pending { + continue + } if err := src.AutoMigrate(m); err != nil { t.Fatalf("automigrate %T: %v", m, err) } @@ -61,6 +64,9 @@ func TestMigrateData_CompositeKeyTableLargerThanBatch(t *testing.T) { if got != n { t.Fatalf("client_inbounds rows = %d, want %d", got, n) } + if err := dst.Model(&model.NodePendingClientDelete{}).Count(&got).Error; err != nil || got != 0 { + t.Fatalf("migrated pending delete rows = %d, want 0 (%v)", got, err) + } } func TestMigrateData_PreservesFalseDefaultedColumns(t *testing.T) { @@ -207,3 +213,41 @@ func TestMigrateData_FailedCopyLeavesDestinationUntouched(t *testing.T) { t.Fatalf("failed migration leaked partial rows: evil count = %d, want 0", evil) } } + +func TestCopyPendingClientDeletesAcceptsLegacySourceAndPreservesNewRows(t *testing.T) { + openDB := func(path string) *gorm.DB { + t.Helper() + db, err := gorm.Open(sqlite.Open(path), &gorm.Config{Logger: logger.Discard}) + if err != nil { + t.Fatal(err) + } + conn, err := db.DB() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = conn.Close() }) + return db + } + src := openDB(t.TempDir() + "/source.db") + dst := openDB(t.TempDir() + "/destination.db") + pending := &model.NodePendingClientDelete{NodeId: 1, Email: "pending@example.test", ClientId: 3, Generation: "queue-generation", LastAttemptAt: 17} + if err := dst.AutoMigrate(pending); err != nil { + t.Fatal(err) + } + if n, err := copyTable(src, dst, pending); err != nil || n != 0 { + t.Fatalf("copy from source without delete queue: %d rows, %v", n, err) + } + if err := src.AutoMigrate(pending); err != nil { + t.Fatal(err) + } + if err := src.Create(pending).Error; err != nil { + t.Fatal(err) + } + if n, err := copyTable(src, dst, pending); err != nil || n != 1 { + t.Fatalf("copy persisted delete queue: %d rows, %v", n, err) + } + var got model.NodePendingClientDelete + if err := dst.Take(&got).Error; err != nil || got != *pending { + t.Fatalf("copied delete intent = %+v, want %+v (%v)", got, pending, err) + } +} diff --git a/internal/database/model/node_pending_client_delete.go b/internal/database/model/node_pending_client_delete.go new file mode 100644 index 000000000..9d48cc53d --- /dev/null +++ b/internal/database/model/node_pending_client_delete.go @@ -0,0 +1,10 @@ +package model + +// NodePendingClientDelete tracks a permanent delete that the node has not confirmed. +type NodePendingClientDelete struct { + NodeId int `gorm:"primaryKey;autoIncrement:false;index:idx_node_delete_order,priority:1"` + Email string `gorm:"primaryKey;index:idx_node_delete_order,priority:3"` + ClientId int `gorm:"not null"` + Generation string `gorm:"not null"` + LastAttemptAt int64 `gorm:"not null;index:idx_node_delete_order,priority:2"` +} diff --git a/internal/nodee2e/harness_test.go b/internal/nodee2e/harness_test.go index 8b9101efa..09c65a619 100644 --- a/internal/nodee2e/harness_test.go +++ b/internal/nodee2e/harness_test.go @@ -16,6 +16,7 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" "time" @@ -49,14 +50,31 @@ type panel struct { logOut *os.File } +// The fixture processes bind after their databases have been prepared. Keep +// each assignment unique for the run and below the default ephemeral range on +// CI, where outbound HTTP connections could otherwise take the same port. +var fixturePortOffset atomic.Uint32 + func freePort(t *testing.T) int { t.Helper() - l, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - t.Fatalf("free port: %v", err) + var lastErr error + for range 64 { + port := 19999 + int(fixturePortOffset.Add(1)) + if port > 29999 { + t.Fatal("exhausted node fixture ports") + } + listener, err := net.Listen("tcp", ":"+strconv.Itoa(port)) + if err != nil { + lastErr = err + continue + } + if err := listener.Close(); err != nil { + t.Fatalf("release fixture port %d: %v", port, err) + } + return port } - defer l.Close() - return l.Addr().(*net.TCPAddr).Port + t.Fatalf("no available node fixture port: %v", lastErr) + return 0 } func (p *panel) env() []string { diff --git a/internal/nodee2e/node_snapshot_test.go b/internal/nodee2e/node_snapshot_test.go index 6cf4f7388..dcdbf55cf 100644 --- a/internal/nodee2e/node_snapshot_test.go +++ b/internal/nodee2e/node_snapshot_test.go @@ -3,6 +3,7 @@ package nodee2e import ( "bytes" "compress/gzip" + "context" "encoding/json" "fmt" "io" @@ -11,9 +12,14 @@ import ( "net/http/httputil" "net/url" "os" + "slices" "strconv" "sync/atomic" "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" ) func TestNodeSnapshotVersionCompatibility(t *testing.T) { @@ -39,7 +45,7 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { token := node.mintToken("snapshot-link", "node-sync") master.start() node.start() - var lists, compact, full, unchanged atomic.Int32 + var lists, compact, full, unchanged, clientAdds atomic.Int32 target, err := url.Parse(node.url()) if err != nil { t.Fatal(err) @@ -88,6 +94,8 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { lists.Add(1) case "/panel/api/inbounds/trafficSnapshot": compact.Add(1) + case "/panel/api/clients/add": + clientAdds.Add(1) } proxy.ServeHTTP(w, req) })) @@ -101,10 +109,14 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { t.Fatal(err) } inboundPort := freePort(t) + secondaryPort := freePort(t) var source inboundView if err := json.Unmarshal(node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix", inboundPort, nil, vlessClient("matrix-first"))), &source); err != nil { t.Fatal(err) } + if version.master == current { + node.call(http.MethodPost, "/panel/api/inbounds/add", vlessInbound("matrix-secondary", secondaryPort, nil)) + } master.call(http.MethodPost, "/panel/api/nodes/add", map[string]any{"name": "matrix-node", "scheme": "http", "address": address.Hostname(), "port": port, "basePath": "/", "apiToken": token, "enable": true, "allowPrivateAddress": true}) eventually(t, settleTimeout, "version pair synchronizes and reaches steady state", func() (bool, string) { ib, ok := master.inboundOnPort(inboundPort) @@ -136,6 +148,50 @@ func TestNodeSnapshotVersionCompatibility(t *testing.T) { master.start() eventually(t, settleTimeout, "master restart reacquires complete structure", func() (bool, string) { return full.Load() > before, fmt.Sprint(full.Load()) }) } + if version.master == current { + first, hasFirst := master.inboundOnPort(inboundPort) + second, hasSecond := master.inboundOnPort(secondaryPort) + if !hasFirst || !hasSecond { + t.Fatal("master did not adopt both inbounds") + } + const email = "matrix-shared-create" + master.call(http.MethodPost, "/panel/api/clients/add", map[string]any{ + "client": map[string]any{"email": email, "enable": true}, "inboundIds": []int{first.Id, second.Id}, + }) + if got := clientAdds.Load(); got != 1 { + t.Fatalf("node-sync received %d add requests, want one", got) + } + var tags []string + for _, port := range []int{inboundPort, secondaryPort} { + if ib, ok := node.inboundOnPort(port); !ok || ib.client(email) == nil { + t.Fatalf("node did not apply the grouped client on port %d", port) + } else { + tags = append(tags, ib.Tag) + } + } + admin := runtime.NewRemote(&model.Node{ + Name: "matrix-admin", Scheme: "http", Address: address.Hostname(), Port: port, + BasePath: "/", ApiToken: node.token, Enable: true, AllowPrivateAddress: true, + }, nil) + const adminEmail = "matrix-admin-create" + raw, err := json.Marshal(vlessClient(adminEmail)) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + if _, ack, err := admin.AddClientGroup(ctx, tags, raw); err != nil || !slices.Equal(ack, []bool{true, true}) { + t.Fatalf("admin grouped add acknowledged %v, err=%v", ack, err) + } + if got := clientAdds.Load(); got != 2 { + t.Fatalf("admin sent %d add requests, want one", got-1) + } + for _, port := range []int{inboundPort, secondaryPort} { + if ib, ok := node.inboundOnPort(port); !ok || ib.client(adminEmail) == nil { + t.Fatalf("admin grouped client absent on port %d", port) + } + } + } }) } } diff --git a/internal/sub/controller.go b/internal/sub/controller.go index ef155e99f..0a9af1fba 100644 --- a/internal/sub/controller.go +++ b/internal/sub/controller.go @@ -506,18 +506,22 @@ func dedupeEmails(emails []string) []string { // subs handles HTTP requests for subscription links, returning either HTML page or base64-encoded subscription data. func (a *SUBController) subs(c *gin.Context) { userAgent := c.GetHeader("User-Agent") + requestedFormat := c.Query("format") + loon := strings.EqualFold(requestedFormat, "loon") || + requestedFormat == "" && strings.HasPrefix(strings.ToLower(userAgent), "loon/") + c.Writer.Header().Add("Vary", "User-Agent") if a.maybeServeSubInfo(c) { logSubscriptionRoute(userAgent, "info") return } - if a.maybeServeSubPage(c, subPageFormatRaw) { + if !loon && a.maybeServeSubPage(c, subPageFormatRaw) { logSubscriptionRoute(userAgent, "html") return } format := hwidLinks - if shouldAutoServeClash(a.subClashAutoDetect, a.clashEnabled, false, userAgent, a.clashUserAgent) { + if !loon && shouldAutoServeClash(a.subClashAutoDetect, a.clashEnabled, false, userAgent, a.clashUserAgent) { format = hwidClash - } else if shouldAutoServeJson(a.jsonAutoDetect, a.jsonEnabled, false, userAgent, a.jsonUserAgent) { + } else if !loon && shouldAutoServeJson(a.jsonAutoDetect, a.jsonEnabled, false, userAgent, a.jsonUserAgent) { format = hwidJSONArray } if !a.enforceHwid(c, format) { @@ -528,12 +532,16 @@ func (a *SUBController) subs(c *gin.Context) { logSubscriptionRoute(userAgent, "clash") return } - if shouldAutoServeJson(a.jsonAutoDetect, a.jsonEnabled, false, userAgent, a.jsonUserAgent) && a.serveJsonBody(c, true, "application/json; charset=utf-8", false) { + if !loon && shouldAutoServeJson(a.jsonAutoDetect, a.jsonEnabled, false, userAgent, a.jsonUserAgent) && a.serveJsonBody(c, true, "application/json; charset=utf-8", false) { a.recordSubscriptionFetch(c) logSubscriptionRoute(userAgent, "json") return } - logSubscriptionRoute(userAgent, "raw") + if loon { + logSubscriptionRoute(userAgent, "loon") + } else { + logSubscriptionRoute(userAgent, "raw") + } subId := c.Param("subid") scheme, host, hostWithPort, _ := a.subService.ResolveRequest(c) subReq := a.subService.ForRequest(host) @@ -546,9 +554,13 @@ func (a *SUBController) subs(c *gin.Context) { writeSubError(c, err) } else { var result strings.Builder - for _, sub := range subs { - result.WriteString(sub) - result.WriteString("\n") + if loon { + result.WriteString(loonSubscription(subs)) + } else { + for _, sub := range subs { + result.WriteString(sub) + result.WriteByte('\n') + } } // Add headers @@ -557,7 +569,7 @@ func (a *SUBController) subs(c *gin.Context) { a.ApplyCommonHeaders(c, header, a.updateInterval, metadata.Title, metadata.SupportURL, metadata.ProfileURL, metadata.Announce, a.subEnableRouting, a.subRoutingRules, a.subHideSettings) // Incy's profile rides the raw body; other clients must not see that line (#6062). - if IsIncyClient(userAgent) && a.subIncyEnableRouting && a.subIncyRoutingRules != "" { + if !loon && IsIncyClient(userAgent) && a.subIncyEnableRouting && a.subIncyRoutingRules != "" { incyRules, _, err := resolveIncyRoutingSource(a.subIncyRoutingRules) if err == nil && strings.TrimSpace(incyRules) != "" { result.WriteString(incyRules) diff --git a/internal/sub/loon.go b/internal/sub/loon.go new file mode 100644 index 000000000..29b229bc7 --- /dev/null +++ b/internal/sub/loon.go @@ -0,0 +1,90 @@ +package sub + +import ( + "fmt" + "net/url" + "strconv" + "strings" + "unicode" + + "github.com/google/uuid" +) + +// loonSubscription keeps existing URI entries and renders eligible REALITY TCP nodes in Loon's native format. +func loonSubscription(links []string) string { + var out strings.Builder + out.WriteString("[Proxy]\n") + usedNames := make(map[string]bool) + for _, linksForClient := range links { + for line := range strings.SplitSeq(linksForClient, "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + name, node, ok := loonRealityNode(line) + if ok { + base := name + for suffix := 2; usedNames[name]; suffix++ { + name = base + " (" + strconv.Itoa(suffix) + ")" + } + usedNames[name] = true + line = name + " = " + node + } + out.WriteString(line) + out.WriteByte('\n') + } + } + return out.String() +} + +func loonRealityNode(raw string) (name, node string, ok bool) { + u, err := url.Parse(raw) + if err != nil || u.Scheme != "vless" || u.User == nil { + return "", "", false + } + q := u.Query() + switch q.Get("type") { + case "", "raw", "tcp": + default: + return "", "", false + } + if q.Get("security") != "reality" || q.Get("support-x25519mlkem768") != "true" || + q.Get("pqv") != "" || (q.Get("encryption") != "" && q.Get("encryption") != "none") || + (q.Get("headerType") != "" && q.Get("headerType") != "none") { + return "", "", false + } + host, key, serverName, shortID, flow := u.Hostname(), q.Get("pbk"), q.Get("sni"), q.Get("sid"), q.Get("flow") + port, portErr := strconv.ParseUint(u.Port(), 10, 16) + id, idErr := uuid.Parse(u.User.Username()) + if portErr != nil || port == 0 || idErr != nil || host == "" || key == "" || + (flow != "" && flow != "xtls-rprx-vision" && flow != "xtls-rprx-vision-udp443") { + return "", "", false + } + for _, value := range []string{host, key, serverName, shortID} { + if strings.ContainsAny(value, ",=\"\\[]#") || strings.ContainsFunc(value, func(r rune) bool { + return unicode.IsControl(r) || unicode.IsSpace(r) + }) { + return "", "", false + } + } + name = strings.TrimSpace(strings.Map(func(r rune) rune { + if unicode.IsControl(r) || strings.ContainsRune("=,[]#\"", r) { + return ' ' + } + return r + }, u.Fragment)) + if name == "" { + name = host + } + node = fmt.Sprintf("VLESS,%s,%d,%q,transport=tcp,over-tls=true,public-key=%q,tls-profile=chrome147", host, port, id.String(), key) + if shortID != "" { + node += ",short-id=" + shortID + } + if serverName != "" { + node += ",sni=" + serverName + } + if flow != "" { + node += ",flow=" + flow + } + return name, node, true +} diff --git a/internal/sub/loon_test.go b/internal/sub/loon_test.go new file mode 100644 index 000000000..6e5167491 --- /dev/null +++ b/internal/sub/loon_test.go @@ -0,0 +1,59 @@ +package sub + +import ( + "encoding/base64" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" +) + +func TestLoonSubscriptionUsesChrome147ForPostQuantumReality(t *testing.T) { + seedSubDB(t) + seedSubInbound(t, "loon-profile", "reality", 8443, 1, `{ + "network":"tcp","security":"reality", + "realitySettings":{"serverNames":["backend.example.test"],"shortIds":["ab12cd"], + "settings":{"publicKey":"TEST-public-key","fingerprint":"chrome"}} + }`) + seedSubInbound(t, "loon-profile", "tls", 9443, 2, `{"network":"tcp","security":"tls"}`) + gin.SetMode(gin.TestMode) + router := newSubscriptionTestRouter(subscriptionTestRouterConfig{clashAutoDetect: true}) + fetch := func(query, client string) string { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "http://sub.example.test/sub/loon-profile"+query, nil) + req.Header.Set("User-Agent", client) + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("subscription response status = %d", rec.Code) + } + if rec.Header().Get("Subscription-Userinfo") == "" { + t.Fatal("usage header was lost") + } + body, err := base64.StdEncoding.DecodeString(rec.Body.String()) + if err != nil { + t.Fatalf("decode subscription: %v", err) + } + return string(body) + } + raw := fetch("", "Generic/1.0") + if strings.Contains(raw, "tls-profile=") || !strings.Contains(raw, "fp=chrome") { + t.Fatal("default raw VLESS subscription changed") + } + const loonAgent = "Loon/991 CFNetwork/3896.100.1.1.1 Darwin/27.0.0" + loon := fetch("?format=loon", "Mihomo/1.19") + if auto := fetch("", loonAgent); auto != loon { + t.Fatal("Loon's default subscription URL differs from the explicit Loon format") + } + if explicitRaw := fetch("?format=raw", loonAgent); explicitRaw != raw { + t.Fatal("explicit raw format for Loon does not retain the normal share URIs") + } + if !strings.HasPrefix(loon, "[Proxy]\n") || !strings.Contains(loon, "= VLESS,203.0.113.5,8443,") || + !strings.Contains(loon, `public-key="TEST-public-key"`) || !strings.Contains(loon, "short-id=ab12cd") || + !strings.Contains(loon, "sni=backend.example.test") || !strings.Contains(loon, "tls-profile=chrome147") || + !strings.Contains(loon, "vless://") { + t.Fatalf("Loon subscription lacks the native REALITY node or the unchanged TLS entry: %s", loon) + } +} diff --git a/internal/sub/sub.go b/internal/sub/sub.go index 64821c886..a2d1f4066 100644 --- a/internal/sub/sub.go +++ b/internal/sub/sub.go @@ -5,6 +5,7 @@ package sub import ( "context" "crypto/tls" + "errors" "io" "io/fs" "net" @@ -485,6 +486,13 @@ func (s *Server) Start() (err error) { // Stop gracefully shuts down the subscription server and closes the listener. func (s *Server) Stop() error { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return s.StopWithContext(ctx) +} + +// StopWithContext drains subscription HTTP connections within the caller's deadline. +func (s *Server) StopWithContext(ctx context.Context) error { s.cancel() if s.sub != nil { s.sub.Close() @@ -493,12 +501,13 @@ func (s *Server) Stop() error { var err1 error var err2 error if s.httpServer != nil { - shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) - defer shutdownCancel() - err1 = s.httpServer.Shutdown(shutdownCtx) + err1 = s.httpServer.Shutdown(ctx) } if s.listener != nil { err2 = s.listener.Close() + if errors.Is(err2, net.ErrClosed) { + err2 = nil + } } return common.Combine(err1, err2) } diff --git a/internal/util/wirecodec/wirecodec.go b/internal/util/wirecodec/wirecodec.go index 9f1ef8458..5d7df1d70 100644 --- a/internal/util/wirecodec/wirecodec.go +++ b/internal/util/wirecodec/wirecodec.go @@ -4,6 +4,7 @@ package wirecodec import ( + "context" "crypto/sha256" "encoding/hex" "errors" @@ -39,22 +40,53 @@ const ( // maxDecodeBytes bounds in-memory decompression to defuse a zstd bomb from // an (authenticated) node-API caller. maxDecodeBytes = 16 << 20 + + // Node requests reuse a small history and keep a fixed upper bound on + // retained encoder workspaces, even on a master with many CPUs. + encoderWindow = 1 << 20 + maxEncoderWorkers = 4 ) // EncodeAll/DecodeAll on these shared instances are safe for concurrent use. var ( - decoderWorkers = runtime.GOMAXPROCS(0) - zstdEncoder, _ = zstd.NewWriter(nil) - zstdDecoder, _ = zstd.NewReader(nil, zstd.WithDecoderMaxMemory(maxDecodeBytes), + zstdEncoder, encoderWorkers = newEncoder(runtime.GOMAXPROCS(0)) + encoderSlots = make(chan struct{}, encoderWorkers) + decoderWorkers = runtime.GOMAXPROCS(0) + zstdDecoder, _ = zstd.NewReader(nil, zstd.WithDecoderMaxMemory(maxDecodeBytes), zstd.WithDecodeAllCapLimit(true), zstd.WithDecoderConcurrency(decoderWorkers)) // decodeSlots keeps callers waiting for a decoder worker from each holding an output buffer. decodeSlots = make(chan struct{}, decoderWorkers) errDecodedTooLarge = errors.New("wirecodec: decompressed body exceeds limit") ) +// newEncoder builds the envelope encoder for a host with cpus CPUs and reports +// how many workspaces it pools; they are never freed, hence the cap (#7274). +func newEncoder(cpus int) (*zstd.Encoder, int) { + workers := min(maxEncoderWorkers, cpus) + enc, _ := zstd.NewWriter(nil, zstd.WithWindowSize(encoderWindow), + zstd.WithEncoderConcurrency(workers), zstd.WithLowerEncoderMem(true)) + return enc, workers +} + // Compress zstd-compresses b. func Compress(b []byte) []byte { - return zstdEncoder.EncodeAll(b, nil) + out, _ := CompressContext(context.Background(), b) + return out +} + +// CompressContext lets a caller cancel while waiting for an encoder. Once +// EncodeAll starts it runs synchronously. +func CompressContext(ctx context.Context, b []byte) ([]byte, error) { + select { + case encoderSlots <- struct{}{}: + case <-ctx.Done(): + return nil, ctx.Err() + } + defer func() { <-encoderSlots }() + if err := ctx.Err(); err != nil { + return nil, err + } + return zstdEncoder.EncodeAll(b, nil), nil } // Decompress zstd-decompresses src, rejecting output larger than maxOut (and any diff --git a/internal/util/wirecodec/wirecodec_test.go b/internal/util/wirecodec/wirecodec_test.go index 08ad22b30..a34f0fd3f 100644 --- a/internal/util/wirecodec/wirecodec_test.go +++ b/internal/util/wirecodec/wirecodec_test.go @@ -2,9 +2,16 @@ package wirecodec import ( "bytes" + "context" + "errors" + "fmt" "runtime" "strings" + "sync" "testing" + "time" + + "github.com/klauspost/compress/zstd" ) func TestCompressRoundTrip(t *testing.T) { @@ -64,3 +71,107 @@ func TestDecompressOfManyFramesAllocatesTheOutputOnce(t *testing.T) { t.Fatalf("decoding %d bytes of frames allocated %d MiB", len(src), allocated>>20) } } + +// The encoder keeps every workspace it has used for the life of the process, so +// their total must not grow with the master's CPU count (#7274). +func TestEncoderWorkspacesStayWithinBudgetOnAManyCoreHost(t *testing.T) { + const cpus, budget = 64, 12 << 20 + payload := bytes.Repeat([]byte("synthetic client traffic row "), 20_000) + enc, _ := newEncoder(cpus) + defer enc.Close() + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + // EncodeAll hands the workspaces out in rotation, so sequential calls warm each one. + for range 2 * cpus { + enc.EncodeAll(payload, nil) + } + runtime.GC() + runtime.ReadMemStats(&after) + if retained := int64(after.HeapAlloc) - int64(before.HeapAlloc); retained > budget { + t.Fatalf("encoder for %d CPUs retains %.1f MiB after use, want at most %d MiB", + cpus, float64(retained)/(1<<20), budget>>20) + } +} + +func TestCompressBoundsFrameWindow(t *testing.T) { + orig := bytes.Repeat([]byte("synthetic node configuration"), 150_000) + packed := Compress(orig) + var header zstd.Header + if err := header.Decode(packed); err != nil { + t.Fatal(err) + } + window := header.WindowSize + if header.SingleSegment { + window = header.FrameContentSize + } + if window > 1<<20 { + t.Fatalf("zstd frame needs %d bytes of window, want at most 1 MiB", window) + } +} + +func TestCompressConcurrentFramesAreCompatible(t *testing.T) { + decoder, err := zstd.NewReader(nil, zstd.WithDecoderConcurrency(1)) + if err != nil { + t.Fatal(err) + } + defer decoder.Close() + var callers sync.WaitGroup + for i := range 16 { + callers.Go(func() { + raw := bytes.Repeat(fmt.Appendf(nil, "client-%d", i), 40_000) + packed, err := CompressContext(t.Context(), raw) + if err != nil { + t.Errorf("encode %d: %v", i, err) + return + } + got, err := decoder.DecodeAll(packed, nil) + if err != nil || !bytes.Equal(got, raw) { + t.Errorf("decode frame %d with the default decoder: %v", i, err) + } + }) + } + callers.Wait() + + encoder, err := zstd.NewWriter(nil, zstd.WithEncoderConcurrency(1)) + if err != nil { + t.Fatal(err) + } + defer encoder.Close() + raw := bytes.Repeat([]byte("legacy envelope"), 300_000) + decoded, err := Decompress(encoder.EncodeAll(raw, nil), len(raw)) + if err != nil || !bytes.Equal(decoded, raw) { + t.Fatalf("decode frame with the legacy default window: %v", err) + } +} + +func TestCompressCancelsWhileWaitingForAnEncoder(t *testing.T) { + for range cap(encoderSlots) { + encoderSlots <- struct{}{} + } + defer func() { + for range cap(encoderSlots) { + <-encoderSlots + } + }() + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + called := make(chan struct{}) + result := make(chan error, 1) + go func() { + close(called) + _, err := CompressContext(ctx, []byte("waiting for a slot")) + result <- err + }() + <-called + cancel() + select { + case err := <-result: + if !errors.Is(err, context.Canceled) { + t.Fatalf("compression returned %v, want context.Canceled", err) + } + case <-time.After(time.Second): + t.Fatal("compression waited for a slot after cancellation") + } +} diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go index 9380e28df..b2b5c43d7 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.CreateWithContext(c.Request.Context(), &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/inbound.go b/internal/web/controller/inbound.go index ad4020ddf..f89aea5bb 100644 --- a/internal/web/controller/inbound.go +++ b/internal/web/controller/inbound.go @@ -39,18 +39,22 @@ func NewInboundController(g *gin.RouterGroup) *InboundController { // Mirrors the same heuristic used by the periodic traffic job. const broadcastInboundsUpdateClientLimit = 5000 -// broadcastInboundsUpdate fetches and broadcasts the inbound list for userId. -// At scale (10k+ clients) the marshaled JSON exceeds the WS payload ceiling, -// so we send an invalidate signal instead — frontend re-fetches via REST. -// Skipped entirely when no WebSocket clients are connected. +// broadcastInboundsUpdate sends either a small snapshot or an invalidate. +// Skip all snapshot work when no WebSocket clients are connected. func (a *InboundController) broadcastInboundsUpdate(userId int) { if !websocket.HasClients() { return } + overLimit, err := a.inboundService.InboundClientStatsOverLimit(userId, broadcastInboundsUpdateClientLimit) + if err != nil || overLimit { + websocket.BroadcastInvalidate(websocket.MessageTypeInbounds) + return + } inbounds, err := a.inboundService.GetInbounds(userId) if err != nil { return } + // Stats can grow between the probe and the snapshot read. totalClients := 0 for _, ib := range inbounds { totalClients += len(ib.ClientStats) diff --git a/internal/web/controller/inbound_broadcast_test.go b/internal/web/controller/inbound_broadcast_test.go new file mode 100644 index 000000000..9587de484 --- /dev/null +++ b/internal/web/controller/inbound_broadcast_test.go @@ -0,0 +1,192 @@ +package controller + +import ( + "context" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/robfig/cron/v3" + "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/entity" + "github.com/mhsanaei/3x-ui/v3/internal/web/global" + "github.com/mhsanaei/3x-ui/v3/internal/web/session" + "github.com/mhsanaei/3x-ui/v3/internal/web/websocket" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +type inboundBroadcastServer struct{ hub *websocket.Hub } + +func (s inboundBroadcastServer) GetWSHub() any { return s.hub } +func (inboundBroadcastServer) GetCtx() context.Context { return context.Background() } +func (inboundBroadcastServer) GetCron() *cron.Cron { return nil } + +func TestInboundMutationSkipsSnapshotReadsAboveWebSocketCutoff(t *testing.T) { + dbtest.InitDB(t, filepath.Join(t.TempDir(), "panel.db")) + db := database.GetDB() + seed := func(userID, port, count int) model.Inbound { + t.Helper() + row := model.Inbound{UserId: userID, Port: port, Tag: fmt.Sprintf("in-%d", port), Protocol: model.VLESS, Settings: `{"clients":[],"decryption":"none"}`} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + stats := make([]xray.ClientTraffic, count) + for i := range stats { + stats[i] = xray.ClientTraffic{InboundId: row.Id, Email: fmt.Sprintf("client-%d-%d", port, i)} + } + if count > 0 { + if err := db.CreateInBatches(&stats, 100).Error; err != nil { + t.Fatal(err) + } + } + return row + } + const limit = broadcastInboundsUpdateClientLimit + owned := seed(1, 29100, limit-1) + sibling := seed(1, 29101, 0) + seed(2, 29102, limit+1) + attach := func(inbound model.Inbound, statsIndex int) { + t.Helper() + row := model.ClientRecord{Email: fmt.Sprintf("client-%d-%d", owned.Port, statsIndex)} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + link := model.ClientInbound{ClientId: row.Id, InboundId: inbound.Id} + if err := db.Create(&link).Error; err != nil { + t.Fatal(err) + } + } + attach(sibling, 0) + attach(owned, 1) + + snapshotReads, probes := 0, 0 + if err := db.Callback().Query().After("gorm:query").Register("test:inbound_snapshot", func(tx *gorm.DB) { + sql := tx.Statement.SQL.String() + if _, ok := tx.Statement.Dest.(*[]*model.Inbound); ok && + strings.Contains(sql, "WHERE user_id =") && strings.HasSuffix(sql, "ORDER BY id ASC") { + snapshotReads++ + } + }); err != nil { + t.Fatal(err) + } + if err := db.Callback().Row().After("gorm:row").Register("test:inbound_stats_probe", func(tx *gorm.DB) { + if strings.Contains(tx.Statement.SQL.String(), "AS candidate_stats") { + probes++ + } + }); err != nil { + t.Fatal(err) + } + + router := gin.New() + group := router.Group("/panel/api/inbounds", func(c *gin.Context) { + session.SetAPIAuthUser(c, &model.User{Id: 1}) + }) + NewInboundController(group) + previous := global.GetWebServer() + t.Cleanup(func() { global.SetWebServer(previous) }) + + for i, tc := range []struct { + name string + ws bool + wantType websocket.MessageType + reads int + prepare func() + }{ + {name: "no subscribers"}, + {name: "at cutoff with shared traffic and unrelated user", ws: true, wantType: websocket.MessageTypeInbounds, reads: 1}, + {name: "above cutoff from sibling counter", ws: true, wantType: websocket.MessageTypeInvalidate, prepare: func() { attach(sibling, 2) }}, + {name: "above cutoff from direct traffic", ws: true, wantType: websocket.MessageTypeInvalidate, prepare: func() { seed(1, 29110, 2) }}, + } { + t.Run(tc.name, func(t *testing.T) { + var subscriber *websocket.Client + if tc.ws { + hub := websocket.NewHub() + done := make(chan struct{}) + go func() { + defer close(done) + hub.Run() + }() + t.Cleanup(func() { hub.Stop(); <-done }) + global.SetWebServer(inboundBroadcastServer{hub}) + subscriber = websocket.NewClient("test") + hub.Register(subscriber) + for deadline := time.Now().Add(2 * time.Second); hub.GetClientCount() == 0; { + if time.Now().After(deadline) { + t.Fatal("subscriber did not register") + } + time.Sleep(time.Millisecond) + } + } else { + global.SetWebServer(nil) + } + if tc.prepare != nil { + tc.prepare() + } + snapshotReads, probes = 0, 0 + port := 29103 + i + body := fmt.Sprintf(`{"protocol":"vless","enable":false,"remark":"created","port":%d,"settings":"{\"clients\":[],\"decryption\":\"none\"}","streamSettings":"{\"network\":\"tcp\",\"security\":\"none\"}"}`, port) + req := httptest.NewRequest(http.MethodPost, "/panel/api/inbounds/add", strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + rec := httptest.NewRecorder() + router.ServeHTTP(rec, req) + var response entity.Msg + if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil || !response.Success { + t.Fatalf("add failed: %s (%v)", rec.Body, err) + } + if snapshotReads != tc.reads { + t.Errorf("full inbound snapshot reads = %d, want %d", snapshotReads, tc.reads) + } + wantProbes := 0 + if tc.ws { + wantProbes = 1 + } + if probes != wantProbes { + t.Errorf("snapshot size probes = %d, want %d", probes, wantProbes) + } + if subscriber == nil { + return + } + select { + case data := <-subscriber.Send: + var event struct { + Type websocket.MessageType + Payload json.RawMessage + } + if err := json.Unmarshal(data, &event); err != nil || event.Type != tc.wantType { + t.Fatalf("unexpected WebSocket type %q: %v, want %q", event.Type, err, tc.wantType) + } + if tc.wantType == websocket.MessageTypeInbounds { + var rows []model.Inbound + if err := json.Unmarshal(event.Payload, &rows); err != nil { + t.Fatal(err) + } + total, created := 0, false + for _, row := range rows { + if row.Port == 29102 { + t.Fatal("snapshot contains another user's inbound") + } + total += len(row.ClientStats) + created = created || row.Port == port + } + if !created || total != limit { + t.Fatalf("snapshot missing updated state: created=%t client stats=%d", created, total) + } + } else if string(event.Payload) != `{"type":"inbounds"}` { + t.Fatalf("unexpected invalidation payload %s", event.Payload) + } + case <-time.After(2 * time.Second): + t.Fatal("mutation did not publish an inbound event") + } + }) + } +} diff --git a/internal/web/controller/setting.go b/internal/web/controller/setting.go index ca5c25fad..977c86401 100644 --- a/internal/web/controller/setting.go +++ b/internal/web/controller/setting.go @@ -241,7 +241,7 @@ func (a *SettingController) restartPanel(c *gin.Context) { } answer.NextPort, _ = a.settingService.GetListenPort() err := a.panelService.RestartPanel(time.Second * 3) - jsonMsgObj(c, I18nWeb(c, "pages.settings.restartPanelSuccess"), answer, err) + jsonMsgObj(c, I18nWeb(c, "pages.settings.restartPanelAccepted"), answer, err) } // getDefaultXrayConfig retrieves the default Xray configuration. 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/global/global.go b/internal/web/global/global.go index 89bd52c1a..d8b229f75 100644 --- a/internal/web/global/global.go +++ b/internal/web/global/global.go @@ -10,6 +10,7 @@ import ( ) var ( + serverMu sync.RWMutex webServer WebServer subServer SubServer @@ -31,21 +32,29 @@ type SubServer interface { // SetWebServer sets the global web server instance. func SetWebServer(s WebServer) { + serverMu.Lock() + defer serverMu.Unlock() webServer = s } // GetWebServer returns the global web server instance. func GetWebServer() WebServer { + serverMu.RLock() + defer serverMu.RUnlock() return webServer } // SetSubServer sets the global subscription server instance. func SetSubServer(s SubServer) { + serverMu.Lock() + defer serverMu.Unlock() subServer = s } // GetSubServer returns the global subscription server instance. func GetSubServer() SubServer { + serverMu.RLock() + defer serverMu.RUnlock() return subServer } 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..6f62c81a6 100644 --- a/internal/web/job/node_traffic_sync_ip_push_test.go +++ b/internal/web/job/node_traffic_sync_ip_push_test.go @@ -5,6 +5,7 @@ import ( "fmt" "net/http" "net/http/httptest" + "os" "path/filepath" "slices" "strconv" @@ -14,11 +15,13 @@ import ( "time" "github.com/op/go-logging" + "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" xuilogger "github.com/mhsanaei/3x-ui/v3/internal/logger" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" "github.com/mhsanaei/3x-ui/v3/internal/web/service" ) @@ -76,7 +79,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}) { @@ -84,3 +90,257 @@ func TestNodeTrafficSyncPushesOnlyHostedClientIps(t *testing.T) { } } } + +func TestNodeTrafficSyncMergesFourOverlappingIPReports(t *testing.T) { + loggerInitOnce.Do(func() { xuilogger.InitLogger(logging.ERROR) }) + isolateIPPollDatabase(t) + dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.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) }) + db := database.GetDB() + + const email = "shared-ip@example.test" + const common = "198.51.100.1" + const size = 4 + const clientID = "00000001-0000-4000-8000-000000000000" + const subscriptionID = "shared-fixture" + settings := fmt.Sprintf(`{"clients":[{"email":%q,"id":%q,"subId":%q,"enable":true}],"decryption":"none"}`, email, clientID, subscriptionID) + now := time.Now().Unix() + arrived := make(chan int, size) + release := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + for i := range size { + guid := fmt.Sprintf("edge-%d", i) + port := 29500 + i + tag := fmt.Sprintf("in-%d", port) + entries := []model.ClientIpEntry{ + {IP: fmt.Sprintf("192.0.2.%d", i+1), Timestamp: now - int64(i)}, + {IP: common, Timestamp: now - int64(i)}, + } + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var obj any = []any{} + switch { + case strings.HasSuffix(r.URL.Path, "/inbounds/list"): + obj = []*model.Inbound{{Id: i + 1, Tag: tag, Port: port, Protocol: model.VLESS, Enable: true, Settings: settings}} + case strings.HasSuffix(r.URL.Path, "/server/clientIps") && r.Method == http.MethodGet: + encoded, _ := json.Marshal(entries) + obj = []model.InboundClientIps{{ClientEmail: email, Ips: string(encoded)}} + case strings.HasSuffix(r.URL.Path, "/clients/clientIpsByGuid"): + arrived <- i + select { + case <-release: + case <-r.Context().Done(): + return + } + obj = map[string]map[string][]model.ClientIpEntry{guid: {email: entries}, "unowned": {email: entries}} + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) + })) + t.Cleanup(server.Close) + host, rawPort, _ := strings.Cut(strings.TrimPrefix(server.URL, "http://"), ":") + httpPort, err := strconv.Atoi(rawPort) + if err != nil { + t.Fatal(err) + } + node := &model.Node{ + Name: guid, Guid: guid, Scheme: "http", Address: host, Port: httpPort, + BasePath: "/", ApiToken: "tok", Enable: true, Status: "online", AllowPrivateAddress: true, + } + if err := db.Create(node).Error; err != nil { + t.Fatal(err) + } + // A node is not allowed to claim a client attached only to another node. + // Establish the shared membership on the hub before any node reports it. + inbound := &model.Inbound{ + NodeID: &node.Id, UserId: 1, Port: port, Tag: tag, Protocol: model.VLESS, Enable: true, Settings: settings, + } + if err := db.Create(inbound).Error; err != nil { + t.Fatal(err) + } + if err := (&service.ClientService{}).SyncInbound(db, inbound.Id, []model.Client{ + {Email: email, ID: clientID, SubID: subscriptionID, Enable: true}, + }); err != nil { + t.Fatal(err) + } + } + + job := NewNodeTrafficSyncJob() + t.Cleanup(func() { unblock(); job.Close() }) + job.Run() + deadline := time.After(5 * time.Second) + for range size { + select { + case <-arrived: + case <-deadline: + t.Fatal("four independent polls did not reach the attribution endpoint together") + } + } + unblock() + job.workers.Wait() + + var flat model.InboundClientIps + if err := db.Where("client_email = ?", email).First(&flat).Error; err != nil { + t.Fatal(err) + } + var flatEntries []model.ClientIpEntry + if err := json.Unmarshal([]byte(flat.Ips), &flatEntries); err != nil { + t.Fatal(err) + } + wantFlat := map[string]int64{common: now} + for i := range size { + wantFlat[fmt.Sprintf("192.0.2.%d", i+1)] = now - int64(i) + } + for _, entry := range flatEntries { + if want, ok := wantFlat[entry.IP]; !ok || want != entry.Timestamp { + t.Fatalf("unexpected flat IP entry %+v (all entries %v, remaining expected %v)", entry, flatEntries, wantFlat) + } + delete(wantFlat, entry.IP) + } + if len(wantFlat) != 0 { + t.Fatalf("flat IP union missing %v", wantFlat) + } + tree, err := (&service.InboundService{}).GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + if len(tree) != size { + t.Fatalf("expected %d scoped GUIDs, got %+v", size, tree) + } + for i := range size { + entries := tree[fmt.Sprintf("edge-%d", i)][email] + want := fmt.Sprintf("192.0.2.%d", i+1) + if len(entries) != 2 || !slices.Contains(entries, model.ClientIpEntry{IP: want, Timestamp: now - int64(i)}) { + t.Fatalf("wrong attribution for edge %d: %+v", i, entries) + } + } +} + +func TestClientIpSyncPostgresScheduler(t *testing.T) { + if os.Getenv("XUI_DB_TYPE") != "postgres" || os.Getenv("XUI_DB_DSN") == "" { + t.Skip("requires PostgreSQL") + } + t.Run("overlapping reports", TestNodeTrafficSyncMergesFourOverlappingIPReports) + t.Run("obsolete reports", TestNodeTrafficSyncDropsObsoleteIPReport) +} + +func TestNodeTrafficSyncDropsObsoleteIPReport(t *testing.T) { + loggerInitOnce.Do(func() { xuilogger.InitLogger(logging.ERROR) }) + for _, stage := range []string{"disable during flat fetch", "disable during attribution fetch", "delete after attribution read"} { + t.Run(stage, func(t *testing.T) { + isolateIPPollDatabase(t) + dbtest.InitDB(t, filepath.Join(t.TempDir(), "x-ui.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) }) + db := database.GetDB() + + const email = "late-ip@example.test" + const tag = "in-29444" + const guid = "ip-reporter" + seen, release := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + now := time.Now().Unix() + entry := model.ClientIpEntry{IP: "192.0.2.40", Timestamp: now} + settings := fmt.Sprintf(`{"clients":[{"email":%q,"id":"00000001-0000-4000-8000-000000000000","enable":true}],"decryption":"none"}`, email) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var obj any = []any{} + switch { + case strings.HasSuffix(r.URL.Path, "/inbounds/list"): + obj = []*model.Inbound{{Id: 1, Tag: tag, Port: 29444, Protocol: model.VLESS, Enable: true, Settings: settings}} + case strings.HasSuffix(r.URL.Path, "/server/clientIps") && r.Method == http.MethodGet && stage == "disable during flat fetch": + close(seen) + select { + case <-release: + case <-r.Context().Done(): + return + } + obj = []model.InboundClientIps{{ClientEmail: email, Ips: fmt.Sprintf(`[{"ip":%q,"timestamp":%d}]`, entry.IP, now)}} + case strings.HasSuffix(r.URL.Path, "/clients/clientIpsByGuid"): + if stage == "disable during attribution fetch" { + close(seen) + select { + case <-release: + case <-r.Context().Done(): + return + } + } + obj = map[string]map[string][]model.ClientIpEntry{guid: {email: {entry}}} + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) + })) + t.Cleanup(server.Close) + host, port, _ := strings.Cut(strings.TrimPrefix(server.URL, "http://"), ":") + portNum, err := strconv.Atoi(port) + if err != nil { + t.Fatal(err) + } + node := &model.Node{ + Name: guid, Guid: guid, Scheme: "http", Address: host, Port: portNum, + BasePath: "/", ApiToken: "tok", Enable: true, Status: "online", AllowPrivateAddress: true, + } + if err := db.Create(node).Error; err != nil { + t.Fatal(err) + } + + const hook = "test:park-obsolete-attribution" + if stage == "delete after attribution read" { + park := sync.OnceFunc(func() { close(seen); <-release }) + if err := db.Callback().Query().After("gorm:query").Register(hook, func(tx *gorm.DB) { + if tx.Statement.Table == "node_client_ips" { + park() + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(hook) }) + } + job := NewNodeTrafficSyncJob() + t.Cleanup(func() { unblock(); job.Close() }) + job.Run() + select { + case <-seen: + case <-time.After(3 * time.Second): + t.Fatal("IP sync did not reach the requested barrier") + } + + svc := &service.NodeService{} + if stage == "delete after attribution read" { + if err := db.Model(&model.Inbound{}).Where("node_id = ?", node.Id).Update("node_id", nil).Error; err != nil { + t.Fatal(err) + } + if err := svc.Delete(node.Id); err != nil { + t.Fatal(err) + } + } else if err := svc.SetEnable(node.Id, false); err != nil { + t.Fatal(err) + } + unblock() + job.workers.Wait() + var attribution, flat int64 + if err := db.Model(&model.NodeClientIp{}).Where("email = ?", email).Count(&attribution).Error; err != nil { + t.Fatal(err) + } + if err := db.Model(&model.InboundClientIps{}).Where("client_email = ?", email).Count(&flat).Error; err != nil { + t.Fatal(err) + } + if attribution != 0 || flat != 0 { + t.Fatalf("obsolete poll persisted attribution=%d flat=%d", attribution, flat) + } + }) + } +} + +func isolateIPPollDatabase(t *testing.T) { + t.Helper() + if os.Getenv("XUI_DB_TYPE") != "postgres" { + return + } + cleanup, err := testpg.IsolatePackage("job_ip_poll") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) +} diff --git a/internal/web/job/node_traffic_sync_job.go b/internal/web/job/node_traffic_sync_job.go index 50be79292..f86fc0934 100644 --- a/internal/web/job/node_traffic_sync_job.go +++ b/internal/web/job/node_traffic_sync_job.go @@ -2,6 +2,8 @@ package job import ( "context" + "errors" + "maps" "strings" "sync" "time" @@ -24,6 +26,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 +40,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 +97,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 +244,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 +260,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 +320,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 +438,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 +581,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 +599,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,40 +624,42 @@ 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) if err == nil && len(nodeIps) > 0 { - if err := j.inboundService.MergeNodeClientIps(n.Id, nodeIps); err != nil { + if err := j.inboundService.MergePolledNodeClientIps(ipCtx, n, nodeIps); err != nil { + if errors.Is(err, service.ErrIneligibleNodeIPReport) { + return + } logger.Warningf("node traffic sync: merge client ips from %s failed: %v", n.Name, err) } } else if err != nil { @@ -559,7 +669,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 { @@ -582,12 +692,12 @@ func (j *NodeTrafficSyncJob) syncOne(mgr *runtime.Manager, n *model.Node, doIpSy } else { j.noGuidIpEndpoint.Delete(n.Id) if len(guidTrees) > 0 { - if err := j.inboundService.MergeClientIpsByGuid(n, guidTrees); err != nil { + if err := j.inboundService.MergePolledClientIpsByGuid(ipCtx, n, guidTrees); err != nil && + !errors.Is(err, service.ErrIneligibleNodeIPReport) { logger.Warningf("node traffic sync: merge client ip attribution from %s failed: %v", n.Name, err) } } } - 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..f2e13b453 100644 --- a/internal/web/node_contract_test.go +++ b/internal/web/node_contract_test.go @@ -2,12 +2,14 @@ package web import ( "context" + "encoding/json" "fmt" "net/http" "net/http/httptest" "net/url" "path/filepath" "reflect" + "slices" "strconv" "strings" "sync" @@ -226,18 +228,49 @@ 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) } }}, + {"AddClientGroup attaches one client to two inbounds", []string{"AddClientGroup"}, func() error { + second := masterInbound("grouped", false) + second.Tag, second.Port = "in-51002-tcp", 51002 + if err := master.AddInbound(ctx, second); err != nil { + return err + } + client, err := json.Marshal(model.Client{ + Email: "grouped", ID: "0b6d5c2e-7c1a-4f4e-9d3b-000000000004", SubID: "s-grouped", Enable: true, + }) + if err != nil { + return err + } + _, ack, err := master.AddClientGroup(ctx, []string{contractTag, second.Tag}, client) + if err == nil && !slices.Equal(ack, []bool{true, true}) { + return fmt.Errorf("acknowledged inbounds %v, want both", ack) + } + return err + }, func(t *testing.T) { + for _, tag := range []string{contractTag, "in-51002-tcp"} { + inbound, ok := nodeRow(t, tag) + if !ok { + t.Fatalf("node has no inbound %s", tag) + } + clients, err := (&service.InboundService{}).GetClients(inbound) + if err != nil || !slices.ContainsFunc(clients, func(c model.Client) bool { return c.Email == "grouped" }) { + t.Fatalf("node inbound %s received no grouped client, err=%v", tag, err) + } + } + }}, {"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 +390,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) @@ -417,14 +452,15 @@ func TestMasterNodeContract(t *testing.T) { // Remote methods that never reach the node, or that this table must not run. var remoteMethodsOutsideContract = map[string]string{ - "Name": "local label", - "RecordAdoptedInbound": "local fingerprint bookkeeping", - "AdoptInboundAlias": "local alias bookkeeping", - "AdoptedInboundAliases": "local alias bookkeeping", - "AdvancePushedInbound": "local fingerprint bookkeeping", - "ForgetPushedInbound": "local fingerprint bookkeeping", - "ForgetInbound": "local bookkeeping for an inbound the node no longer has", - "UpdatePanel": "replaces the node binary; node-sync is denied it on purpose (#6201)", + "Name": "local label", + "RecordAdoptedInbound": "local fingerprint bookkeeping", + "AdoptInboundAlias": "local alias bookkeeping", + "AdoptedInboundAliases": "local alias bookkeeping", + "AdvancePushedInbound": "local fingerprint bookkeeping", + "PreparePushedInboundAdvance": "local fingerprint bookkeeping", + "ForgetPushedInbound": "local fingerprint bookkeeping", + "ForgetInbound": "local bookkeeping for an inbound the node no longer has", + "UpdatePanel": "replaces the node binary; node-sync is denied it on purpose (#6201)", } // A Remote method with no cell is how activeInbounds and bulkResetTraffic 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 7bff47238..8e225320c 100644 --- a/internal/web/runtime/reconcile_skip_test.go +++ b/internal/web/runtime/reconcile_skip_test.go @@ -65,6 +65,38 @@ func TestReconcileInbound_SkipsUnchanged(t *testing.T) { } } +func TestDeleteClientInvalidatesOnlyInboundsStampedWithThatClient(t *testing.T) { + for _, response := range []struct { + name string + body string + failed bool + }{ + {name: "acknowledged", body: `{"success":true}`}, + {name: "uncertain", body: `{"success":false,"msg":"apply failed"}`, failed: true}, + } { + t.Run(response.name, func(t *testing.T) { + srv, _ := newCountingNodeServer(t, response.body) + r := NewRemote(nodeForPlainServer(t, srv, "verify", "tok"), nil) + affected := &model.Inbound{Tag: "in-1", Protocol: model.VLESS, Settings: `{"clients":[{"email":"delete@example.test"}]}`} + 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 { + t.Fatalf("unexpected delete result: %v", err) + } + if pushed, err := r.ReconcileInbound(t.Context(), unaffected, true); err != nil || pushed { + t.Fatalf("unaffected inbound: pushed=%v err=%v", pushed, err) + } + if pushed, err := r.ReconcileInbound(t.Context(), affected, true); err != nil || !pushed { + t.Fatalf("affected inbound: pushed=%v err=%v", pushed, err) + } + if id, err := r.resolveRemoteID(t.Context(), unaffected.Tag); err != nil || id != 2 { + t.Fatalf("unaffected alias: id=%d err=%v", id, err) + } + }) + } +} + type nodeCallCounts struct { adds atomic.Int32 inboundUpdates atomic.Int32 @@ -94,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) }}, } @@ -127,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) @@ -169,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) @@ -197,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) @@ -224,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) @@ -243,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 { @@ -268,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 ada3d9d75..7f9eab52f 100644 --- a/internal/web/runtime/remote.go +++ b/internal/web/runtime/remote.go @@ -97,7 +97,7 @@ type Remote struct { // pushedFP holds the fingerprint of the last inbound wire payload successfully // pushed, keyed by panel-side tag, so reconcile can skip re-sending an // unchanged inbound. Guarded by mu; dropped with the Remote on node config change. - pushedFP map[string]string + pushedFP map[string]pushedInboundState // supportsZstd is learned from the node's X-3x-Node-Caps response header; once // seen, config pushes to this node are zstd-compressed. Old nodes never set // it, so they keep receiving plain bodies (mixed-version safe). @@ -137,7 +137,7 @@ func NewRemote(n *model.Node, r NodeEgressResolver) *Remote { snapshotGate: make(chan struct{}, 1), remoteIDByTag: make(map[string]int), adoptedAliases: make(map[string]string), - pushedFP: make(map[string]string), + pushedFP: make(map[string]pushedInboundState), egressResolver: r, } } @@ -354,7 +354,10 @@ func (r *Remote) do(ctx context.Context, method, path string, body any) (*envelo if bodyBytes != nil { hashHex = wirecodec.Sha256Hex(bodyBytes) if len(bodyBytes) >= zstdMinBodyBytes && r.nodeSupportsZstd() { - bodyBytes = wirecodec.Compress(bodyBytes) + bodyBytes, err = wirecodec.CompressContext(ctx, bodyBytes) + if err != nil { + return nil, err + } zstdEncoded = true } reqBody = bytes.NewReader(bodyBytes) @@ -470,19 +473,21 @@ func stripNodeInboundTagPrefix(nodeID int, tag string) string { // that lives on only one of the two panels: the node may carry the bare tag // while the central panel stores the prefixed form, or vice versa. func (r *Remote) cacheGetTag(tag string) (int, bool) { - if id, ok := r.cacheGet(tag); ok { + r.mu.RLock() + defer r.mu.RUnlock() + return r.cachedTagID(tag) +} + +func (r *Remote) cachedTagID(tag string) (int, bool) { + if id, ok := r.remoteIDByTag[tag]; ok { return id, true } prefix := nodeInboundTagPrefix(r.node.Id) if stripped, found := strings.CutPrefix(tag, prefix); found { - return r.cacheGet(stripped) + tag = stripped + } else { + tag = prefix + tag } - return r.cacheGet(prefix + tag) -} - -func (r *Remote) cacheGet(tag string) (int, bool) { - r.mu.RLock() - defer r.mu.RUnlock() id, ok := r.remoteIDByTag[tag] return id, ok } @@ -652,7 +657,7 @@ func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, exists r.mu.RLock() prev, ok := r.pushedFP[ib.Tag] r.mu.RUnlock() - if ok && prev == fp { + if ok && prev.fingerprint == fp { return false, nil } } else { @@ -667,9 +672,9 @@ func (r *Remote) ReconcileInbound(ctx context.Context, ib *model.Inbound, exists // recordPushedInbound stamps the fingerprint after a full-payload push — the // only operation that proves the node holds the entire wire payload. func (r *Remote) recordPushedInbound(ib *model.Inbound) { - fp := wireFingerprint(wireInbound(ib, r.node.Id)) + state := stampPushedInbound(ib, r.node.Id) r.mu.Lock() - r.pushedFP[ib.Tag] = fp + r.pushedFP[ib.Tag] = state r.mu.Unlock() } @@ -710,11 +715,12 @@ func (r *Remote) ForgetInbound(tag string) { // AdoptInboundAlias records a deployed alias without mutating either panel. // The runtime association is rediscovered after a master restart. func (r *Remote) AdoptInboundAlias(ib *model.Inbound, remote RemoteInboundOption) { + state := stampPushedInbound(ib, r.node.Id) r.mu.Lock() r.remoteIDByTag[remote.Tag] = remote.Id r.remoteIDByTag[ib.Tag] = remote.Id r.adoptedAliases[ib.Tag] = remote.Tag - r.pushedFP[ib.Tag] = wireFingerprint(wireInbound(ib, r.node.Id)) + r.pushedFP[ib.Tag] = state r.mu.Unlock() } @@ -734,13 +740,57 @@ func (r *Remote) AdoptedInboundAliases() []string { // node held the exact pre-edit state; otherwise the stale fingerprint stays and // the next reconcile re-sends the full inbound. func (r *Remote) AdvancePushedInbound(prevIb, ib *model.Inbound) { + r.PreparePushedInboundAdvance(prevIb, ib)() +} + +// PreparePushedInboundAdvance keeps large settings blobs out of pending client batches. +func (r *Remote) PreparePushedInboundAdvance(prevIb, ib *model.Inbound) func() { + tag := ib.Tag prevFP := wireFingerprint(wireInbound(prevIb, r.node.Id)) - nextFP := wireFingerprint(wireInbound(ib, r.node.Id)) - r.mu.Lock() - if r.pushedFP[ib.Tag] == prevFP { - r.pushedFP[ib.Tag] = nextFP + next := stampPushedInbound(ib, r.node.Id) + return func() { + r.mu.Lock() + defer r.mu.Unlock() + if r.pushedFP[tag].fingerprint == prevFP { + r.pushedFP[tag] = next + } + } +} + +type pushedInboundClient struct { + Email string `json:"email"` +} + +type pushedInboundState struct { + fingerprint string + clients []pushedInboundClient + clientsKnown bool +} + +func stampPushedInbound(ib *model.Inbound, nodeID int) pushedInboundState { + var settings struct { + Clients []pushedInboundClient `json:"clients"` + } + err := json.Unmarshal([]byte(ib.Settings), &settings) + return pushedInboundState{ + fingerprint: wireFingerprint(wireInbound(ib, nodeID)), + clients: settings.Clients, + clientsKnown: err == nil, + } +} + +// A node-wide delete can remove a client from several inbounds, even when its +// reply times out. Only those previously stamped with that client can change. +func (r *Remote) forgetPushedClient(email string) { + r.mu.Lock() + defer r.mu.Unlock() + for tag, state := range r.pushedFP { + if !state.clientsKnown || slices.ContainsFunc(state.clients, func(client pushedInboundClient) bool { + return client.Email == email + }) { + delete(r.pushedFP, tag) + } } - r.mu.Unlock() } // wireFingerprint hashes a wire payload so an unchanged inbound is cheap to detect. @@ -757,75 +807,134 @@ 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 { - id, err := r.resolveRemoteID(ctx, ib.Tag) - if err != nil { - return fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err) +func remoteClientApplyResult(env *envelope, err error) (ClientApplyResult, error) { + if err != nil || env == nil { + return ClientApplyResult{}, err } - payload := map[string]any{ - "client": client, - "inboundIds": []int{id}, + var result struct { + NodePending bool `json:"nodePending"` } - if _, err := r.do(ctx, http.MethodPost, "panel/api/clients/add", payload); err != nil { - return err - } - return nil + pending := json.Unmarshal(env.Obj, &result) == nil && result.NodePending + return ClientApplyResult{DownstreamPending: pending}, nil } -func (r *Remote) DeleteUser(ctx context.Context, ib *model.Inbound, email string) error { +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 ClientApplyResult{}, fmt.Errorf("remote AddClient: resolve tag %q: %w", ib.Tag, err) + } + return remoteClientApplyResult(r.postClientAdd(ctx, []int{id}, client)) +} + +// AddClientGroup returns the subset of tags acknowledged by one existing add RPC. +func (r *Remote) AddClientGroup(ctx context.Context, tags []string, client json.RawMessage) (ClientApplyResult, []bool, error) { + var refreshErr error + for _, tag := range tags { + if id, ok := r.cacheGetTag(tag); !ok || id <= 0 { + refreshErr = r.refreshRemoteIDs(ctx) + break + } + } + ids := make([]int, 0, len(tags)) + acknowledged := make([]bool, len(tags)) + seen := make(map[int]struct{}, len(tags)) + var missing []error + r.mu.RLock() + for i, tag := range tags { + id, ok := r.cachedTagID(tag) + if !ok || id <= 0 { + missing = append(missing, fmt.Errorf("%w: tag %q on node %s", errRemoteInboundNotFound, tag, r.node.Name)) + continue + } + acknowledged[i] = true + if _, duplicate := seen[id]; !duplicate { + ids = append(ids, id) + seen[id] = struct{}{} + } + } + r.mu.RUnlock() + unresolved := errors.Join(refreshErr, errors.Join(missing...)) + if len(ids) == 0 { + return ClientApplyResult{}, nil, unresolved + } + env, err := r.postClientAdd(ctx, ids, client) + if err != nil { + return ClientApplyResult{}, nil, errors.Join(err, unresolved) + } + var ack struct { + NodePending bool `json:"nodePending"` + } + // Legacy success replies omit obj or send null. + if len(env.Obj) != 0 { + if err := json.Unmarshal(env.Obj, &ack); err != nil { + return ClientApplyResult{}, nil, errors.Join(fmt.Errorf("decode grouped client add acknowledgment: %w", err), unresolved) + } + } + return ClientApplyResult{DownstreamPending: ack.NodePending}, acknowledged, unresolved +} + +func (r *Remote) postClientAdd(ctx context.Context, ids []int, client any) (*envelope, error) { + payload := map[string]any{"client": client, "inboundIds": ids} + return r.do(ctx, http.MethodPost, "panel/api/clients/add", payload) +} + +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) && strings.Contains(strings.ToLower(apiErr.msg), "not found") { - return nil + 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 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 ea249ba19..585689177 100644 --- a/internal/web/service/client_bulk.go +++ b/internal/web/service/client_bulk.go @@ -4,6 +4,7 @@ import ( "context" "encoding/json" "fmt" + "slices" "strings" "time" @@ -20,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"` @@ -144,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} }) @@ -173,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"` @@ -254,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} }) @@ -296,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"` @@ -479,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 { @@ -681,7 +685,8 @@ func (s *ClientService) bulkAdjustInboundClients( adTagIneligible: map[string]bool{}, } - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -694,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() } @@ -816,7 +822,7 @@ func (s *ClientService) bulkAdjustInboundClients( // Serialize against the traffic poll to avoid the cross-transaction // lock-order deadlock on inbounds/client_records (runSerializedTx). - txErr := runSerializedTx(func(tx *gorm.DB) error { + txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil { return err } @@ -827,12 +833,10 @@ func (s *ClientService) bulkAdjustInboundClients( if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } 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() @@ -847,29 +851,32 @@ func (s *ClientService) bulkAdjustInboundClients( if perr != nil { logger.Warning("BulkAdjust: node runtime lookup after commit failed:", perr) } else if push { - for email := range foundEmails { - entry := plan[email] - updated := *entry.record.ToClient() - if entry.applyExpiry { - updated.ExpiryTime = entry.newExpiry + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { + for email := range foundEmails { + entry := plan[email] + updated := *entry.record.ToClient() + if entry.applyExpiry { + updated.ExpiryTime = entry.newExpiry + } + if entry.applyTotal { + updated.TotalGB = entry.newTotal + } + if adTag != "" && oldInbound.Protocol == model.MTProto { + updated.AdTag = wantAdTag + } + updated.UpdatedAt = nowMs + if !batch.acknowledge(rt.UpdateUser(ctx, oldInbound, email, updated)) { + return false + } } - if entry.applyTotal { - updated.TotalGB = entry.newTotal - } - if adTag != "" && oldInbound.Protocol == model.MTProto { - updated.AdTag = wantAdTag - } - updated.UpdatedAt = nowMs - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, email, updated) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - // First failure ends the batch push; the reconcile converges the rest. - break - } - } + return true + }) } + if perr != nil || !push { + s.recordClientNodeDeferred(oldInbound.NodeID) + } + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } } @@ -879,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"` } @@ -952,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 { @@ -1013,9 +1021,9 @@ func (s *ClientService) BulkDelete(inboundSvc *InboundService, emails []string, if e := tx.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; e != nil { return e } - if e := tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error; e != nil { - return e - } + } + if e := inboundSvc.delClientIPsByEmails(tx, successEmails); e != nil { + return e } } for _, batch := range chunkInts(successIds, sqlInChunk) { @@ -1057,7 +1065,8 @@ func (s *ClientService) bulkDelInboundClients( res := bulkInboundDeleteResult{perEmailSkipped: map[string]string{}} defer InvalidateSubData() - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -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() } @@ -1190,9 +1200,17 @@ func (s *ClientService) bulkDelInboundClients( } } - // Serialize against the traffic poll to avoid the cross-transaction - // lock-order deadlock on inbounds/client_records (runSerializedTx). - txErr := runSerializedTx(func(tx *gorm.DB) error { + var dispatchEmails []string + if oldInbound.NodeID != nil { + for email := range wantedEmails { + if _, skip := res.perEmailSkipped[email]; !skip { + dispatchEmails = append(dispatchEmails, email) + } + } + slices.Sort(dispatchEmails) + } + var pending []model.NodePendingClientDelete + txErr := mutation.commit(oldInbound, nodeFullClientDelete, func(tx *gorm.DB) error { if err := commitInboundClientSettings(tx, oldInbound, prevSettings); err != nil { return err } @@ -1203,12 +1221,11 @@ func (s *ClientService) bulkDelInboundClients( if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } - return nil + pending, err = queueNodeClientDeletes(tx, oldInbound.NodeID, dispatchEmails) + 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() @@ -1238,30 +1255,28 @@ func (s *ClientService) bulkDelInboundClients( } } } else { - dispatchEmails := make([]string, 0, len(wantedEmails)) - for email := range wantedEmails { - if _, skip := res.perEmailSkipped[email]; !skip { - dispatchEmails = append(dispatchEmails, email) - } - } - if len(dispatchEmails) > nodeBulkPushThreshold { + 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 { - for _, email := range dispatchEmails { - ctx, cancel := nodePushContext() - err1 := rt.DeleteClient(ctx, email) - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err1) - // The node is already dirty, so one reconcile converges the rest of - // the batch instead of paying another deadline per client. - break + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { + complete := true + for _, row := range pending { + result, attempted, err := applyNodeClientDelete(ctx, rt, row) + if !batch.acknowledge(result, err) { + return false + } + complete = complete && attempted } - } + return complete + }) + } + if perr != nil || !push { + s.recordClientNodeDeferred(oldInbound.NodeID) } } @@ -1270,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"` } @@ -1482,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 { @@ -1568,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"` } @@ -1628,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 { @@ -1714,7 +1731,8 @@ func applyBulkSidecar(inboundSvc *InboundService, inboundId int, protocol model. func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, inboundId int, emails []string, enable bool) bulkSetEnableInboundResult { res := bulkSetEnableInboundResult{perEmailSkipped: map[string]string{}} - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { @@ -1726,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() } @@ -1813,7 +1832,7 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, push = false } - txErr := runSerializedTx(func(tx *gorm.DB) error { + txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { if e := commitInboundClientSettings(tx, oldInbound, prevSettings); e != nil { return e } @@ -1824,12 +1843,10 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, if err := s.SyncInbound(tx, inboundId, finalClients); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }) if txErr != nil { + s.recordClientNodeFailure(oldInbound.NodeID, &txErr) for _, ch := range changed { res.perEmailSkipped[ch.email] = txErr.Error() } @@ -1862,23 +1879,19 @@ func (s *ClientService) bulkSetEnableInboundClients(inboundSvc *InboundService, } } } else if push { - pushFailed := false - for _, ch := range changed { - updated := ch.client - updated.UpdatedAt = nowMs - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, ch.email, updated) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - pushFailed = true - // First failure ends the batch push; the reconcile converges the rest. - break + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { + for _, ch := range changed { + updated := ch.client + updated.UpdatedAt = nowMs + if !batch.acknowledge(rt.UpdateUser(ctx, oldInbound, ch.email, updated)) { + return false + } } - } - if !pushFailed { advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + return true + }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } return res diff --git a/internal/web/service/client_create_dispatch.go b/internal/web/service/client_create_dispatch.go new file mode 100644 index 000000000..47ec3db5c --- /dev/null +++ b/internal/web/service/client_create_dispatch.go @@ -0,0 +1,193 @@ +package service + +import ( + "context" + "encoding/json" + "fmt" + "runtime/debug" + "sync" + "time" + + "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" +) + +type queuedClientCreate struct { + turn *nodeConfigTurn + remote *runtime.Remote + tag string + client string + advance func() + queuedAt time.Time +} + +func (q *queuedClientCreate) prepare(turn *nodeConfigTurn, remote *runtime.Remote, previous, inbound *model.Inbound, client string, prunedOrphans bool) { + q.turn, q.remote, q.tag, q.client = turn, remote, inbound.Tag, client + q.queuedAt = time.Now() + if !prunedOrphans { + q.advance = remote.PreparePushedInboundAdvance(previous, inbound) + } +} + +func (s *ClientService) pushClientCreates(parent context.Context, pushes []queuedClientCreate) (bool, error) { + ctx, cancel := context.WithTimeout(parent, nodeClientPushTimeout) + defer cancel() + byNode := make(map[int][]*queuedClientCreate) + var nodeOrder []int + for i := range pushes { + push := &pushes[i] + if push.turn == nil { + continue + } + nodeID := push.turn.nodeID + if len(byNode[nodeID]) == 0 { + nodeOrder = append(nodeOrder, nodeID) + } + byNode[nodeID] = append(byNode[nodeID], push) + } + + applies := make([]inboundApply, 0, len(byNode)) + // Reserve one delivery slot per admitted node. Extra groups use spare capacity. + spare := make(chan struct{}, max(0, inboundFanoutConcurrency-len(byNode))) + for _, nodeID := range nodeOrder { + group := byNode[nodeID] + applies = append(applies, inboundApply{id: group[0].turn.inboundID, nodeID: &nodeID, run: func() (bool, error) { + s.pushClientCreatesOnNode(ctx, spare, group) + return false, nil + }}) + } + return fanoutInboundApplies(applies) +} + +func (s *ClientService) pushClientCreatesOnNode(ctx context.Context, spare chan struct{}, pending []*queuedClientCreate) { + queue := pending[0].turn.queue + nodeID := pending[0].turn.nodeID + defer func() { + for _, push := range pending { + push.turn.release() + } + }() + var workers sync.WaitGroup + defer workers.Wait() + primary := make(chan struct{}, 1) + for len(pending) > 0 { + if err := ctx.Err(); err != nil { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) + return + } + changed := queue.changes() + type batchKey struct { + remote *runtime.Remote + client string + } + var batches [][]*queuedClientCreate + positions := make(map[batchKey]int) + var waiting []*queuedClientCreate + for _, push := range pending { + select { + case <-push.turn.ready: + key := batchKey{remote: push.remote, client: push.client} + i, found := positions[key] + if !found { + i = len(batches) + positions[key] = i + batches = append(batches, nil) + } + batches[i] = append(batches[i], push) + default: + waiting = append(waiting, push) + } + } + if len(batches) == 0 { + select { + case <-changed: + case <-ctx.Done(): + } + continue + } + // Release ready lanes before waiting for lanes behind a node-wide turn. + for _, batch := range batches { + slot := reserveClientCreateSlot(ctx, primary, spare) + if slot == nil { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, ctx.Err()) + return + } + run := func() { + defer func() { <-slot }() + defer func() { + for _, push := range batch { + push.turn.release() + } + }() + s.applyClientCreateBatch(ctx, nodeID, queue, batch) + } + if len(batches) == 1 && len(waiting) == 0 { + run() + } else { + workers.Go(run) + } + } + pending = waiting + } +} + +func reserveClientCreateSlot(ctx context.Context, primary, spare chan struct{}) chan struct{} { + select { + case primary <- struct{}{}: + return primary + default: + } + select { + case primary <- struct{}{}: + return primary + case spare <- struct{}{}: + return spare + case <-ctx.Done(): + return nil + } +} + +func (s *ClientService) applyClientCreateBatch(ctx context.Context, nodeID int, queue *nodeConfigQueue, batch []*queuedClientCreate) { + if err := ctx.Err(); err != nil { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) + return + } + if !queue.acquireLive() { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy) + return + } + defer queue.releaseLive() + defer func() { + if panicValue := recover(); panicValue != nil { + for _, push := range batch { + push.remote.ForgetPushedInbound(push.tag) + } + err := fmt.Errorf("panic applying grouped client create: %v", panicValue) + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) + logger.Errorf("%v for node %d\n%s", err, nodeID, debug.Stack()) + } + }() + tags := make([]string, len(batch)) + for i, push := range batch { + tags[i] = push.tag + } + remote := batch[0].remote + started := time.Now() + result, acknowledged, err := remote.AddClientGroup(ctx, tags, json.RawMessage(batch[0].client)) + if err != nil { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, err) + logger.Warning("Error applying clients on", remote.Name(), ":", err) + } + for i, push := range batch { + if i >= len(acknowledged) || !acknowledged[i] || push.advance == nil { + remote.ForgetPushedInbound(push.tag) + s.recordClientNodePush(nodeID, i < len(acknowledged) && acknowledged[i] && result.DownstreamPending, result, nil) + continue + } + push.advance() + s.recordClientNodePush(nodeID, true, result, nil) + } + logger.Debugf("client create node apply: node_id=%d inbounds=%d queue_wait_ms=%d rpc_ms=%d", + nodeID, len(tags), started.Sub(batch[0].queuedAt).Milliseconds(), time.Since(started).Milliseconds()) +} diff --git a/internal/web/service/client_create_fanout_test.go b/internal/web/service/client_create_fanout_test.go index 1d7dc57bc..940ca93e4 100644 --- a/internal/web/service/client_create_fanout_test.go +++ b/internal/web/service/client_create_fanout_test.go @@ -56,6 +56,248 @@ func TestCreateAcrossManyInboundsUsesOneEmailSnapshot(t *testing.T) { } } +func TestCreateGroupsCompatibleInboundsOnOneRemote(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + first := realNodeInbound(t, fake, 40301, nil) + ids := []int{first.Id} + remoteIDs := []int{101} + for i := 1; i < 11; i++ { + ib := nodeInbound(t, *first.NodeID, 40301+i, nil) + ids = append(ids, ib.Id) + remoteIDs = append(remoteIDs, 101+i) + fake.tags[ib.Tag] = 101 + i + } + + svc := (&ClientService{}).TrackNodeApplies() + const email = "grouped@x" + const uuid = "bbbbbbbb-1111-2222-3333-555555555555" + for range 2 { + _, err := svc.Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: email, ID: uuid, SubID: "sub-grouped", Enable: true}, InboundIds: ids, + }) + if err != nil { + t.Fatal(err) + } + } + + fake.mu.Lock() + pushes := slices.Clone(fake.clientAdds) + fake.mu.Unlock() + if len(pushes) != 1 { + t.Fatalf("client add RPCs = %d, want one for all 11 inbounds and none on retry", len(pushes)) + } + slices.Sort(pushes[0].InboundIds) + if !slices.Equal(pushes[0].InboundIds, remoteIDs) || pushes[0].Client.ID != uuid { + t.Fatalf("node received wrong IDs or credentials: %+v", pushes[0]) + } + rec := lookupClientRecord(t, email) + attached, err := svc.GetInboundIdsForRecord(rec.Id) + if err != nil { + t.Fatal(err) + } + slices.Sort(attached) + if !slices.Equal(attached, ids) { + t.Fatalf("local attachments = %v, want %v", attached, ids) + } + if r := svc.NodeApplyResponse(); r == nil || r.NodePending || !slices.Equal(r.NodeResults, []ClientNodeApplyOutcome{ + {NodeID: *first.NodeID, Status: "applied"}, + }) { + t.Fatalf("node outcome = %+v, want applied", r) + } +} + +func TestCreateSplitsFlowAndSendsResolvedInbounds(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + raw := realNodeInbound(t, fake, 40321, nil) + tls := nodeInbound(t, *raw.NodeID, 40322, nil) + missing := nodeInbound(t, *raw.NodeID, 40323, nil) + if err := database.GetDB().Model(tls).Update("stream_settings", `{"network":"tcp","security":"tls"}`).Error; err != nil { + t.Fatal(err) + } + fake.tags[tls.Tag] = 122 + + svc := (&ClientService{}).TrackNodeApplies() + const flow = "xtls-rprx-vision" + _, err := svc.Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: "split@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Flow: flow, Enable: true}, + InboundIds: []int{raw.Id, tls.Id, missing.Id}, + }) + if err != nil { + t.Fatal(err) + } + fake.mu.Lock() + pushes := slices.Clone(fake.clientAdds) + fake.mu.Unlock() + slices.SortFunc(pushes, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] }) + if len(pushes) != 2 || !slices.Equal(pushes[0].InboundIds, []int{121}) || !slices.Equal(pushes[1].InboundIds, []int{122}) || + pushes[0].Client.Flow != "" || pushes[1].Client.Flow != flow { + t.Fatalf("wrong delivery for mixed flow and missing tag: %+v", pushes) + } + res := svc.NodeApplyResponse() + want := []ClientNodeApplyOutcome{{NodeID: *raw.NodeID, Status: "pending", Reason: "push_failed"}} + if res == nil || !res.NodePending || !slices.Equal(res.NodeResults, want) { + t.Fatalf("node outcome = %+v, want %v", res, want) + } + _, _, dirty, _, err := (&NodeService{}).NodeSyncState(*raw.NodeID) + if err != nil || !dirty { + t.Fatalf("missing inbound must leave a durable reconcile: dirty=%t err=%v", dirty, err) + } +} + +func TestCreateUsesEffectiveAllowedIPsOnRemote(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + wg := realNodeInbound(t, fake, 40331, nil) + awg := nodeInbound(t, *wg.NodeID, 40332, nil) + for _, inbound := range []struct { + id int + protocol model.Protocol + settings string + }{ + {id: wg.Id, protocol: model.WireGuard, settings: wgServerSettings()}, + {id: awg.Id, protocol: model.AmneziaWG, settings: amneziawgClientTestSettings}, + } { + if err := database.GetDB().Model(&model.Inbound{}).Where("id = ?", inbound.id). + Updates(map[string]any{"protocol": inbound.protocol, "settings": inbound.settings}).Error; err != nil { + t.Fatal(err) + } + } + fake.tags[awg.Tag] = 132 + + _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{ + Email: "split-tunnel@x", Enable: true, + AllowedIPsByInbound: map[int][]string{wg.Id: {"10.0.0.9/32"}, awg.Id: {"10.8.1.9/32"}}, + }, + InboundIds: []int{wg.Id, awg.Id}, + }) + if err != nil { + t.Fatal(err) + } + fake.mu.Lock() + pushes := slices.Clone(fake.clientAdds) + fake.mu.Unlock() + slices.SortFunc(pushes, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] }) + if len(pushes) != 2 { + t.Fatalf("node received %d add requests, want 2 distinct tunnel payloads", len(pushes)) + } + for i, addr := range []string{"10.0.0.9/32", "10.8.1.9/32"} { + push := pushes[i] + if !slices.Equal(push.InboundIds, []int{131 + i}) || !slices.Equal(push.Client.AllowedIPs, []string{addr}) || + len(push.Client.AllowedIPsByInbound) != 0 { + t.Fatalf("tunnel %d payload = %+v, want remote inbound %d and %s", i, push, 131+i, addr) + } + } +} + +func TestCreateDispatchesReadyLaneBeforeBlockedLane(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + fake := newFakeNodeHTTP(t) + first := realNodeInbound(t, fake, 40341, nil) + second := nodeInbound(t, *first.NodeID, 40342, nil) + fake.tags[second.Tag] = 142 + predecessor := reserveNodeConfigTurn(*first.NodeID, first.Id, nodeClientDelta) + defer predecessor.release() + + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + done := make(chan struct{}) + var saveErr error + go func() { + defer close(done) + _, saveErr = (&ClientService{}).CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: "ordered-add@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Enable: true}, + InboundIds: []int{first.Id, second.Id}, + }) + }() + t.Cleanup(func() { + cancel() + <-done + }) + wantRPC := func(remoteID int) { + t.Helper() + select { + case got := <-fake.clientAddEvents: + if !slices.Equal(got.InboundIds, []int{remoteID}) { + t.Fatalf("node received inbound IDs %v, want [%d]", got.InboundIds, remoteID) + } + case <-time.After(5 * time.Second): + t.Fatalf("ready inbound %d was not dispatched", remoteID) + } + } + wantRPC(142) + predecessor.release() + wantRPC(141) + select { + case <-done: + if saveErr != nil { + t.Fatal(saveErr) + } + case <-time.After(5 * time.Second): + t.Fatal("create waited after both requests were delivered") + } +} + +func TestCreateCancellationStopsFurtherNodeWaves(t *testing.T) { + setupClientNodeOrderDB(t) + useTestRuntimeManager(t) + const nodeCount = inboundFanoutConcurrency + 1 + fakes := make([]*fakeNodeHTTP, nodeCount) + var ids []int + for i := range nodeCount { + fakes[i] = newFakeNodeHTTP(t) + fakes[i].setHold(true) + ids = append(ids, realNodeInbound(t, fakes[i], 40351+i, nil).Id) + } + + svc := (&ClientService{}).TrackNodeApplies() + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + var saveErr error + go func() { + defer close(done) + _, saveErr = svc.CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: "cancel-add@x", ID: "bbbbbbbb-1111-2222-3333-555555555555", Enable: true}, + InboundIds: ids, + }) + }() + t.Cleanup(func() { cancel(); <-done }) + deadline := time.After(5 * time.Second) + for _, fake := range fakes[:inboundFanoutConcurrency] { + select { + case <-fake.clientAddEvents: + case <-deadline: + t.Fatal("the first wave did not reach every admitted node") + } + } + cancel() + select { + case <-done: + if saveErr != nil { + t.Fatal(saveErr) + } + case <-time.After(3 * time.Second): + t.Fatal("cancelled pushes held up the create") + } + if got := fakes[nodeCount-1].hitCount("/clients/add"); got != 0 { + t.Fatalf("queued node received %d RPCs after request cancellation", got) + } + rec := lookupClientRecord(t, "cancel-add@x") + links, err := svc.GetInboundIdsForRecord(rec.Id) + if err != nil || len(links) != nodeCount { + t.Fatalf("cancellation lost a committed membership: %v, err=%v", links, err) + } + if res := svc.NodeApplyResponse(); res == nil || !res.NodePending || len(res.NodeResults) != nodeCount { + t.Fatalf("node outcome = %+v, want all %d pending", res, nodeCount) + } +} + func TestAttachAcrossManyInboundsUsesOneEmailSnapshot(t *testing.T) { setupBulkDB(t) svc := &ClientService{} @@ -110,7 +352,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_create_node_reads_test.go b/internal/web/service/client_create_node_reads_test.go new file mode 100644 index 000000000..9b6e48dc2 --- /dev/null +++ b/internal/web/service/client_create_node_reads_test.go @@ -0,0 +1,283 @@ +package service + +import ( + "context" + "net/http" + "slices" + "sync" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestSlimCreateUsesLockedFlowForGroupedDelivery(t *testing.T) { + peer, _, inbounds, _ := setupGroupedCreatePeer(t) + db := database.GetDB() + first, second := inbounds[0], inbounds[1] + const tls = `{"network":"tcp","security":"tls"}` + const reality = `{"network":"tcp","security":"reality"}` + if err := db.Model(first).Update("stream_settings", tls).Error; err != nil { + t.Fatal(err) + } + third := nodeInbound(t, *first.NodeID, 46203, nil) + peer.tags[third.Tag] = 103 + peer.settings[103] = third.Settings + if err := db.Model(third).Update("settings", `{"clients":[],"decryption":"mlkem768x25519plus.native.0rtt.test"}`).Error; err != nil { + t.Fatal(err) + } + var disableFirst, enableSecond sync.Once + const hook = "test:flow-changes-after-create-preparation-read" + query := db.Callback().Query() + if err := query.After("gorm:query").Register(hook, func(tx *gorm.DB) { + ib, ok := tx.Statement.Dest.(*model.Inbound) + if !ok || tx.Error != nil { + return + } + switch ib.Id { + case first.Id: + disableFirst.Do(func() { _ = tx.AddError(db.Model(first).Update("disable_flow", true).Error) }) + case second.Id: + enableSecond.Do(func() { _ = tx.AddError(db.Model(second).Update("stream_settings", reality).Error) }) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = query.Remove(hook) }) + + const flow = "xtls-rprx-vision" + client := groupedRecoveryClient("locked-flow@x") + client.Flow = flow + if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + Client: client, InboundIds: []int{first.Id, second.Id, third.Id}, + }); err != nil { + t.Fatal(err) + } + peer.mu.Lock() + calls := slices.Clone(peer.adds) + peer.mu.Unlock() + slices.SortFunc(calls, func(a, b ClientCreatePayload) int { return a.InboundIds[0] - b.InboundIds[0] }) + if len(calls) != 2 || !slices.Equal(calls[0].InboundIds, []int{101}) || calls[0].Client.Flow != "" || + !slices.Equal(calls[1].InboundIds, []int{102, 103}) || calls[1].Client.Flow != flow { + t.Fatalf("peer received %+v, want no flow on 101 and Vision on 102/103", calls) + } + for _, ib := range []*model.Inbound{first, second, third} { + want := flow + if ib.Id == first.Id { + want = "" + } + if c, ok := settingsClient(t, ib.Id, client.Email); !ok || c.Flow != want { + t.Fatalf("stored flow for inbound %d = %q, want %q", ib.Id, c.Flow, want) + } + } +} + +func TestSlimCreateHealthyTargetsProgressWithBlockedPeer(t *testing.T) { + slow, node, slowTargets, _ := setupGroupedCreatePeer(t) + healthy := newFakeNodeHTTP(t) + firstHealthy := realNodeInbound(t, healthy, 46321, nil) + secondHealthy := nodeInbound(t, *firstHealthy.NodeID, 46322, nil) + healthy.tags[secondHealthy.Tag] = 122 + for i := range 2 { + ib := nodeInbound(t, node.Id, 46331+i, nil) + slow.tags[ib.Tag] = 131 + i + slow.settings[131+i] = ib.Settings + slowTargets = append(slowTargets, ib) + } + var ids []int + var locks []*inboundMutationLock + for _, ib := range slowTargets { + ids = append(ids, ib.Id) + locks = append(locks, lockInbound(ib.Id)) + } + releaseLocks := sync.OnceFunc(func() { + for _, lock := range locks { + lock.Unlock() + } + }) + ids = append(ids, firstHealthy.Id, secondHealthy.Id) + healthySent := make(chan struct{}) + releaseRPC := sync.OnceFunc(func() { close(healthySent) }) + slow.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) { + select { + case <-healthySent: + case <-r.Context().Done(): + return + } + apply(len(payload.InboundIds)) + _, _ = w.Write([]byte(`{"success":true}`)) + } + saved := make(chan int, 2) + db := database.GetDB() + const hook = "test:healthy-inbound-write-while-other-inbounds-block" + updates := db.Callback().Update() + if err := updates.After("gorm:update").Register(hook, func(tx *gorm.DB) { + if tx.Statement.Table == "inbounds" && len(tx.Statement.Vars) == 2 { + if id, ok := tx.Statement.Vars[1].(int); ok && (id == firstHealthy.Id || id == secondHealthy.Id) { + saved <- id + } + } + }); err != nil { + releaseLocks() + t.Fatal(err) + } + t.Cleanup(func() { _ = updates.Remove(hook) }) + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan struct{}) + svc := (&ClientService{}).TrackNodeApplies() + var createErr error + t.Cleanup(func() { releaseLocks(); releaseRPC(); cancel(); <-done }) + go func() { + defer close(done) + _, createErr = svc.CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{ + Client: groupedRecoveryClient("healthy-node@x"), InboundIds: ids, + }) + }() + deadline := time.After(3 * time.Second) + seen := make(map[int]bool) + for range 2 { + select { + case id := <-saved: + seen[id] = true + case <-deadline: + t.Fatalf("healthy node's writes waited for parked lanes: %v", seen) + } + } + if len(seen) != 2 { + t.Fatalf("healthy writes seen = %v", seen) + } + if err := submitTrafficWrite(func() error { return nil }); err != nil { + t.Fatal(err) + } + releaseLocks() + select { + case call := <-healthy.clientAddEvents: + if !slices.Equal(call.InboundIds, []int{121, 122}) { + t.Fatalf("healthy peer received IDs %v, want 121 and 122 together", call.InboundIds) + } + case <-time.After(3 * time.Second): + t.Fatal("healthy peer waited for the slow peer's RPC") + } + releaseRPC() + select { + case <-done: + if createErr != nil { + t.Fatal(createErr) + } + case <-time.After(5 * time.Second): + t.Fatal("create did not return") + } + result := svc.NodeApplyResponse() + want := []ClientNodeApplyOutcome{{NodeID: node.Id, Status: "applied"}, {NodeID: *firstHealthy.NodeID, Status: "applied"}} + if result == nil || result.NodePending || !slices.Equal(result.NodeResults, want) { + t.Fatalf("node outcomes = %+v, want %v", result, want) + } +} + +func TestSlimCreateProjectionPreservesNodeIDAndProtocolSettings(t *testing.T) { + setupClientNodeOrderDB(t) + fake := newFakeNodeHTTP(t) + remote := realNodeInbound(t, fake, 46341, nil) + local := seedInboundSettingsReadTest(t, 46342, model.VLESS, `{"clients":[]}`) + mtproto := seedInboundSettingsReadTest(t, 46343, model.MTProto, `{"clients":[],"fakeTlsDomain":"front.example.test"}`) + for _, tc := range []struct { + inbound *model.Inbound + generate bool + settings string + }{ + {inbound: remote}, + {inbound: local}, + {inbound: mtproto, generate: true, settings: mtproto.Settings}, + {inbound: mtproto}, + } { + got, err := getInboundForClientCreate(tc.inbound.Id, tc.generate) + if err != nil { + t.Fatal(err) + } + var nodeID, wantNodeID int + if got.NodeID != nil { + nodeID = *got.NodeID + } + if tc.inbound.NodeID != nil { + wantNodeID = *tc.inbound.NodeID + } + if got.Id != tc.inbound.Id || nodeID != wantNodeID || got.Protocol != tc.inbound.Protocol || + got.Enable != tc.inbound.Enable || got.Listen != tc.inbound.Listen || got.Settings != tc.settings { + t.Fatalf("projection id=%d node=%d protocol=%s settings bytes=%d, want id=%d node=%d protocol=%s settings bytes=%d", + got.Id, nodeID, got.Protocol, len(got.Settings), tc.inbound.Id, wantNodeID, tc.inbound.Protocol, len(tc.settings)) + } + } + secret := model.GenerateFakeTLSSecret("supplied.example.test") + const email = "preserve-supplied-secret@x" + if _, err := (&ClientService{}).CreateOne(&InboundService{}, mtproto.Id, model.Client{Email: email, Secret: secret}); err != nil { + t.Fatal(err) + } + if c, ok := settingsClient(t, mtproto.Id, email); !ok || c.Secret != secret { + t.Fatal("create regenerated the supplied MTProto secret") + } +} + +func TestSlimAttachUsesLockedFlowAndPreservesRawAdd(t *testing.T) { + setupClientNodeOrderDB(t) + db := database.GetDB() + inboundSvc, svc := &InboundService{}, &ClientService{} + client := groupedRecoveryClient("attach-flow@x") + client.Flow = "xtls-rprx-vision" + source := seedInboundSettingsReadTest(t, 46351, model.VLESS, clientsSettings(t, []model.Client{client})) + if err := svc.SyncInbound(nil, source.Id, []model.Client{client}); err != nil { + t.Fatal(err) + } + target := seedInboundSettingsReadTest(t, 46352, model.VLESS, `{"clients":[]}`) + if err := db.Model(target).Update("stream_settings", `{"network":"tcp","security":"tls"}`).Error; err != nil { + t.Fatal(err) + } + query := db.Callback().Query() + const hook = "test:disable-flow-after-attach-preparation-read" + var disable sync.Once + if err := query.After("gorm:query").Register(hook, func(tx *gorm.DB) { + if ib, ok := tx.Statement.Dest.(*model.Inbound); ok && ib.Id == target.Id && tx.Error == nil { + disable.Do(func() { _ = tx.AddError(db.Model(target).Update("disable_flow", true).Error) }) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = query.Remove(hook) }) + if _, err := svc.AttachByEmail(inboundSvc, client.Email, []int{target.Id}); err != nil { + t.Fatal(err) + } + if c, ok := settingsClient(t, target.Id, client.Email); !ok || c.Flow != "" { + t.Fatalf("attach retained stale flow %q", c.Flow) + } + client.Email, client.SubID, client.ID = "legacy-add@x", "legacy-add", "aaaaaaaa-1111-2222-3333-555555555555" + if _, err := svc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: target.Id, Settings: clientsSettings(t, []model.Client{client}), + }); err != nil { + t.Fatal(err) + } + if c, ok := settingsClient(t, target.Id, client.Email); !ok || c.Flow != client.Flow { + t.Fatalf("raw AddInboundClient changed its caller-owned flow to %q", c.Flow) + } +} + +func TestSlimUpdateRebasesConcurrentSettings(t *testing.T) { + setupClientNodeOrderDB(t) + ib := seedRenewableNeighbour(t, 46361, nil) + record := lookupClientRecord(t, "x@stale") + current := record.ToClient() + current.Comment = "updated alongside renewal" + edit := &model.Inbound{Id: ib.Id, Settings: clientsSettings(t, []model.Client{*current})} + var editErr error + commitTickBetweenReadAndWrite(t, renewYTick(ib.Id), func() { + _, editErr = (&ClientService{}).UpdateInboundClient(&InboundService{}, edit, current.Email) + }) + if editErr != nil { + t.Fatal(editErr) + } + requireNeighbourRenewed(t, ib.Id) + if saved, ok := settingsClient(t, ib.Id, current.Email); !ok || saved.Comment != current.Comment { + t.Fatalf("update lost the edited comment: %+v", saved) + } +} diff --git a/internal/web/service/client_create_order_test.go b/internal/web/service/client_create_order_test.go new file mode 100644 index 000000000..7e6cfb191 --- /dev/null +++ b/internal/web/service/client_create_order_test.go @@ -0,0 +1,308 @@ +package service + +import ( + "context" + "net/http" + "slices" + "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/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +func TestGroupedCreateOrdersLaterClientMutations(t *testing.T) { + for _, change := range []string{"update", "rename", "detach", "delete", "delete and reattach"} { + t.Run(change, func(t *testing.T) { + peer, node, ibs, _ := setupGroupedCreatePeer(t) + db := database.GetDB() + svc, inboundSvc := &ClientService{}, &InboundService{} + client := groupedRecoveryClient("ordered-group@x") + updateEmail := client.Email + if change == "rename" { + updateEmail = "renamed-group@x" + } + blocked, release := make(chan struct{}), make(chan struct{}) + free := sync.OnceFunc(func() { close(release) }) + var workers sync.WaitGroup + t.Cleanup(func() { free(); workers.Wait() }) + var requests atomic.Int32 + calls := make(chan string, 8) + peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) { + calls <- "add" + if requests.Add(1) == 1 { + close(blocked) + select { + case <-release: + case <-r.Context().Done(): + return + } + } + apply(len(payload.InboundIds)) + _, _ = w.Write([]byte(`{"success":true}`)) + } + peer.mutate = func(w http.ResponseWriter, r *http.Request) { + calls <- r.URL.Path + _, _ = w.Write([]byte(`{"success":true}`)) + } + async := func(op func() (bool, error)) <-chan error { + done := make(chan error, 1) + workers.Go(func() { _, err := op(); done <- err }) + return done + } + created := async(func() (bool, error) { + return svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: []int{ibs[0].Id, ibs[1].Id}}) + }) + waitTrafficWriterSignal(t, blocked, "grouped create never reached the node") + original := lookupClientRecord(t, client.Email) + before := groupedDirtyGeneration(t, node.Id) + const callback = "test:observe-later-grouped-commit" + marked := make(chan struct{}, 8) + if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) { + if tx.Statement.Table == "nodes" && strings.Contains(tx.Statement.SQL.String(), "config_dirty_at") { + marked <- struct{}{} + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) }) + waitCommit := func(previous int64) int64 { + t.Helper() + deadline := time.After(2 * time.Second) + for { + select { + case <-marked: + case <-deadline: + t.Fatal("later local mutation did not advance the dirty generation") + } + if err := submitTrafficWrite(func() error { return nil }); err != nil { + t.Fatal(err) + } + if generation := groupedDirtyGeneration(t, node.Id); generation > previous { + return generation + } + } + } + mutated := async(func() (bool, error) { + switch change { + case "update", "rename": + next := client + next.Comment, next.Email = "committed later", updateEmail + return svc.UpdateByEmail(inboundSvc, client.Email, next, 0, ibs[0].Id) + case "detach": + return svc.DetachByEmail(inboundSvc, ibs[0].Id, client.Email) + default: + return svc.DeleteByEmail(inboundSvc, client.Email, false) + } + }) + after := waitCommit(before) + if change == "update" || change == "rename" { + for { + stored, ok := settingsClient(t, ibs[0].Id, updateEmail) + if ok && stored.Comment == "committed later" { + break + } + after = waitCommit(after) + } + } + if strings.HasPrefix(change, "delete") { + for { + links, err := svc.GetInboundIdsForRecord(original.Id) + if err != nil { + t.Fatal(err) + } + if len(links) == 0 { + break + } + after = waitCommit(after) + } + } + deletes := func() int64 { + t.Helper() + var n int64 + if err := db.Model(&model.NodePendingClientDelete{}).Where("node_id = ? AND email = ?", node.Id, client.Email).Count(&n).Error; err != nil { + t.Fatal(err) + } + return n + } + var reattached <-chan error + if strings.HasPrefix(change, "delete") && deletes() != 1 { + t.Fatal("queued full delete has no durable outbox entry") + } + if change == "delete and reattach" { + reattached = async(func() (bool, error) { + return svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: []int{ibs[0].Id}}) + }) + waitCommit(after) + } + if err := (&NodeService{}).ClearNodeDirty(node.Id, before); err != nil { + t.Fatal(err) + } + groupedDirtyGeneration(t, node.Id) + if len(calls) != 1 { + t.Fatalf("later operation reached peer before grouped create acknowledgment (%d calls)", len(calls)) + } + free() + done := []<-chan error{created, mutated} + if reattached != nil { + done = append(done, reattached) + } + for i, settled := range done { + if err := waitTrafficWriterErr(t, settled); err != nil { + t.Fatalf("operation %d failed: %v", i+1, err) + } + } + var got []string + for len(calls) > 0 { + got = append(got, <-calls) + } + second := "/panel/api/clients/update/" + client.Email + switch change { + case "detach": + second = "/panel/api/clients/" + client.Email + "/detach" + case "delete": + second = "/panel/api/clients/del/" + client.Email + case "delete and reattach": + second = "add" + } + if !slices.Equal(got, []string{"add", second}) { + t.Fatalf("remote order = %v, want [add %s]", got, second) + } + if deletes() != 0 { + t.Fatal("completed or superseded delete was retained") + } + if reattached != nil { + rec := lookupClientRecord(t, client.Email) + links, err := svc.GetInboundIdsForRecord(rec.Id) + if err != nil || !slices.Equal(links, []int{ibs[0].Id}) { + t.Fatalf("later attachment lost: %v, err=%v", links, err) + } + } + }) + } +} + +func TestGroupedCreateKeepsFifthNodeDurablyPendingWhenBudgetExpires(t *testing.T) { + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + const nodes = inboundFanoutConcurrency + 1 + var peers []*fakeNodeHTTP + var ids []int + var healthy *model.Inbound + for i := range nodes { + fake := newFakeNodeHTTP(t) + fake.setHold(i < inboundFanoutConcurrency) + peers = append(peers, fake) + healthy = realNodeInbound(t, fake, 46231+i, nil) + ids = append(ids, healthy.Id) + } + svc := (&ClientService{}).TrackNodeApplies() + inboundSvc := &InboundService{} + started := time.Now() + client := groupedRecoveryClient("fifth-destination@x") + if _, err := svc.Create(inboundSvc, &ClientCreatePayload{Client: client, InboundIds: ids}); err != nil { + t.Fatal(err) + } + elapsed := time.Since(started) + if elapsed >= 2*nodeClientPushTimeout { + t.Fatalf("create took %v, want one delivery window", elapsed) + } + status := svc.NodeApplyResponse() + if status == nil || !status.NodePending || len(status.NodeResults) != nodes { + t.Fatalf("node outcomes = %+v, want %d pending", status, nodes) + } + for i, p := range peers { + want := 1 + if i == inboundFanoutConcurrency { + want = 0 + } + if got := p.hitCount("/clients/add"); got != want { + t.Fatalf("peer %d received %d adds, want %d with shared timeout", i, got, want) + } + if outcome := status.NodeResults[i]; outcome.Status != "pending" || outcome.Reason != "timeout" { + t.Fatalf("peer %d outcome = %+v, want timeout", i, outcome) + } + } + inboundID := *healthy.NodeID + groupedDirtyGeneration(t, inboundID) + if got := settingsClientEmails(t, healthy.Id); !slices.Equal(got, []string{client.Email}) { + t.Fatalf("healthy peer membership was dropped: %v", got) + } + var node model.Node + if err := database.GetDB().First(&node, inboundID).Error; err != nil { + t.Fatal(err) + } + rt, err := mgr.RuntimeFor(&inboundID) + if err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), time.Second) + defer cancel() + if err := inboundSvc.ReconcileNode(ctx, rt.(*runtime.Remote), &node); err != nil { + t.Fatal(err) + } + if got := peers[nodes-1].hitCount("/inbounds/update/"); got != 1 { + t.Fatalf("healthy peer received %d recovery updates, want 1", got) + } + t.Logf("four slow deliveries used %v and the fifth peer converged on reconciliation", elapsed) +} + +func TestGroupedCreateReconcileBarrierDrainsAfterAcknowledgment(t *testing.T) { + peer, node, ibs, remote := setupGroupedCreatePeer(t) + blocked, release := make(chan struct{}), make(chan struct{}) + free := sync.OnceFunc(func() { close(release) }) + var workers sync.WaitGroup + t.Cleanup(func() { free(); workers.Wait() }) + peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) { + close(blocked) + select { + case <-release: + case <-r.Context().Done(): + return + } + apply(len(payload.InboundIds)) + _, _ = w.Write([]byte(`{"success":true}`)) + } + created, reconciled := make(chan error, 1), make(chan error, 1) + inboundSvc := &InboundService{} + workers.Go(func() { + _, err := (&ClientService{}).Create(inboundSvc, &ClientCreatePayload{ + Client: groupedRecoveryClient("reconcile-barrier@x"), InboundIds: []int{ibs[0].Id, ibs[1].Id}, + }) + created <- err + }) + waitTrafficWriterSignal(t, blocked, "grouped add never reached peer") + workers.Go(func() { reconciled <- inboundSvc.ReconcileNode(t.Context(), remote, node) }) + deadline := time.Now().Add(2 * time.Second) + for { + nodeConfigDispatchMu.Lock() + q := nodeConfigDispatch[node.Id] + waiting := q != nil && q.reconciles == 1 + nodeConfigDispatchMu.Unlock() + if waiting { + break + } + select { + case err := <-reconciled: + t.Fatalf("reconcile overtook the blocked grouped create, err=%v", err) + default: + } + if time.Now().After(deadline) { + t.Fatal("reconciliation never reached the node-wide barrier") + } + time.Sleep(time.Millisecond) + } + free() + for _, done := range []<-chan error{created, reconciled} { + if err := waitTrafficWriterErr(t, done); err != nil { + t.Fatal(err) + } + } + assertGroupedRecovery(t, peer, node, remote, ibs, 1, nil) +} diff --git a/internal/web/service/client_create_reconcile_test.go b/internal/web/service/client_create_reconcile_test.go new file mode 100644 index 000000000..87f435e46 --- /dev/null +++ b/internal/web/service/client_create_reconcile_test.go @@ -0,0 +1,489 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "slices" + "strconv" + "strings" + "sync" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" +) + +type groupedCreatePeer struct { + mu sync.Mutex + tags map[string]int + settings map[int]string + adds []ClientCreatePayload + updates []int + respond func(http.ResponseWriter, *http.Request, ClientCreatePayload, func(int)) + mutate func(http.ResponseWriter, *http.Request) +} + +func (p *groupedCreatePeer) serve(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + switch { + case strings.HasSuffix(r.URL.Path, "/inbounds/list"): + p.mu.Lock() + catalog := make([]runtime.RemoteInboundOption, 0, len(p.tags)) + for tag, id := range p.tags { + catalog = append(catalog, runtime.RemoteInboundOption{Id: id, Tag: tag}) + } + p.mu.Unlock() + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": catalog}) + case strings.HasSuffix(r.URL.Path, "/clients/add"): + var payload ClientCreatePayload + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + p.mu.Lock() + p.adds = append(p.adds, payload) + p.mu.Unlock() + apply := func(count int) { + p.mu.Lock() + defer p.mu.Unlock() + for _, id := range payload.InboundIds[:count] { + var settings map[string]any + _ = json.Unmarshal([]byte(p.settings[id]), &settings) + clients, _ := settings["clients"].([]any) + if slices.ContainsFunc(clients, func(entry any) bool { + _, email := clientEntryEmail(entry) + return email == payload.Client.Email + }) { + continue + } + settings["clients"] = append(clients, payload.Client) + encoded, _ := json.Marshal(settings) + p.settings[id] = string(encoded) + } + } + if p.respond != nil { + p.respond(w, r, payload, apply) + return + } + apply(len(payload.InboundIds)) + _, _ = w.Write([]byte(`{"success":true}`)) + case strings.Contains(r.URL.Path, "/inbounds/update/"): + _, suffix, _ := strings.Cut(r.URL.Path, "/inbounds/update/") + id, err := strconv.Atoi(suffix) + if err != nil || r.ParseForm() != nil || r.Form.Get("settings") == "" { + http.Error(w, "missing inbound ID or settings", http.StatusBadRequest) + return + } + p.mu.Lock() + p.settings[id] = r.Form.Get("settings") + p.updates = append(p.updates, id) + p.mu.Unlock() + _, _ = w.Write([]byte(`{"success":true}`)) + default: + if p.mutate == nil { + http.NotFound(w, r) + } else { + p.mutate(w, r) + } + } +} + +func TestGroupedCreateRecoversIndeterminateDelivery(t *testing.T) { + for _, tc := range []struct { + name string + reason string + reply func(w http.ResponseWriter, r *http.Request, apply func(int)) + }{ + {"partially applied HTTP error", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(1) + http.Error(w, "second write failed", http.StatusInternalServerError) + }}, + {"lost acknowledgment", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(2) + conn, _, err := w.(http.Hijacker).Hijack() + if err == nil { + _ = conn.Close() + } + }}, + {"deadline after persistence", "timeout", func(_ http.ResponseWriter, r *http.Request, apply func(int)) { + apply(2) + <-r.Context().Done() + }}, + {"malformed acknowledgment", "push_failed", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(1) + _, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":"unknown"}}`)) + }}, + {"downstream pending", "downstream_pending", func(w http.ResponseWriter, _ *http.Request, apply func(int)) { + apply(2) + _, _ = w.Write([]byte(`{"success":true,"obj":{"nodePending":true}}`)) + }}, + } { + t.Run(tc.name, func(t *testing.T) { + peer, node, inbounds, remote := setupGroupedCreatePeer(t) + peer.respond = func(w http.ResponseWriter, r *http.Request, _ ClientCreatePayload, apply func(int)) { + tc.reply(w, r, apply) + } + client := groupedRecoveryClient("unknown-delivery@x") + svc := (&ClientService{}).TrackNodeApplies() + inboundSvc := &InboundService{} + payload := &ClientCreatePayload{Client: client, InboundIds: []int{inbounds[0].Id, inbounds[1].Id}} + if _, err := svc.Create(inboundSvc, payload); err != nil { + t.Fatal(err) + } + wantGroupedOutcome(t, &svc, node.Id, "pending", tc.reason) + dirtyAt := groupedDirtyGeneration(t, node.Id) + if _, err := (&ClientService{}).Create(inboundSvc, payload); err != nil { + t.Fatal(err) + } + if got := groupedDirtyGeneration(t, node.Id); dirtyAt != got { + t.Fatalf("idempotent create changed generation from %d to %d", dirtyAt, got) + } + for _, inbound := range inbounds { + if got := settingsClientEmails(t, inbound.Id); !slices.Equal(got, []string{client.Email}) { + t.Fatalf("master inbound %d lost or duplicated commits: %v", inbound.Id, got) + } + } + want := []int{101, 102} + if tc.reason == "downstream_pending" { + want = nil + } + assertGroupedRecovery(t, peer, node, remote, inbounds, 1, want) + }) + } +} + +func TestGroupedCreateDispatchesIndependentReadyPayload(t *testing.T) { + peer, _, inbounds, _ := setupGroupedCreatePeer(t) + first, second := inbounds[0], inbounds[1] + if err := database.GetDB().Model(first).Update("stream_settings", `{"network":"tcp","security":"reality"}`).Error; err != nil { + t.Fatal(err) + } + slow, healthy, release := make(chan struct{}), make(chan struct{}), make(chan struct{}) + free := sync.OnceFunc(func() { close(release) }) + t.Cleanup(free) + peer.respond = func(w http.ResponseWriter, r *http.Request, payload ClientCreatePayload, apply func(int)) { + if slices.Equal(payload.InboundIds, []int{101}) && payload.Client.Flow == "xtls-rprx-vision" { + close(slow) + select { + case <-release: + case <-r.Context().Done(): + return + } + } else if slices.Equal(payload.InboundIds, []int{102}) && payload.Client.Flow == "" { + close(healthy) + } else { + http.Error(w, "unexpected grouping", http.StatusBadRequest) + return + } + apply(1) + _, _ = w.Write([]byte(`{"success":true}`)) + } + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Second) + done := make(chan struct{}) + var createErr error + t.Cleanup(func() { cancel(); free(); <-done }) + go func() { + defer close(done) + client := groupedRecoveryClient("independent-flow@x") + client.Flow = "xtls-rprx-vision" + _, createErr = (&ClientService{}).CreateWithContext(ctx, &InboundService{}, &ClientCreatePayload{ + Client: client, InboundIds: []int{first.Id, second.Id}, + }) + }() + for _, call := range []<-chan struct{}{slow, healthy} { + select { + case <-call: + case <-ctx.Done(): + t.Fatal("independent payload waited behind the parked RPC") + } + } + free() + <-done + if createErr != nil { + t.Fatal(createErr) + } +} + +func TestGroupedCreateRepairsDeferredTargets(t *testing.T) { + for _, scenario := range []string{"missing tag", "disabled client", "pruned orphan", "one rollback", "transport panic"} { + t.Run(scenario, func(t *testing.T) { + peer, node, inbounds, remote := setupGroupedCreatePeer(t) + first, second := inbounds[0], inbounds[1] + db := database.GetDB() + wantAdds, status, reason, want := 1, "pending", "deferred", []int{101} + client := groupedRecoveryClient("recover-target@x") + switch scenario { + case "missing tag": + delete(peer.tags, first.Tag) + reason = "push_failed" + case "disabled client": + client.Enable = false + wantAdds, want = 0, []int{101, 102} + case "pruned orphan": + first.Settings = clientsSettings(t, []model.Client{groupedRecoveryClient("removed@x")}) + if err := db.Model(first).Update("settings", first.Settings).Error; err != nil { + t.Fatal(err) + } + remote.RecordAdoptedInbound(first) + peer.settings[101] = first.Settings + case "one rollback": + status, reason, want = "failed", "local_save_failed", nil + const callback = "test:grouped-create-local-rollback" + if err := db.Callback().Update().After("gorm:update").Register(callback, func(tx *gorm.DB) { + vars := tx.Statement.Vars + if tx.Statement.Table == "inbounds" && len(vars) == 2 && vars[1] == first.Id { + _ = tx.AddError(errors.New("forced create rollback")) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(callback) }) + case "transport panic": + wantAdds, reason, want = 0, "push_failed", []int{101, 102} + failing := *node + failing.OutboundTag = "test-egress" + remote = runtime.NewRemote(&failing, panickingCreateEgress{}) + runtime.GetManager().SetRuntimeOverride(node.Id, remote) + for _, inbound := range inbounds { + remote.RecordAdoptedInbound(inbound) + } + } + svc := (&ClientService{}).TrackNodeApplies() + _, err := svc.Create(&InboundService{}, &ClientCreatePayload{Client: client, InboundIds: []int{first.Id, second.Id}}) + if scenario == "one rollback" { + if err == nil || !strings.Contains(err.Error(), "forced create rollback") { + t.Fatalf("partial local failure = %v", err) + } + if _, ok := settingsClient(t, first.Id, client.Email); ok { + t.Fatal("rolled back inbound retained its client") + } + } else if err != nil { + t.Fatal(err) + } + if _, ok := settingsClient(t, second.Id, client.Email); !ok { + t.Fatal("successful inbound lost its committed client") + } + wantGroupedOutcome(t, &svc, node.Id, status, reason) + groupedDirtyGeneration(t, node.Id) + if scenario == "transport panic" { + nodeConfigDispatchMu.Lock() + leftover := nodeConfigDispatch[node.Id] + nodeConfigDispatchMu.Unlock() + if leftover != nil { + t.Fatal("recovered transport panic left a reserved node turn") + } + remote = runtime.NewRemote(node, nil) + } + peer.mu.Lock() + peer.tags[first.Tag] = 101 + peer.mu.Unlock() + assertGroupedRecovery(t, peer, node, remote, inbounds, wantAdds, want) + }) + } +} + +type panickingCreateEgress struct{} + +func (panickingCreateEgress) NodeEgressProxyURL(int) string { panic("fixture egress failure") } + +func TestGroupedCreatePreservesProtocolCredentials(t *testing.T) { + for _, tc := range []struct { + protocol model.Protocol + settings string + check func(model.Client) bool + }{ + {model.Shadowsocks, `{"clients":[],"method":"2022-blake3-aes-128-gcm"}`, func(c model.Client) bool { + return validShadowsocksClientKey("2022-blake3-aes-128-gcm", c.Password) + }}, + {model.MTProto, `{"clients":[],"fakeTlsDomain":"example.test"}`, func(c model.Client) bool { return c.Secret != "" }}, + {model.TUIC, `{"clients":[]}`, func(c model.Client) bool { return c.ID != "" && c.Password != "" }}, + } { + t.Run(string(tc.protocol), func(t *testing.T) { + peer, _, inbounds, remote := setupGroupedCreatePeer(t) + db := database.GetDB() + var ids []int + for _, ib := range inbounds { + if err := db.Model(ib).Updates(map[string]any{"protocol": tc.protocol, "settings": tc.settings}).Error; err != nil { + t.Fatal(err) + } + ids = append(ids, ib.Id) + } + first, second := inbounds[0], inbounds[1] + delete(peer.tags, first.Tag) + peer.tags["adopted-legacy-tag"] = 101 + remote.AdoptInboundAlias(first, runtime.RemoteInboundOption{Tag: "adopted-legacy-tag", Id: 101}) + delete(peer.tags, second.Tag) + peer.tags["n"+strconv.Itoa(*second.NodeID)+"-"+second.Tag] = 102 + + const email = "protocol-default-create" + if _, err := (&ClientService{}).Create(&InboundService{}, &ClientCreatePayload{ + Client: model.Client{Email: email, Enable: true}, InboundIds: ids, + }); err != nil { + t.Fatal(err) + } + peer.mu.Lock() + adds := slices.Clone(peer.adds) + peer.mu.Unlock() + if len(adds) != 1 || !slices.Equal(adds[0].InboundIds, []int{101, 102}) || !tc.check(adds[0].Client) { + t.Fatalf("expected one acknowledged %s add with generated credentials and both mapped IDs", tc.protocol) + } + want := adds[0].Client + for _, ib := range inbounds { + local, ok := settingsClient(t, ib.Id, email) + if !ok || local.ID != want.ID || local.Secret != want.Secret || local.Password != want.Password { + t.Fatalf("grouped RPC changed the local %s credentials for inbound %d", tc.protocol, ib.Id) + } + } + }) + } +} + +func groupedRecoveryClient(email string) model.Client { + return model.Client{ + Email: email, Enable: true, ID: "bbbbbbbb-1111-2222-3333-555555555555", SubID: email, + } +} + +func wantGroupedOutcome(t *testing.T, svc *ClientService, nodeID int, status, reason string) { + t.Helper() + res := svc.NodeApplyResponse() + want := []ClientNodeApplyOutcome{{NodeID: nodeID, Status: status, Reason: reason}} + if res == nil || res.NodePending != (status == "pending") || !slices.Equal(res.NodeResults, want) { + t.Fatalf("node outcome = %+v, want %v", res, want) + } +} + +func groupedDirtyGeneration(t *testing.T, nodeID int) int64 { + t.Helper() + _, _, dirty, generation, err := (&NodeService{}).NodeSyncState(nodeID) + if err != nil || !dirty || generation <= 0 { + t.Fatalf("node dirty=%t generation=%d err=%v", dirty, generation, err) + } + return generation +} + +func assertGroupedRecovery(t *testing.T, peer *groupedCreatePeer, node *model.Node, remote *runtime.Remote, inbounds []*model.Inbound, addCount int, wantUpdates []int) { + t.Helper() + svc := &InboundService{} + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + for range 2 { + if err := svc.ReconcileNode(ctx, remote, node); err != nil { + t.Fatal(err) + } + } + peer.mu.Lock() + defer peer.mu.Unlock() + slices.Sort(peer.updates) + if len(peer.adds) != addCount || !slices.Equal(peer.updates, wantUpdates) { + t.Fatalf("add RPCs=%d, repaired IDs=%v, want %d and %v", len(peer.adds), peer.updates, addCount, wantUpdates) + } + for _, ib := range inbounds { + master := settingsClientEmails(t, ib.Id) + var doc struct{ Clients []model.Client } + if err := json.Unmarshal([]byte(peer.settings[peer.tags[ib.Tag]]), &doc); err != nil { + t.Fatal(err) + } + if got := emailsOf(doc.Clients); !slices.Equal(got, master) { + t.Fatalf("node inbound %q has %v, master has %v", ib.Tag, got, master) + } + } +} + +func setupGroupedCreatePeer(t *testing.T) (*groupedCreatePeer, *model.Node, []*model.Inbound, *runtime.Remote) { + t.Helper() + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + peer := &groupedCreatePeer{tags: map[string]int{}, settings: map[int]string{}} + srv := httptest.NewServer(http.HandlerFunc(peer.serve)) + t.Cleanup(srv.Close) + nodeHTTP := &fakeNodeHTTP{srv: srv, tags: peer.tags} + first := realNodeInbound(t, nodeHTTP, 46201, nil) + second := nodeInbound(t, *first.NodeID, 46202, nil) + peer.tags[second.Tag] = 102 + var node model.Node + if err := database.GetDB().First(&node, *first.NodeID).Error; err != nil { + t.Fatal(err) + } + rt, err := mgr.RuntimeFor(&node.Id) + if err != nil { + t.Fatal(err) + } + remote, ok := rt.(*runtime.Remote) + if !ok { + t.Fatalf("runtime = %T, want actual remote", rt) + } + inbounds := []*model.Inbound{first, second} + for _, inbound := range inbounds { + remote.RecordAdoptedInbound(inbound) + peer.settings[peer.tags[inbound.Tag]] = inbound.Settings + } + return peer, &node, inbounds, remote +} + +func TestGroupedCreateReconcilesUnsentRebasedSettings(t *testing.T) { + peer, node, inbounds, remote := setupGroupedCreatePeer(t) + svc := (&ClientService{}).TrackNodeApplies() + inboundSvc := &InboundService{} + changed := inbounds[0] + client := model.Client{ + Email: "group-rebased@x", Enable: true, + ID: "bbbbbbbb-1111-2222-3333-555555555555", SubID: "group-rebased", + } + db := database.GetDB() + var inject sync.Once + const callback = "test:concurrent-settings-before-grouped-write" + if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) { + read, ok := tx.Statement.Dest.(*model.Inbound) + if ok && read.Id == changed.Id && read.Settings == changed.Settings { + // VLESS preparation omits settings. The first full read is under the mutation lock. + inject.Do(func() { + _ = tx.AddError(db.Model(&model.Inbound{}).Where("id = ?", changed.Id). + Update("settings", `{"clients":[],"decryption":"none"}`).Error) + }) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) }) + _, createErr := svc.Create(inboundSvc, &ClientCreatePayload{ + Client: client, InboundIds: []int{changed.Id, inbounds[1].Id}, + }) + if createErr != nil { + t.Fatal(createErr) + } + for _, inbound := range inbounds { + if c, ok := settingsClient(t, inbound.Id, client.Email); !ok || c.ID != client.ID { + t.Fatalf("master lost grouped client in inbound %d: %+v", inbound.Id, c) + } + } + stored, err := inboundSvc.GetInbound(changed.Id) + if err != nil || !strings.Contains(stored.Settings, `"decryption": "none"`) { + t.Fatalf("master lost concurrent settings change: %+v, %v", stored, err) + } + peer.mu.Lock() + adds := slices.Clone(peer.adds) + delivered := peer.settings[101] + peer.mu.Unlock() + if len(adds) != 1 || !slices.Equal(adds[0].InboundIds, []int{101, 102}) || adds[0].Client.Email != client.Email || + strings.Contains(delivered, "decryption") || !strings.Contains(delivered, client.Email) { + t.Fatalf("grouped add was not limited to the new client: %+v, peer settings %s", adds, delivered) + } + for range 2 { + if err := inboundSvc.ReconcileNode(t.Context(), remote, node); err != nil { + t.Fatal(err) + } + } + peer.mu.Lock() + defer peer.mu.Unlock() + if !slices.Equal(peer.updates, []int{101}) || peer.settings[101] != stored.Settings { + t.Fatalf("reconcile updates=%v settings=%s, want exactly one repair of inbound 101", peer.updates, peer.settings[101]) + } +} diff --git a/internal/web/service/client_crud.go b/internal/web/service/client_crud.go index 147737b0e..97e00b309 100644 --- a/internal/web/service/client_crud.go +++ b/internal/web/service/client_crud.go @@ -1,6 +1,7 @@ package service import ( + "context" "encoding/base64" "encoding/json" "errors" @@ -203,6 +204,11 @@ func quotaDisabledEmails(tx *gorm.DB, within []string) ([]string, error) { // Create applies the client to every requested inbound: one failing inbound no // longer aborts the others, so the error can name several and needRestart holds. func (s *ClientService) Create(inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) { + return s.CreateWithContext(context.Background(), inboundSvc, payload) +} + +// CreateWithContext applies the request context to delivery after the local commits. +func (s *ClientService) CreateWithContext(ctx context.Context, inboundSvc *InboundService, payload *ClientCreatePayload) (bool, error) { if payload == nil { return false, common.NewError("empty payload") } @@ -315,23 +321,21 @@ 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 { - // Never on a failed create: this retrims the devices of an email that - // already existed, and a create the panel reported as failed must not. - return needRestart, fanoutErr - } - // nil means omitted and preserves the stored binding. - if client.ClientHostRuleIds != nil { - if err := database.GetDB().Model(&model.ClientRecord{}). + pushes := make([]queuedClientCreate, len(adds)) + needRestart, saveErr := s.fanoutInboundClientAdds(inboundSvc, adds, pushes) + // Finish create metadata before remote delivery can overlap a later rename. + if saveErr == nil && client.ClientHostRuleIds != nil { + saveErr = database.GetDB().Model(&model.ClientRecord{}). Where("email = ?", client.Email). - Update("client_host_rule_ids", model.EncodeClientHostRuleIds(client.ClientHostRuleIds)).Error; err != nil { - return needRestart, err - } + Update("client_host_rule_ids", model.EncodeClientHostRuleIds(client.ClientHostRuleIds)).Error } - return needRestart, s.setClientLimitHwidByEmail(client.Email, payload.LimitHwid) + if saveErr == nil { + saveErr = s.setClientLimitHwidByEmail(client.Email, payload.LimitHwid) + } + remoteRestart, pushErr := s.pushClientCreates(ctx, pushes) + return needRestart || remoteRestart, errors.Join(saveErr, pushErr) } // getInboundForClientCreate returns the settings blob only for protocols @@ -343,7 +347,7 @@ func getInboundForClientCreate(id int, generateSecret bool) (*model.Inbound, err } var inbound model.Inbound if err := database.GetDB().Select( - "id, protocol, enable, listen, CASE WHEN protocol IN ? THEN settings ELSE '' END AS settings", + "id, node_id, protocol, enable, listen, CASE WHEN protocol IN ? THEN settings ELSE '' END AS settings", protocolsWithSettings, ).First(&inbound, id).Error; err != nil { return nil, err @@ -357,8 +361,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 @@ -367,8 +372,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() { @@ -399,22 +405,64 @@ func fanoutInboundApplies(applies []inboundApply) (bool, error) { return needRestart.Load(), errors.Join(errs...) } -// fanoutInboundClientAdds applies the prepared create or attach to each inbound. -func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound) (bool, error) { +func (s *ClientService) fanoutInboundClientAdds(inboundSvc *InboundService, adds []*model.Inbound, pushes []queuedClientCreate) (bool, error) { applies := make([]inboundApply, 0, len(adds)) - for _, add := range adds { - applies = append(applies, inboundApply{id: add.Id, run: func() (bool, error) { - return s.addInboundClient(inboundSvc, add, true) + for i, add := range adds { + var queued *queuedClientCreate + if pushes != nil { + queued = &pushes[i] + } + applies = append(applies, inboundApply{id: add.Id, nodeID: add.NodeID, run: func() (bool, error) { + return s.addInboundClient(inboundSvc, add, true, queued) }}) } 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 } @@ -422,7 +470,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() { @@ -912,7 +964,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) }}) } @@ -1076,7 +1128,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 } @@ -1091,7 +1144,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. @@ -1114,6 +1167,18 @@ func (s *ClientService) Delete(inboundSvc *InboundService, id int, keepTraffic b } if err := runSerializedTx(func(tx *gorm.DB) error { + // A later create can commit while this delete's node turn is waiting. + var attached []int + if err := tx.Table("client_inbounds"). + Joins("JOIN clients ON clients.id = client_inbounds.client_id"). + Joins("JOIN inbounds ON inbounds.id = client_inbounds.inbound_id"). + Where("clients.id = ? OR clients.email = ?", id, existing.Email). + Limit(1).Pluck("client_inbounds.client_id", &attached).Error; err != nil { + return err + } + if len(attached) != 0 { + return nil + } if existing.Email != "" { if err := adjustGroupBaselinesForRemovedTraffic(tx, []string{existing.Email}); err != nil { return err @@ -1288,9 +1353,9 @@ 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) + return s.fanoutInboundClientAdds(inboundSvc, adds, nil) } func (s *ClientService) CreateOne(inboundSvc *InboundService, inboundId int, client model.Client) (bool, error) { @@ -1413,14 +1478,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 abb33309f..84413233b 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -135,18 +135,20 @@ 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 } - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { 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 { @@ -248,15 +250,13 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId // Persist the batch deletion atomically, serialized against the traffic poll // to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { + var purgeIPs []string for _, t := range targets { if t.emailShared || keepTraffic { continue } - if e := inboundSvc.DelClientIPs(tx, t.email); e != nil { - logger.Error("Error in delete client IPs") - return e - } + purgeIPs = append(purgeIPs, t.email) if len(t.email) > 0 { if e := inboundSvc.DelClientStat(tx, t.email); e != nil { logger.Error("Delete stats Data Error") @@ -264,6 +264,9 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId } } } + if e := inboundSvc.delClientIPsByEmails(tx, purgeIPs); e != nil { + return e + } if e := commitInboundClientSettings(tx, oldInbound, prevSettings); e != nil { return e } @@ -276,63 +279,52 @@ func (s *ClientService) delInboundClients(inboundSvc *InboundService, inboundId if err := s.ApplyInboundClientDelta(tx, inboundId, nil, detached); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return needRestart, txErr } - // Resolve the node push plan once for the whole batch instead of per email. - var nodeRt runtime.Runtime - nodePush := false 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 } - nodeRt, nodePush = rt, push - // Large batches collapse into one reconcile push rather than M deletes. - if nodePush && len(targets) > nodeBulkPushThreshold { - nodePush = false + if push && len(targets) <= nodeBulkPushThreshold { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { + for _, target := range targets { + if target.email == "" { + continue + } + 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 } - // Apply runtime deletes after commit — outside the serialized writer so a - // slow node call can't stall traffic accounting. - nodePushFailed := false for _, t := range targets { - if len(t.email) == 0 { + if t.email == "" || !t.needApiDel || !t.notDepleted { continue } - if oldInbound.NodeID == nil { - if t.needApiDel && t.notDepleted { - rt, rterr := inboundSvc.runtimeFor(oldInbound) - if rterr != nil { - needRestart = true - } else if err1 := rt.RemoveUser(context.Background(), oldInbound, t.email); err1 != nil { - if !strings.Contains(err1.Error(), fmt.Sprintf("User %s not found.", t.email)) { - needRestart = true - } - } else if endDroppedClientSessions(oldInbound) { - needRestart = true - } - } - } else if nodePush && !nodePushFailed { - // First failure ends the batch push; the reconcile converges the rest. - ctx, cancel := nodePushContext() - err1 := nodeRt.DeleteUser(ctx, oldInbound, t.email) - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", nodeRt.Name(), ":", err1) - nodePushFailed = true + rt, rterr := inboundSvc.runtimeFor(oldInbound) + if rterr != nil { + needRestart = true + } else if err := rt.RemoveUser(context.Background(), oldInbound, t.email); err != nil { + if !strings.Contains(err.Error(), fmt.Sprintf("User %s not found.", t.email)) { + needRestart = true } + } else if endDroppedClientSessions(oldInbound) { + needRestart = true } } - if nodePush && !nodePushFailed { - advancePushedInbound(nodeRt, prevSettings, string(newSettings), oldInbound) - } return needRestart, nil } @@ -404,14 +396,14 @@ func (s *ClientService) checkEmailsExistForClients(inboundSvc *InboundService, c return "", nil } -func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (bool, error) { - return s.addInboundClient(inboundSvc, data, false) +func (s *ClientService) AddInboundClient(inboundSvc *InboundService, data *model.Inbound) (restartNeeded bool, saveErr error) { + return s.addInboundClient(inboundSvc, data, false, nil) } -func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, gateFlow bool) (bool, error) { +func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model.Inbound, gateFlow bool, queued *queuedClientCreate) (restartNeeded bool, saveErr error) { defer InvalidateSubData() - lock := lockInbound(data.Id) - defer lock.Unlock() + mutation := beginInboundClientMutation(data.Id) + defer mutation.close() clients, err := inboundSvc.GetClients(data) if err != nil { @@ -466,6 +458,7 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model return false, common.NewError("Duplicate email:", existEmail) } + defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil { return false, err } @@ -616,7 +609,7 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model } needRestart := false - nextOrphanOffset := lock.orphanOffset + nextOrphanOffset := mutation.lock.orphanOffset prunedOrphans := false rt, push, _, perr := inboundSvc.nodePushPlan(oldInbound) @@ -626,7 +619,7 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model // Persist client stats + inbound atomically, serialized against the traffic // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { // lockInbound is per-inbound, so the pre-tx cross-inbound checks race // concurrent writers on other inbounds — re-run them in here (#6225). if oldInbound.Protocol == model.WireGuard || oldInbound.Protocol == model.AmneziaWG { @@ -656,7 +649,7 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model } } // Confirm absence in the writer so an earlier committed re-add survives. - compacted, next, err := compactAddOrphans(tx, oldClients, lock.orphanOffset) + compacted, next, err := compactAddOrphans(tx, oldClients, mutation.lock.orphanOffset) if err != nil { return err } @@ -684,14 +677,11 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, addedClients, nil); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return false, txErr } - lock.orphanOffset = nextOrphanOffset + mutation.lock.orphanOffset = nextOrphanOffset // Apply to the running runtime after commit — outside the serialized writer // so a slow node call can't stall traffic accounting. @@ -726,42 +716,57 @@ func (s *ClientService) addInboundClient(inboundSvc *InboundService, data *model } } } - } else { - // Large batches would be M sequential per-client RPCs; the inbound's saved - // settings already hold the final set, so mark dirty and let one reconcile - // push converge the node instead. - if push && len(clients) > nodeBulkPushThreshold { - push = false - } - for _, client := range clients { - // /clients/add on the node historically coerced enable=true; skip live - // push for disabled clients and leave dirty so reconcile converges. - if !client.Enable { - push = false - continue + } else if push && len(clients) <= nodeBulkPushThreshold { + if remote, ok := rt.(*runtime.Remote); ok && queued != nil && len(clients) == 1 { + if mutation.turn == nil || !clients[0].Enable { + s.recordClientNodeDeferred(oldInbound.NodeID) + } else { + mutation.unlock() + client := clients[0] + // Create already selected the effective addresses for this inbound. + client.AllowedIPsByInbound = nil + raw, err := json.Marshal(client) + if err != nil { + s.recordClientNodePush(*oldInbound.NodeID, true, runtime.ClientApplyResult{}, err) + return needRestart, nil + } + previous := *oldInbound + previous.Settings = prevSettings + pushed := *oldInbound + // The add RPC omits unrelated settings merged by the write transaction. + pushed.Settings = string(newSettings) + queued.prepare(mutation.turn, remote, &previous, &pushed, string(raw), prunedOrphans) + mutation.turn = nil } - if push { - ctx, cancel := nodePushContext() - err1 := rt.AddClient(ctx, oldInbound, client) - cancel() - if err1 != nil { - logger.Warning("Error in adding client on", rt.Name(), ":", err1) - push = false + return needRestart, nil + } + 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 + } + if !batch.acknowledge(rt.AddClient(ctx, oldInbound, client)) { + return false } } - } - // AddClient only pushed the new clients. Reconcile any orphan removals. - if push && !prunedOrphans { - advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + // AddClient only pushed the new clients. Reconcile any orphan removals. + if !prunedOrphans { + advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) + } + 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() - defer lockInbound(data.Id).Unlock() + mutation := beginInboundClientMutation(data.Id) + defer mutation.close() clients, err := inboundSvc.GetClients(data) if err != nil { @@ -782,6 +787,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo interfaceClients := settings["clients"].([]any) + defer s.recordClientNodeFailure(oldInbound.NodeID, &saveErr) if err := validateTuicClientEmails(oldInbound.Protocol, clients); err != nil { return false, err } @@ -1059,7 +1065,7 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo // Persist client stats + inbound atomically, serialized against the traffic // poll to avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + if txErr := mutation.commit(oldInbound, nodeClientDelta, func(tx *gorm.DB) error { // Same re-check-inside-the-writer rule as AddInboundClient (#6225): // the pre-tx pass can race a concurrent writer on another inbound. if oldInbound.Protocol == model.WireGuard { @@ -1165,9 +1171,6 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo if err := s.ApplyInboundClientDelta(tx, oldInbound.Id, changedClients, detachEmails); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) - } return nil }); txErr != nil { return false, txErr @@ -1217,16 +1220,18 @@ func (s *ClientService) UpdateInboundClient(inboundSvc *InboundService, data *mo } } } else if push { - ctx, cancel := nodePushContext() - err1 := rt.UpdateUser(ctx, oldInbound, oldEmail, clients[0]) - cancel() - if err1 != nil { - logger.Warning("Error in updating client on", rt.Name(), ":", err1) - } else { + 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 } @@ -1234,15 +1239,17 @@ 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() - defer lockInbound(inboundId).Unlock() + mutation := beginInboundClientMutation(inboundId) + defer mutation.close() oldInbound, err := inboundSvc.GetInbound(inboundId) if err != nil { 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 { @@ -1271,7 +1278,7 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo } } - if !found { + if !found && (!fullDelete || oldInbound.NodeID == nil) { return false, fmt.Errorf("%w for email: %s", ErrClientNotInInbound, email) } db := database.GetDB() @@ -1321,7 +1328,12 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo // Persist the deletion atomically, serialized against the traffic poll to // avoid the cross-transaction lock-order deadlock (runSerializedTx). - if txErr := runSerializedTx(func(tx *gorm.DB) error { + var pending []model.NodePendingClientDelete + work := nodeClientDelta + if fullDelete { + work = nodeFullClientDelete + } + if txErr := mutation.commit(oldInbound, work, func(tx *gorm.DB) error { if !emailShared && !keepTraffic { if e := inboundSvc.DelClientIPs(tx, email); e != nil { logger.Error("Error in delete client IPs") @@ -1340,8 +1352,9 @@ func (s *ClientService) DelInboundClientByEmail(inboundSvc *InboundService, inbo if err := s.ApplyInboundClientDelta(tx, inboundId, nil, []string{email}); err != nil { return err } - if oldInbound.NodeID != nil { - return (&NodeService{}).MarkNodeDirtyTx(tx, *oldInbound.NodeID) + if fullDelete { + pending, err = queueNodeClientDeletes(tx, oldInbound.NodeID, []string{email}) + return err } return nil }); txErr != nil { @@ -1387,19 +1400,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 { - ctx, cancel := nodePushContext() - var err1 error - if fullDelete { - err1 = rt.DeleteClient(ctx, email) - } else { - err1 = rt.DeleteUser(ctx, oldInbound, email) - } - cancel() - if err1 != nil { - logger.Warning("Error in deleting client on", rt.Name(), ":", err1) - } else { + mutation.push(s, rt, oldInbound, func(ctx context.Context, batch *nodeClientBatch) bool { + if fullDelete { + complete := len(pending) > 0 + for _, row := range pending { + result, attempted, err := applyNodeClientDelete(ctx, rt, row) + if !batch.acknowledge(result, err) { + return false + } + complete = complete && attempted + } + return complete + } + if !batch.acknowledge(rt.DeleteUser(ctx, oldInbound, email)) { + return false + } advancePushedInbound(rt, prevSettings, string(newSettings), oldInbound) - } + return true + }) + } else { + s.recordClientNodeDeferred(oldInbound.NodeID) } } } diff --git a/internal/web/service/client_ip_sync_postgres_test.go b/internal/web/service/client_ip_sync_postgres_test.go index 7fc575313..cec89d4d4 100644 --- a/internal/web/service/client_ip_sync_postgres_test.go +++ b/internal/web/service/client_ip_sync_postgres_test.go @@ -21,6 +21,12 @@ func TestClientIpSyncPostgres(t *testing.T) { {"exhaustion rollback", TestClientIpSyncCASExhaustionRollsBack}, {"concurrent writer", TestMergeInboundClientIps_RetriesAfterConcurrentWriter}, {"attribution unchanged", TestNodeClientIpCanonicalUnchangedSkipsUpsert}, + {"attribution batched refresh", TestNodeClientIpRefreshBatchesWrites}, + {"attribution concurrent merge", TestNodeClientIpBatchRetriesConcurrentChange}, + {"attribution rollback", TestNodeClientIpBatchRollsBackOnLaterFailure}, + {"shared descendant writers", TestConcurrentPolledReportsMergeMixedRowsForSharedDescendant}, + {"later CAS conflicts", TestNodeClientIpLaterBatchCASRollsBackBeforeRetry}, + {"attribution concurrent prune", TestPruneNodeClientIpsPreservesConcurrentRefresh}, {"remote ids", TestMergeInboundClientIps_CreatesNodeOnlyRowIgnoringRemoteId}, {"attribution round trip", TestRecordLocalClientIps_RoundTripByGuid}, {"attribution expiry", TestRecordLocalClientIps_MergesAndDropsStale}, diff --git a/internal/web/service/client_link.go b/internal/web/service/client_link.go index e457d830f..ddf69e9ac 100644 --- a/internal/web/service/client_link.go +++ b/internal/web/service/client_link.go @@ -106,7 +106,7 @@ func applyClientRecordMerge(row *model.ClientRecord, incoming *model.ClientRecor // SyncInbound makes the inbound's client records and links match clients // exactly: links for clients no longer in the set are removed. func (s *ClientService) SyncInbound(tx *gorm.DB, inboundId int, clients []model.Client) error { - return s.syncInboundClients(tx, inboundId, clients, nil, true) + return s.syncInboundClients(tx, inboundId, clients, nil, true, nil) } // withClientSyncSavepoint lets a caller continue only after a failed sync is undone. @@ -132,10 +132,14 @@ func withClientSyncSavepoint(tx *gorm.DB, sync func() error) (rejected, fatal er // the whole point being that a one-client edit must not rewrite the inbound's // entire membership set (#6252). func (s *ClientService) ApplyInboundClientDelta(tx *gorm.DB, inboundId int, changed []model.Client, detachEmails []string) error { - return s.syncInboundClients(tx, inboundId, changed, detachEmails, false) + return s.syncInboundClients(tx, inboundId, changed, detachEmails, false, nil) } -func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients []model.Client, detachEmails []string, prune bool) error { +type nodeInboundSyncResult struct { + detached []int +} + +func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients []model.Client, detachEmails []string, prune bool, node *nodeInboundSyncResult) error { if err := validateClientsRenewal(clients); err != nil { return err } @@ -239,6 +243,9 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ } before := *row + if node != nil { + incoming.Comment = before.Comment + } applyClientRecordMerge(row, incoming) _, outranked := onLowerTunnel[row.Id] _, wireguardOutranked := onLowerWireguard[row.Id] @@ -255,6 +262,10 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ } // Keep GORM's save hooks and serializers while writing the agreed timestamp once. save := tx.Session(&gorm.Session{NowFunc: func() time.Time { return time.UnixMilli(preservedUpdatedAt) }}) + if node != nil { + // An operator can change the note while this node merge is open. + save = save.Omit("Comment") + } if err := save.Save(row).Error; err != nil { return err } @@ -303,7 +314,7 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ wantedIds = append(wantedIds, id) } - relinked, err := s.reconcileInboundLinks(tx, inboundId, wantedFlow, wantedIds, detachEmails, prune) + relinked, detached, err := s.reconcileInboundLinks(tx, inboundId, inbound.NodeID, wantedFlow, wantedIds, detachEmails, prune) if err != nil { return err } @@ -354,22 +365,25 @@ func (s *ClientService) syncInboundClients(tx *gorm.DB, inboundId int, clients [ // A failed validation can roll back the row while the outer transaction commits. liftTombstonesOnCommit(tx, toCreate) + if node != nil { + node.detached = detached + } return nil } // reconcileInboundLinks writes only the client_inbounds rows that differ and returns -// their clients. prune also removes links absent from wantedFlow, as only a full sync may. -func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) ([]int, error) { +// affected and detached client IDs. Only full sync prunes links absent from wantedFlow. +func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, nodeID *int, wantedFlow map[int]string, wantedIds []int, detachEmails []string, prune bool) (relinked, detached []int, err error) { var current []model.ClientInbound if prune { if err := tx.Where("inbound_id = ?", inboundId).Find(¤t).Error; err != nil { - return nil, err + return nil, nil, err } } else { for _, batch := range chunkInts(wantedIds, sqlInChunk) { var rows []model.ClientInbound if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch).Find(&rows).Error; err != nil { - return nil, err + return nil, nil, err } current = append(current, rows...) } @@ -397,7 +411,7 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wanted for _, batch := range chunkStrings(detachEmails, sqlInChunk) { var ids []int if err := tx.Model(&model.ClientRecord{}).Where("email IN ?", batch).Pluck("id", &ids).Error; err != nil { - return nil, err + return nil, nil, err } for _, id := range ids { if _, keep := wantedFlow[id]; !keep { @@ -421,12 +435,12 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wanted // A restored, still-attached client must lose its legacy mark before it loses its link. if err := clearSyncOrphanMarks(tx, toDelete); err != nil { - return nil, err + return nil, nil, err } for _, batch := range chunkInts(toDelete, sqlInChunk) { if err := tx.Where("inbound_id = ? AND client_id IN ?", inboundId, batch). Delete(&model.ClientInbound{}).Error; err != nil { - return nil, err + return nil, nil, err } } for flow, ids := range toUpdate { @@ -434,7 +448,7 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wanted if err := tx.Model(&model.ClientInbound{}). Where("inbound_id = ? AND client_id IN ?", inboundId, batch). Update("flow_override", flow).Error; err != nil { - return nil, err + return nil, nil, err } } } @@ -445,18 +459,31 @@ func (s *ClientService) reconcileInboundLinks(tx *gorm.DB, inboundId int, wanted Columns: []clause.Column{{Name: "client_id"}, {Name: "inbound_id"}}, DoUpdates: clause.AssignmentColumns([]string{"flow_override"}), }).CreateInBatches(toInsert, 200).Error; err != nil { - return nil, err + return nil, nil, err + } + if nodeID != nil { + reattached := make([]int, 0, len(toInsert)) + for _, link := range toInsert { + reattached = append(reattached, link.ClientId) + } + for _, batch := range chunkInts(reattached, sqlInChunk) { + emails := tx.Model(&model.ClientRecord{}).Select("email").Where("id IN ?", batch) + if err := tx.Where("node_id = ? AND email IN (?)", *nodeID, emails). + Delete(&model.NodePendingClientDelete{}).Error; err != nil { + return nil, nil, err + } + } } } - relinked := append([]int(nil), toDelete...) + relinked = append([]int(nil), toDelete...) for _, ids := range toUpdate { relinked = append(relinked, ids...) } for _, link := range toInsert { relinked = append(relinked, link.ClientId) } - return relinked, nil + return relinked, toDelete, nil } // keepLinkOwnedFields undoes the merge of the record fields one inbound cannot decide 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 new file mode 100644 index 000000000..244f7a64c --- /dev/null +++ b/internal/web/service/client_node_dispatch.go @@ -0,0 +1,266 @@ +package service + +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" +) + +var ( + nodeConfigDispatchMu sync.Mutex + nodeConfigDispatch = map[int]*nodeConfigQueue{} +) + +type nodeConfigQueue struct { + groups list.List + reconciles int + live int + changed chan struct{} +} + +// Inbounds in the same group can push concurrently. A node-wide operation +// waits for the preceding group to drain before the next group can run. +type nodeConfigGroup struct { + position *list.Element + exclusive bool + inbounds map[int]*list.List +} + +type nodeConfigTurn struct { + nodeID int + inboundID int + queue *nodeConfigQueue + group *nodeConfigGroup + position *list.Element + ready chan struct{} + work nodeConfigWork +} + +type nodeConfigWork uint8 + +const ( + nodeClientDelta nodeConfigWork = iota + nodeFullClientDelete + nodeFullReconcile +) + +func reserveNodeConfigTurn(nodeID, inboundID int, work nodeConfigWork) *nodeConfigTurn { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + q := nodeConfigDispatch[nodeID] + if q == nil { + q = &nodeConfigQueue{} + nodeConfigDispatch[nodeID] = q + } + // A reconcile can see later commits. It converges overlapping deltas, + // while node-wide deletes still run because they also remove client records. + if q.reconciles > 0 && work == nodeClientDelta { + return nil + } + exclusive := work != nodeClientDelta + if exclusive { + inboundID = 0 + } + var group *nodeConfigGroup + if last := q.groups.Back(); last != nil { + group = last.Value.(*nodeConfigGroup) + } + if group == nil || group.exclusive != exclusive { + group = &nodeConfigGroup{exclusive: exclusive, inbounds: make(map[int]*list.List)} + group.position = q.groups.PushBack(group) + } + lane := group.inbounds[inboundID] + if lane == nil { + lane = &list.List{} + group.inbounds[inboundID] = lane + } + turn := &nodeConfigTurn{ + nodeID: nodeID, inboundID: inboundID, queue: q, group: group, ready: make(chan struct{}), work: work, + } + turn.position = lane.PushBack(turn) + if work == nodeFullReconcile { + q.reconciles++ + } + if q.groups.Front() == group.position && lane.Front() == turn.position { + close(turn.ready) + } + return turn +} + +func (t *nodeConfigTurn) wait(ctx context.Context) bool { + select { + case <-t.ready: + return ctx.Err() == nil + case <-ctx.Done(): + return false + } +} + +func (t *nodeConfigTurn) release() { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + if t.position == nil { + return + } + q, group := t.queue, t.group + if q.changed != nil { + close(q.changed) + q.changed = nil + } + lane := group.inbounds[t.inboundID] + wasReady := q.groups.Front() == group.position && lane.Front() == t.position + lane.Remove(t.position) + t.position = nil + if t.work == nodeFullReconcile { + q.reconciles-- + } + if front := lane.Front(); front != nil { + if wasReady { + close(front.Value.(*nodeConfigTurn).ready) + } + return + } + delete(group.inbounds, t.inboundID) + if len(group.inbounds) > 0 { + return + } + q.groups.Remove(group.position) + if next := q.groups.Front(); next == nil { + delete(nodeConfigDispatch, t.nodeID) + } else if wasReady { + for _, lane := range next.Value.(*nodeConfigGroup).inbounds { + close(lane.Front().Value.(*nodeConfigTurn).ready) + } + } +} + +func (q *nodeConfigQueue) changes() <-chan struct{} { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + if q.changed == nil { + q.changed = make(chan struct{}) + } + return q.changed +} + +func (q *nodeConfigQueue) acquireLive() bool { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + if q.live >= inboundFanoutConcurrency { + return false + } + q.live++ + return true +} + +func (q *nodeConfigQueue) releaseLive() { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + q.live-- +} + +type inboundClientMutation struct { + lock *inboundMutationLock + turn *nodeConfigTurn +} + +func beginInboundClientMutation(inboundID int) *inboundClientMutation { + return &inboundClientMutation{lock: lockInbound(inboundID)} +} + +func (m *inboundClientMutation) unlock() { + if m.lock != nil { + m.lock.Unlock() + m.lock = nil + } +} + +func (m *inboundClientMutation) close() { + m.unlock() + if m.turn != nil { + m.turn.release() + } +} + +func (m *inboundClientMutation) commit(inbound *model.Inbound, work nodeConfigWork, write func(*gorm.DB) error) error { + if inbound.NodeID == nil { + return runSerializedTx(write) + } + nodeID := *inbound.NodeID + 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 + } + return (&NodeService{}).MarkNodeDirtyTx(tx, nodeID) + }, 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 +} + +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. + if !m.turn.queue.acquireLive() { + s.recordClientNodePush(nodeID, true, runtime.ClientApplyResult{}, errClientNodePushBusy) + return + } + defer m.turn.queue.releaseLive() + ctx, cancel := nodePushContext() + defer cancel() + complete := false + defer func() { + if remote, ok := rt.(*runtime.Remote); ok && !complete && m.turn.work != nodeFullClientDelete { + remote.ForgetPushedInbound(inbound.Tag) + } + }() + 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 new file mode 100644 index 000000000..771867366 --- /dev/null +++ b/internal/web/service/client_node_order_test.go @@ -0,0 +1,734 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +type blockedClientPushRuntime struct { + fakeNodeRuntime + calls chan string + release <-chan struct{} + blockedEmail string + waitForTimeout bool + expired atomic.Bool +} + +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 runtime.ClientApplyResult{}, nil + } + if r.waitForTimeout { + if deadline, ok := ctx.Deadline(); !ok || time.Until(deadline) > nodeClientPushTimeout { + 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. + call, cancel := context.WithTimeout(ctx, nodeClientPushTimeout/2) + defer cancel() + <-call.Done() + r.expired.Store(errors.Is(call.Err(), context.DeadlineExceeded)) + return runtime.ClientApplyResult{}, call.Err() + } + select { + case <-r.release: + return runtime.ClientApplyResult{}, nil + case <-ctx.Done(): + return runtime.ClientApplyResult{}, ctx.Err() + } +} + +func (r *blockedClientPushRuntime) UpdateUser(_ context.Context, _ *model.Inbound, email string, client model.Client) (runtime.ClientApplyResult, error) { + r.calls <- "update " + email + " " + client.Comment + return runtime.ClientApplyResult{}, nil +} + +func (r *blockedClientPushRuntime) DeleteUser(_ context.Context, _ *model.Inbound, email string) (runtime.ClientApplyResult, error) { + r.calls <- "detach " + email + return runtime.ClientApplyResult{}, nil +} + +func (r *blockedClientPushRuntime) UpdateInbound(_ context.Context, _ *model.Inbound, inbound *model.Inbound) error { + r.calls <- "lifecycle " + inbound.Tag + return nil +} + +func setupClientNodeOrderDB(t *testing.T) { + t.Helper() + cleanup, err := testpg.IsolatePackage("client_node_order") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + setupBulkDB(t) + startSerializedWriter(t) +} + +func TestNodeClientMutationsCommitWhileAnEarlierPushIsBlocked(t *testing.T) { + for _, tc := range []struct { + name string + timeout bool + }{ + {name: "successful push"}, + {name: "ambiguous timeout", timeout: true}, + } { + t.Run(tc.name, func(t *testing.T) { + setupClientNodeOrderDB(t) + nodeID, _ := setupNodeRuntime(t) + release := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + const email = "ordered@example.test" + blocked := &blockedClientPushRuntime{ + calls: make(chan string, 8), release: release, blockedEmail: email, waitForTimeout: tc.timeout, + } + mgr := runtime.GetManager() + mgr.SetRuntimeOverride(nodeID, blocked) + ib := nodeInbound(t, nodeID, 46001, nil) + siblingInbound := nodeInbound(t, nodeID, 46003, nil) + controlNode := model.Node{Name: "control", Address: "127.0.0.1", Port: 2097, ApiToken: "token", Enable: true, Status: "online"} + if err := database.GetDB().Create(&controlNode).Error; err != nil { + t.Fatal(err) + } + control := &fakeNodeRuntime{} + mgr.SetRuntimeOverride(controlNode.Id, control) + other := nodeInbound(t, controlNode.Id, 46002, nil) + clientSvc, inboundSvc := &ClientService{}, &InboundService{} + client := model.Client{Email: email, ID: uuid.NewString(), Enable: true} + changed := client + changed.Comment = "committed update" + sibling := model.Client{Email: "control@example.test", ID: uuid.NewString(), Enable: true} + sameNode := model.Client{Email: "same-node@example.test", ID: uuid.NewString(), Enable: true} + data := func(inbound *model.Inbound, client model.Client) *model.Inbound { + return &model.Inbound{Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{client})} + } + addData, updateData, controlData := data(ib, client), data(ib, changed), data(other, sibling) + siblingData := data(siblingInbound, sameNode) + + var wg sync.WaitGroup + t.Cleanup(func() { + unblock() + wg.Wait() + }) + async := func(operation func() (bool, error)) <-chan error { + done := make(chan error, 1) + wg.Go(func() { + restart, err := operation() + if restart { + err = errors.Join(err, errors.New("requested a local restart for a remote mutation")) + } + done <- err + }) + return done + } + expectCall := func(want string) { + t.Helper() + select { + case got := <-blocked.calls: + if got != want { + t.Fatalf("node operation = %q, want %q", got, want) + } + case <-time.After(nodeClientPushTimeout + time.Second): + t.Fatalf("node never received %q", want) + } + } + waitSettings := func(id int, contains string, present bool) { + t.Helper() + start := time.Now() + for { + current, err := inboundSvc.GetInbound(id) + if err == nil && strings.Contains(current.Settings, contains) == present { + t.Logf("local commit observed after %s while first RPC was blocked", time.Since(start)) + return + } + if time.Since(start) >= time.Second { + t.Fatalf("local settings did not reach %q present=%t while first RPC was blocked (last read err=%v)", contains, present, err) + } + time.Sleep(5 * time.Millisecond) + } + } + + add := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, addData) }) + expectCall("add " + client.Email) + start := time.Now() + locked := make(chan time.Duration, 1) + wg.Go(func() { + start := time.Now() + lockInbound(ib.Id).Unlock() + locked <- time.Since(start) + }) + select { + case took := <-locked: + t.Logf("inbound mutation lock acquired in %s while first RPC was blocked", took) + case <-time.After(time.Second): + t.Fatal("first RPC still holds the inbound mutation lock") + } + writerStart := time.Now() + if err := runSerializedTx(func(*gorm.DB) error { return nil }); err != nil { + t.Fatal(err) + } + t.Logf("independent writer turn took %s while first RPC was blocked", time.Since(writerStart)) + update := async(func() (bool, error) { return clientSvc.UpdateInboundClient(inboundSvc, updateData, client.Email) }) + waitSettings(ib.Id, changed.Comment, true) + detach := async(func() (bool, error) { + return clientSvc.DelInboundClientByEmail(inboundSvc, ib.Id, client.Email, true, false) + }) + waitSettings(ib.Id, client.Email, false) + sameNodeDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, siblingData) }) + waitSettings(siblingInbound.Id, sameNode.Email, true) + expectCall("add " + sameNode.Email) + if err := waitTrafficWriterErr(t, sameNodeDone); err != nil { + t.Fatal(err) + } + controlDone := async(func() (bool, error) { return clientSvc.AddInboundClient(inboundSvc, controlData) }) + select { + case err := <-controlDone: + if err != nil || control.addClient.Load() != 1 { + t.Fatalf("control inbound did not complete independently: %v (pushes=%d)", err, control.addClient.Load()) + } + case <-time.After(time.Second): + t.Fatal("control inbound waited for unrelated node") + } + select { + case got := <-blocked.calls: + t.Fatalf("%q overtook the first RPC", got) + default: + } + unblock() + expectCall("update " + client.Email + " " + changed.Comment) + t.Logf("first RPC held its dispatch turn for %s", time.Since(start)) + if tc.timeout && !blocked.expired.Load() { + t.Fatal("the first push did not finish through its deadline") + } + expectCall("detach " + client.Email) + for i, done := range []<-chan error{add, update, detach} { + select { + case err := <-done: + if err != nil { + t.Fatal(fmt.Errorf("operation %d reported %w after commit", i, err)) + } + case <-time.After(time.Second): + t.Fatalf("operation %d did not complete", i) + } + } + if _, _, dirty, _, err := (&NodeService{}).NodeSyncState(nodeID); err != nil || !dirty { + t.Fatalf("node dirty=%t error=%v after committed client batch", dirty, err) + } + }) + } +} + +func TestNodeClientQueueTimeoutDefersCommittedDelta(t *testing.T) { + setupClientNodeOrderDB(t) + nodeID, fake := setupNodeRuntime(t) + inbound := nodeInbound(t, nodeID, 46004, nil) + first := reserveNodeConfigTurn(nodeID, inbound.Id, nodeClientDelta) + t.Cleanup(first.release) + + email := "wait-deadline@example.test" + data := &model.Inbound{Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{{ + Email: email, ID: uuid.NewString(), Enable: true, + }})} + inboundSvc, clientSvc := &InboundService{}, &ClientService{} + done := make(chan error, 1) + completed := make(chan struct{}) + t.Cleanup(func() { + first.release() + <-completed + }) + go func() { + defer close(completed) + _, err := clientSvc.AddInboundClient(inboundSvc, data) + done <- err + }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(nodeClientPushTimeout + 2*time.Second): + t.Fatal("client request waited for a dispatch turn past its deadline") + } + if fake.addClient.Load() != 0 { + t.Fatal("expired client push overtook the in-flight operation") + } + current, err := inboundSvc.GetInbound(inbound.Id) + if err != nil || !strings.Contains(current.Settings, email) { + t.Fatalf("expired queue wait lost the committed client: %v", err) + } + if _, _, dirty, _, err := (&NodeService{}).NodeSyncState(nodeID); err != nil || !dirty { + t.Fatalf("expired queue wait did not leave the node dirty: dirty=%v err=%v", dirty, err) + } + first.release() + next := reserveNodeConfigTurn(nodeID, inbound.Id, nodeClientDelta) + defer next.release() + select { + case <-next.ready: + default: + t.Fatal("expired dispatch turn blocked the next mutation") + } +} + +func TestTrafficDepletionWaitsForEarlierNodeClientPush(t *testing.T) { + setupClientNodeOrderDB(t) + nodeID, _ := setupNodeRuntime(t) + mgr := runtime.GetManager() + release := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + const email = "depleted-while-pushing@example.test" + blocked := &blockedClientPushRuntime{calls: make(chan string, 4), release: release, blockedEmail: email} + mgr.SetRuntimeOverride(nodeID, blocked) + ib := nodeInbound(t, nodeID, 46012, nil) + inboundSvc := &InboundService{} + client := model.Client{Email: email, ID: uuid.NewString(), Enable: true, TotalGB: 5} + add := &model.Inbound{Id: ib.Id, Protocol: ib.Protocol, Settings: clientsSettings(t, []model.Client{client})} + var wg sync.WaitGroup + t.Cleanup(func() { + unblock() + wg.Wait() + }) + addDone := make(chan error, 1) + wg.Go(func() { + _, err := (&ClientService{}).AddInboundClient(inboundSvc, add) + addDone <- err + }) + select { + case got := <-blocked.calls: + if got != "add "+client.Email { + t.Fatalf("first node operation = %q", got) + } + case <-time.After(3 * time.Second): + t.Fatal("node did not receive the add") + } + depletionDone := make(chan error, 1) + wg.Go(func() { + _, disabled, err := inboundSvc.AddTraffic(nil, []*xray.ClientTraffic{{Email: client.Email, Up: 10}}) + if !disabled { + err = errors.Join(err, errors.New("traffic did not disable the depleted client")) + } + depletionDone <- err + }) + deadline := time.Now().Add(time.Second) + for readTraffic(t, database.GetDB(), client.Email).Enable { + if time.Now().After(deadline) { + t.Fatal("depletion did not commit while the add was blocked") + } + time.Sleep(5 * time.Millisecond) + } + select { + case got := <-blocked.calls: + t.Fatalf("node operation %q overtook the pending add", got) + case <-time.After(100 * time.Millisecond): + } + unblock() + select { + case got := <-blocked.calls: + if got != "lifecycle "+ib.Tag { + t.Fatalf("second node operation = %q, want the depletion update", got) + } + case <-time.After(time.Second): + t.Fatal("node did not receive the depletion update") + } + for _, done := range []<-chan error{addDone, depletionDone} { + if err := waitTrafficWriterErr(t, done); err != nil { + t.Fatal(err) + } + } +} + +func TestReconcileDoesNotOvertakeCommittedClientState(t *testing.T) { + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + const tag = "in-46011" + listStarted := make(chan struct{}) + releaseList := make(chan struct{}) + release := sync.OnceFunc(func() { close(releaseList) }) + var lists atomic.Int32 + pushedSettings := make(chan string, 4) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var obj any + switch r.URL.Path { + case "/panel/api/inbounds/list": + if lists.Add(1) == 1 { + close(listStarted) + select { + case <-r.Context().Done(): + return + case <-releaseList: + } + } + obj = []map[string]any{{"id": 1, "tag": tag}} + case "/panel/api/inbounds/update/1": + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + pushedSettings <- r.Form.Get("settings") + default: + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) + })) + t.Cleanup(server.Close) + t.Cleanup(release) + + node := reconcileTestNode(t, server, "reconcile-overlap", "all", nil) + remote := runtime.NewRemote(node, nil) + fast := &fakeNodeRuntime{} + mgr.SetRuntimeOverride(node.Id, fast) + ib := nodeInbound(t, node.Id, 46011, nil) + clientSvc, inboundSvc, nodeSvc := &ClientService{}, &InboundService{}, &NodeService{} + // Exercise generation ordering even when the previous timestamp is ahead of the clock. + oldGeneration := time.Now().Add(time.Minute).UnixMilli() + if err := database.GetDB().Model(node).Updates(map[string]any{ + "config_dirty": true, "config_dirty_at": oldGeneration, + }).Error; err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + reconciled := make(chan error, 1) + go func() { reconciled <- inboundSvc.ReconcileNode(ctx, remote, node) }() + waitTrafficWriterSignal(t, listStarted, "reconcile never reached the remote list") + + client := model.Client{Email: "during-reconcile@example.test", ID: uuid.NewString(), Enable: true} + if needRestart, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: ib.Id, Protocol: ib.Protocol, Settings: clientsSettings(t, []model.Client{client}), + }); needRestart || err != nil { + t.Fatalf("add during reconcile: restart=%t err=%v", needRestart, err) + } + if got := fast.addClient.Load(); got != 0 { + t.Fatalf("%d incremental pushes overlapped a reconcile of older settings", got) + } + release() + if err := waitTrafficWriterErr(t, reconciled); err != nil { + t.Fatal(err) + } + select { + case pushed := <-pushedSettings: + if strings.Contains(pushed, client.Email) { + t.Fatalf("first reconcile should still carry the pre-add settings, got %s", pushed) + } + default: + t.Fatal("first reconcile did not push the captured configuration") + } + + if err := nodeSvc.ClearNodeDirty(node.Id, oldGeneration); err != nil { + t.Fatal(err) + } + _, _, dirty, generation, err := nodeSvc.NodeSyncState(node.Id) + if err != nil || !dirty || generation <= oldGeneration { + t.Fatalf("new generation lost after stale reconcile: dirty=%t generation=%d previous=%d err=%v", dirty, generation, oldGeneration, err) + } + if err := inboundSvc.ReconcileNode(ctx, remote, node); err != nil { + t.Fatal(err) + } + select { + case pushed := <-pushedSettings: + if !strings.Contains(pushed, client.Email) { + t.Fatalf("next reconcile did not deliver the committed client: %s", pushed) + } + default: + t.Fatal("next reconcile did not push the new configuration") + } +} + +func TestNodeWideDeleteSkipsReattachmentSentByQueuedReconcile(t *testing.T) { + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + const primaryTag, blockerTag, recreatedTag = "in-46013", "in-46014", "in-46015" + const email = "recreated@example.test" + firstPush := make(chan struct{}) + releaseFirstPush := make(chan struct{}) + release := sync.OnceFunc(func() { close(releaseFirstPush) }) + var hasClient atomic.Bool + hasClient.Store(true) + var adds, deletes, blockerUpdates, recreatedUpdates atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + var obj any + switch r.URL.Path { + case "/panel/api/inbounds/list": + obj = []map[string]any{{"id": 1, "tag": primaryTag}, {"id": 2, "tag": blockerTag}, {"id": 3, "tag": recreatedTag}} + case "/panel/api/clients/add": + if adds.Add(1) == 1 { + close(firstPush) + select { + case <-r.Context().Done(): + return + case <-releaseFirstPush: + } + } + case "/panel/api/inbounds/update/1": + case "/panel/api/inbounds/update/3": + recreatedUpdates.Add(1) + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + hasClient.Store(strings.Contains(r.Form.Get("settings"), "recreated configuration")) + case "/panel/api/inbounds/update/2": + blockerUpdates.Add(1) + case "/panel/api/clients/del/" + email: + deletes.Add(1) + hasClient.Store(false) + default: + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(map[string]any{"success": true, "obj": obj}) + })) + t.Cleanup(server.Close) + var wg sync.WaitGroup + t.Cleanup(func() { + release() + wg.Wait() + }) + + node := reconcileTestNode(t, server, "reconcile-full-delete", "all", nil) + remote := runtime.NewRemote(node, nil) + mgr.SetRuntimeOverride(node.Id, remote) + client := model.Client{Email: email, ID: uuid.NewString(), SubID: "reconcile-recreated", Enable: true} + inbound := nodeInbound(t, node.Id, 46013, []model.Client{client}) + blocker := nodeInbound(t, node.Id, 46014, nil) + recreated := nodeInbound(t, node.Id, 46015, nil) + inboundSvc, clientSvc := &InboundService{}, &ClientService{} + addPayload := &model.Inbound{Id: blocker.Id, Protocol: model.VLESS, Settings: clientsSettings(t, []model.Client{{ + Email: "first-push@example.test", ID: uuid.NewString(), Enable: true, + }})} + async := func(run func() error) <-chan error { + done := make(chan error, 1) + wg.Go(func() { done <- run() }) + return done + } + waitUntil := func(message string, ready func() bool) { + t.Helper() + deadline := time.Now().Add(time.Second) + for !ready() { + if time.Now().After(deadline) { + t.Fatal(message) + } + time.Sleep(5 * time.Millisecond) + } + } + + added := async(func() error { + _, err := clientSvc.AddInboundClient(inboundSvc, addPayload) + return err + }) + waitTrafficWriterSignal(t, firstPush, "first AddClient never reached the node") + ctx, cancel := context.WithTimeout(t.Context(), 6*time.Second) + defer cancel() + reconciled := async(func() error { return inboundSvc.ReconcileNode(ctx, remote, node) }) + waitUntil("reconcile did not queue behind the first add", func() bool { + nodeConfigDispatchMu.Lock() + defer nodeConfigDispatchMu.Unlock() + queue := nodeConfigDispatch[node.Id] + return queue != nil && queue.reconciles > 0 + }) + deleted := async(func() error { + _, err := clientSvc.DelInboundClientByEmail(inboundSvc, inbound.Id, email, true, true) + return err + }) + waitUntil("full delete did not commit behind the reconcile", func() bool { + current, err := inboundSvc.GetInbound(inbound.Id) + return err == nil && !strings.Contains(current.Settings, email) + }) + client.Comment = "recreated configuration" + if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: recreated.Id, Protocol: recreated.Protocol, Settings: clientsSettings(t, []model.Client{client}), + }); err != nil { + t.Fatal(err) + } + release() + for _, done := range []<-chan error{added, reconciled, deleted} { + if err := waitTrafficWriterErr(t, done); err != nil { + t.Fatal(err) + } + } + if adds.Load() != 1 || deletes.Load() != 0 || !hasClient.Load() { + t.Fatalf("queued delete touched the reattachment: adds=%d deletes=%d client=%t", adds.Load(), deletes.Load(), hasClient.Load()) + } + if err := inboundSvc.ReconcileNode(ctx, remote, node); err != nil { + t.Fatal(err) + } + if !hasClient.Load() || recreatedUpdates.Load() != 1 { + t.Fatalf("reconcile unnecessarily re-sent the reattachment (pushes=%d)", recreatedUpdates.Load()) + } + if blockerUpdates.Load() != 1 { + t.Fatalf("reconcile re-sent unrelated inbound (pushes=%d)", blockerUpdates.Load()) + } +} + +func TestNodeWideDeleteRetriesAfterQueueExpiry(t *testing.T) { + for _, mode := range []string{"expired queue", "lost acknowledgment", "recreated client", "recreated on another node"} { + t.Run(mode, func(t *testing.T) { + setupClientNodeOrderDB(t) + mgr := useTestRuntimeManager(t) + const email = "durable-delete@example.test" + const tag = "in-46019" + var remoteRecord, remoteLink, dropAck atomic.Bool + var deletes atomic.Int32 + remoteRecord.Store(true) + remoteLink.Store(true) + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + response := map[string]any{"success": true} + switch r.URL.Path { + case "/panel/api/inbounds/list": + response["obj"] = []map[string]any{{"id": 1, "tag": tag}} + case "/panel/api/inbounds/update/1": + if err := r.ParseForm(); err != nil { + http.Error(w, err.Error(), http.StatusBadRequest) + return + } + remoteLink.Store(strings.Contains(r.Form.Get("settings"), email)) + case "/panel/api/clients/add": + remoteLink.Store(true) + remoteRecord.Store(true) + case "/panel/api/clients/del/" + email: + deletes.Add(1) + remoteLink.Store(false) + if !remoteRecord.Swap(false) { + response["success"] = false + response["msg"] = fmt.Sprintf("Error (client %q not found in any inbound or client record)", email) + } + if dropAck.CompareAndSwap(true, false) { + <-r.Context().Done() + return + } + default: + http.NotFound(w, r) + return + } + _ = json.NewEncoder(w).Encode(response) + })) + t.Cleanup(server.Close) + node := reconcileTestNode(t, server, "durable-client-delete", "all", nil) + remote := runtime.NewRemote(node, nil) + mgr.SetRuntimeOverride(node.Id, remote) + client := model.Client{Email: email, ID: uuid.NewString(), SubID: "durable-delete", Enable: true} + inbound := nodeInbound(t, node.Id, 46019, []model.Client{client}) + inboundSvc, clientSvc := &InboundService{}, &ClientService{} + record := lookupClientRecord(t, email) + + if mode == "expired queue" { + earlier := reserveNodeConfigTurn(node.Id, inbound.Id, nodeClientDelta) + defer earlier.release() + start := time.Now() + if _, err := clientSvc.Delete(inboundSvc, record.Id, false); err != nil { + t.Fatal(err) + } + if elapsed := time.Since(start); elapsed >= 2*nodeClientPushTimeout || deletes.Load() != 0 { + t.Fatalf("delete ignored its queue budget: elapsed=%v RPCs=%d", elapsed, deletes.Load()) + } + earlier.release() + } else { + if err := database.GetDB().Model(node).Update("status", "offline").Error; err != nil { + t.Fatal(err) + } + if _, err := clientSvc.Delete(inboundSvc, record.Id, false); err != nil { + t.Fatal(err) + } + if err := database.GetDB().Model(node).Update("status", "online").Error; err != nil { + t.Fatal(err) + } + } + + if _, err := clientSvc.GetRecordByEmail(nil, email); !errors.Is(err, gorm.ErrRecordNotFound) { + t.Fatalf("master still has the deleted record: %v", err) + } + if !remoteRecord.Load() || !remoteLink.Load() { + t.Fatal("fixture deleted the node client before delivery") + } + wantCalls := int32(1) + var otherNode *model.Node + var otherInbound *model.Inbound + var otherRuntime *fakeNodeRuntime + if mode == "recreated on another node" { + otherNode = &model.Node{Name: "other-delete-node", Address: "127.0.0.1", Port: 2096, ApiToken: "tok", Enable: true, Status: "online"} + if err := database.GetDB().Create(otherNode).Error; err != nil { + t.Fatal(err) + } + otherRuntime = &fakeNodeRuntime{} + mgr.SetRuntimeOverride(otherNode.Id, otherRuntime) + otherInbound = nodeInbound(t, otherNode.Id, 46020, nil) + client.ID = uuid.NewString() + if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: otherInbound.Id, Protocol: otherInbound.Protocol, Settings: clientsSettings(t, []model.Client{client}), + }); err != nil { + t.Fatal(err) + } + if got := lookupClientRecord(t, email); got.Id == record.Id { + t.Fatal("test did not create a new client incarnation on the other node") + } + var pending int64 + if err := database.GetDB().Model(&model.NodePendingClientDelete{}).Where("node_id = ? AND email = ?", node.Id, email).Count(&pending).Error; err != nil || pending != 1 { + t.Fatalf("recreation on another node must keep the original pending delete: %d (%v)", pending, err) + } + } + if mode == "recreated client" { + client.ID = uuid.NewString() + if _, err := clientSvc.AddInboundClient(inboundSvc, &model.Inbound{ + Id: inbound.Id, Protocol: inbound.Protocol, Settings: clientsSettings(t, []model.Client{client}), + }); err != nil { + t.Fatal(err) + } + if got := lookupClientRecord(t, email); got.Id == record.Id { + t.Fatal("test did not create a new client incarnation") + } + wantCalls = 0 + } + if mode == "lost acknowledgment" { + dropAck.Store(true) + ctx, cancel := context.WithTimeout(t.Context(), 500*time.Millisecond) + err := inboundSvc.ReconcileNode(ctx, remote, node) + cancel() + if !errors.Is(err, context.DeadlineExceeded) || remoteRecord.Load() || remoteLink.Load() { + t.Fatalf("expected remote commit with an uncertain reply: %v", err) + } + wantCalls = 2 + } + if err := inboundSvc.ReconcileNode(t.Context(), remote, node); err != nil { + t.Fatal(err) + } + wantPresent := mode == "recreated client" + if deletes.Load() != wantCalls || remoteRecord.Load() != wantPresent || remoteLink.Load() != wantPresent { + t.Fatalf("node after replay: RPCs=%d record=%v membership=%v", deletes.Load(), remoteRecord.Load(), remoteLink.Load()) + } + if otherNode != nil { + current, err := inboundSvc.GetInbound(otherInbound.Id) + if err != nil || !strings.Contains(current.Settings, email) { + t.Fatalf("reconcile changed the other node's desired client: %v", err) + } + if otherRuntime.addClient.Load() != 1 || otherRuntime.deleteClient.Load() != 0 { + t.Fatalf("other node RPCs: adds=%d deletes=%d", otherRuntime.addClient.Load(), otherRuntime.deleteClient.Load()) + } + if got := lookupClientRecord(t, email); got.Id == record.Id { + t.Fatal("reconcile did not preserve the new client record") + } + } + var pending int64 + if err := database.GetDB().Model(&model.NodePendingClientDelete{}).Where("node_id = ?", node.Id).Count(&pending).Error; err != nil || pending != 0 { + t.Fatalf("pending deletes after reconciliation: %d (%v)", pending, err) + } + }) + } +} diff --git a/internal/web/service/client_node_push_test.go b/internal/web/service/client_node_push_test.go index 11119848f..ed2c52513 100644 --- a/internal/web/service/client_node_push_test.go +++ b/internal/web/service/client_node_push_test.go @@ -1,11 +1,16 @@ package service import ( + "fmt" + "os" + "path/filepath" + "sync" "testing" "time" "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" ) // TestResetTrafficAcrossNodesPushesConcurrently covers the panel's per-client @@ -73,12 +78,11 @@ func TestNodePushGivesUpBeforeTheRemoteTimeout(t *testing.T) { // TestBulkDeleteStopsPushingToAHungNode pins the batch circuit-break: once one // push times out, the rest of the batch defers to the reconcile as well. func TestBulkDeleteStopsPushingToAHungNode(t *testing.T) { - setupBulkDB(t) - startSerializedWriter(t) + setupClientNodeOrderDB(t) useTestRuntimeManager(t) f := newFakeNodeHTTP(t) - realNodeInbound(t, f, 53200, []model.Client{ + ib := realNodeInbound(t, f, 53200, []model.Client{ {Email: "b1@x", ID: "66666666-1111-2222-3333-444444444441", SubID: "sub-b1", Enable: true}, {Email: "b2@x", ID: "66666666-1111-2222-3333-444444444442", SubID: "sub-b2", Enable: true}, {Email: "b3@x", ID: "66666666-1111-2222-3333-444444444443", SubID: "sub-b3", Enable: true}, @@ -96,4 +100,178 @@ func TestBulkDeleteStopsPushingToAHungNode(t *testing.T) { if elapsed >= 2*nodeClientPushTimeout { t.Fatalf("deleting 3 clients took %v against a hung node, want a single %v deadline, not one per client", elapsed, nodeClientPushTimeout) } + if err := database.CloseDB(); err != nil { + t.Fatal(err) + } + if err := database.InitDB(filepath.Join(os.Getenv("XUI_DB_FOLDER"), "x-ui.db")); err != nil { + t.Fatal(err) + } + f.setHold(false) + var node model.Node + if err := database.GetDB().First(&node, *ib.NodeID).Error; err != nil { + t.Fatal(err) + } + if err := (&InboundService{}).ReconcileNode(t.Context(), runtime.NewRemote(&node, nil), &node); err != nil { + t.Fatal(err) + } + if got := f.hitCount("/clients/del/"); got != 4 { + 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_portable.go b/internal/web/service/client_portable.go index 64c258a9c..a102212c7 100644 --- a/internal/web/service/client_portable.go +++ b/internal/web/service/client_portable.go @@ -314,9 +314,9 @@ func (s *ClientService) DeleteOrphans() (int, error) { if e := tx.Where("email IN ?", batch).Delete(&xray.ClientTraffic{}).Error; e != nil { return e } - if e := tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error; e != nil { - return e - } + } + if e := (&InboundService{}).delClientIPsByEmails(tx, emails); e != nil { + return e } if e := clearGlobalTraffic(tx, emails...); e != nil { return e diff --git a/internal/web/service/client_sync_orphan.go b/internal/web/service/client_sync_orphan.go index 5e73d8b42..4010cc0ad 100644 --- a/internal/web/service/client_sync_orphan.go +++ b/internal/web/service/client_sync_orphan.go @@ -25,13 +25,19 @@ func clientRecordExists(tx *gorm.DB, email string) bool { return n > 0 } -func markSyncOrphan(tx *gorm.DB, email string, nodeID int, nowMs int64) error { - if email == "" { - return nil +func markDetachedSyncOrphans(tx *gorm.DB, ids []int, nodeID int, nowMs int64) (bool, error) { + marked := false + for _, batch := range chunkInts(ids, sqlInChunk) { + result := tx.Model(&model.ClientRecord{}). + Where("id IN ? AND email <> '' AND sync_orphaned_at = 0", batch). + Where("NOT EXISTS (SELECT 1 FROM client_inbounds WHERE client_inbounds.client_id = clients.id)"). + Updates(map[string]any{"sync_orphaned_at": nowMs, "sync_orphaned_by": nodeID}) + if result.Error != nil { + return false, result.Error + } + marked = marked || result.RowsAffected > 0 } - return tx.Model(&model.ClientRecord{}). - Where("email = ? AND sync_orphaned_at = 0", email). - Updates(map[string]any{"sync_orphaned_at": nowMs, "sync_orphaned_by": nodeID}).Error + return marked, nil } // A client that is attached again is not orphaned, whatever an earlier merge @@ -95,7 +101,7 @@ func (s *ClientService) ReapSyncOrphans() (int, error) { if err := tx.Where("email IN ?", batch).Delete(&model.NodeClientTraffic{}).Error; err != nil { return err } - return tx.Where("client_email IN ?", batch).Delete(&model.InboundClientIps{}).Error + return (&InboundService{}).delClientIPsByEmails(tx, batch) }); err != nil { return reaped, err } 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.go b/internal/web/service/inbound.go index 4761e279d..9097b5664 100644 --- a/internal/web/service/inbound.go +++ b/internal/web/service/inbound.go @@ -199,6 +199,32 @@ func (s *InboundService) GetInbounds(userId int) ([]*model.Inbound, error) { return inbounds, nil } +// InboundClientStatsOverLimit probes direct stats and eligible sibling counters +// without fetching inbound settings or materializing stats. +func (s *InboundService) InboundClientStatsOverLimit(userID, limit int) (bool, error) { + var count int + // Exact email matches include every row eligible for backfill. Case folding + // can only reduce the number actually appended by backfillClientStats. + err := database.GetDB().Raw(` + SELECT COUNT(*) FROM ( + SELECT 1 + FROM inbounds AS ib + JOIN client_traffics AS stats ON stats.inbound_id = ib.id + WHERE ib.user_id = ? + UNION ALL + SELECT 1 + FROM inbounds AS ib + JOIN client_inbounds AS link ON link.inbound_id = ib.id + JOIN clients AS client ON client.id = link.client_id + JOIN client_traffics AS stats ON stats.email = client.email + WHERE ib.user_id = ? AND client.email <> '' + AND (stats.inbound_id <> ib.id OR stats.inbound_id IS NULL) + LIMIT ? + ) AS candidate_stats + `, userID, userID, limit+1).Row().Scan(&count) + return count > limit, err +} + func (s *InboundService) getInboundsFromDB(db *gorm.DB, userId int) ([]*model.Inbound, error) { var inbounds []*model.Inbound err := db.Model(model.Inbound{}).Where("user_id = ?", userId).Order("id ASC").Find(&inbounds).Error @@ -2605,6 +2631,7 @@ func (s *InboundService) updateClientTraffics(tx *gorm.DB, inboundId int, oldCli // Drop stats rows for removed emails — but not when a sibling inbound // still references the email, since the row is the shared accumulator. + var removedIPs []string for i := range oldClients { email := oldClients[i].Email if email == "" { @@ -2623,11 +2650,11 @@ func (s *InboundService) updateClientTraffics(tx *gorm.DB, inboundId int, oldCli if err := s.DelClientStat(tx, email); err != nil { return err } - // Keep inbound_client_ips in sync when the inbound edit drops an - // email, so the IP-limit job doesn't keep a ghost tracking row (#4963). - if err := s.DelClientIPs(tx, email); err != nil { - return err - } + removedIPs = append(removedIPs, email) + } + // The IP-limit job must not keep tracking removed clients (#4963). + if err := s.delClientIPsByEmails(tx, removedIPs); err != nil { + return err } keptEmails := make([]string, 0, len(newClients)) keptClients := make(map[string]*model.Client, len(newClients)) diff --git a/internal/web/service/inbound_client_ips.go b/internal/web/service/inbound_client_ips.go index 82c3e80dc..42e5082f0 100644 --- a/internal/web/service/inbound_client_ips.go +++ b/internal/web/service/inbound_client_ips.go @@ -1,8 +1,11 @@ package service import ( + "context" "encoding/json" + "errors" "fmt" + "slices" "sort" "time" @@ -76,7 +79,10 @@ func mergeClientIpEntries(old, incoming []model.ClientIpEntry, cutoff int64) []m // MergeInboundClientIps unions remote observations without losing concurrent scanner writes. func (s *InboundService) MergeInboundClientIps(incomingIps []model.InboundClientIps) error { - db := database.GetDB() + return mergeInboundClientIps(database.GetDB(), nil, incomingIps) +} + +func mergeInboundClientIps(db *gorm.DB, reporter *model.Node, incomingIps []model.InboundClientIps) error { var currentIps []model.InboundClientIps if err := db.Model(&model.InboundClientIps{}).Find(¤tIps).Error; err != nil { return err @@ -96,6 +102,15 @@ func (s *InboundService) MergeInboundClientIps(incomingIps []model.InboundClient }) tx := db.Begin() + if tx.Error != nil { + return tx.Error + } + if reporter != nil && tx.Name() != database.DialectPostgres { + if err := lockOnlineNodeIPReporter(tx, reporter); err != nil { + tx.Rollback() + return err + } + } defer func() { if r := recover(); r != nil { tx.Rollback() @@ -134,6 +149,9 @@ func (s *InboundService) MergeInboundClientIps(incomingIps []model.InboundClient } current = &model.InboundClientIps{} if err := tx.Where("client_email = ?", incoming.ClientEmail).First(current).Error; err != nil { + if reporter != nil && errors.Is(err, gorm.ErrRecordNotFound) { + continue + } tx.Rollback() return err } @@ -142,7 +160,21 @@ func (s *InboundService) MergeInboundClientIps(incomingIps []model.InboundClient // check_client_ip_job rewrites this blob too; an unconditional Update loses // whichever writer commits second and its remote IPs with it (#6587). - if err := mergeExistingClientIps(tx, current, incomingEntries, cutoff); err != nil { + err := mergeExistingClientIps(tx, current, incomingEntries, cutoff, reporter != nil) + // The observation belongs to the email in the report. A concurrent + // delete or rename can remove it while the poll waits for the row. + if reporter != nil && errors.Is(err, gorm.ErrRecordNotFound) { + continue + } + if err != nil { + tx.Rollback() + return err + } + } + // Client mutations lock flat IP rows before marking the node dirty. + // Take the PostgreSQL reporter lock last and roll back obsolete reports. + if reporter != nil && tx.Name() == database.DialectPostgres { + if err := lockOnlineNodeIPReporter(tx, reporter); err != nil { tx.Rollback() return err } @@ -167,7 +199,12 @@ func CasUpdateInboundClientIps(tx *gorm.DB, id int, expectedIps, newIps string) } // Seed the first CAS from the preload; only a competing write requires a re-read. -func mergeExistingClientIps(tx *gorm.DB, current *model.InboundClientIps, incoming []model.ClientIpEntry, cutoff int64) error { +func mergeExistingClientIps(tx *gorm.DB, current *model.InboundClientIps, incoming []model.ClientIpEntry, cutoff int64, polled bool) error { + if polled { + // Keep the observed email in every CAS attempt even if the ID is + // still present after a concurrent rename. + tx = tx.Where("client_email = ?", current.ClientEmail).Session(&gorm.Session{}) + } for attempt := range ClientIpCasRetries { var oldEntries []model.ClientIpEntry if current.Ips != "" { @@ -199,6 +236,11 @@ func (s *InboundService) UpdateClientIPs(tx *gorm.DB, oldEmail string, newEmail // The caller only renames onto a free identity, so a row already sitting on // newEmail is stale tracking data — drop it instead of failing the edit. if oldEmail != newEmail { + if tx.Name() == database.DialectPostgres { + if _, err := lockFlatClientIPRows(tx, []string{oldEmail, newEmail}); err != nil { + return err + } + } if err := tx.Where("client_email = ?", newEmail).Delete(model.InboundClientIps{}).Error; err != nil { return err } @@ -212,15 +254,40 @@ func (s *InboundService) DelClientIPs(tx *gorm.DB, email string) error { func (s *InboundService) delClientIPsByEmails(tx *gorm.DB, emails []string) error { const chunk = 400 + postgres := tx.Name() == database.DialectPostgres + if postgres { + emails = slices.Clone(emails) + slices.Sort(emails) + } for start := 0; start < len(emails); start += chunk { end := min(start+chunk, len(emails)) - if err := tx.Where("client_email IN ?", emails[start:end]).Delete(model.InboundClientIps{}).Error; err != nil { + query := tx.Where("client_email IN ?", emails[start:end]) + if postgres { + ids, err := lockFlatClientIPRows(tx, emails[start:end]) + if err != nil { + return err + } + if len(ids) == 0 { + continue + } + query = tx.Where("id IN ?", ids) + } + if err := query.Delete(model.InboundClientIps{}).Error; err != nil { return err } } return nil } +// Acquire flat IP row locks in the same byte order as the scanner and poller. +// The planner may visit a multi-row DELETE's targets in heap order instead. +func lockFlatClientIPRows(tx *gorm.DB, emails []string) ([]int, error) { + var ids []int + err := tx.Model(&model.InboundClientIps{}).Where("client_email IN ?", emails). + Order(`client_email COLLATE "C"`).Clauses(clause.Locking{Strength: "UPDATE"}).Pluck("id", &ids).Error + return ids, err +} + func (s *InboundService) GetInboundClientIps(clientEmail string) (string, error) { db := database.GetDB() InboundClientIps := &model.InboundClientIps{} @@ -326,7 +393,16 @@ func nodeAttachedEmails(db *gorm.DB, nodeID int) (map[string]struct{}, error) { // MergeNodeClientIps merges one node's flat client-IP report, cut to the node's clients. func (s *InboundService) MergeNodeClientIps(nodeID int, rows []model.InboundClientIps) error { - attached, err := nodeAttachedEmails(database.GetDB(), nodeID) + return mergeNodeClientIps(database.GetDB(), nil, nodeID, rows) +} + +// MergePolledNodeClientIps preserves the flat union with an online reporter fence. +func (s *InboundService) MergePolledNodeClientIps(ctx context.Context, node *model.Node, rows []model.InboundClientIps) error { + return mergeNodeClientIps(database.GetDB().WithContext(ctx), node, node.Id, rows) +} + +func mergeNodeClientIps(db *gorm.DB, reporter *model.Node, nodeID int, rows []model.InboundClientIps) error { + attached, err := nodeAttachedEmails(db, nodeID) if err != nil { return err } @@ -347,7 +423,7 @@ func (s *InboundService) MergeNodeClientIps(nodeID int, rows []model.InboundClie if len(kept) == 0 { return nil } - return s.MergeInboundClientIps(kept) + return mergeInboundClientIps(db, reporter, kept) } // clampClientIpEntries caps reported timestamps at now: a future-dated entry would never diff --git a/internal/web/service/inbound_node.go b/internal/web/service/inbound_node.go index 6f855bda0..269a2450e 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 @@ -137,14 +120,23 @@ func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, return nil } nodeID := n.Id + turn := reserveNodeConfigTurn(nodeID, 0, nodeFullReconcile) + defer turn.release() + if !turn.wait(ctx) { + return ctx.Err() + } + var errs []error + if err := deliverNodeClientDeletes(ctx, nodeID, rt); err != nil { + errs = append(errs, err) + } db := database.GetDB() var inbounds []*model.Inbound if err := db.Model(model.Inbound{}).Where("node_id = ?", nodeID).Find(&inbounds).Error; err != nil { - return err + return errors.Join(append(errs, err)...) } remoteInbounds, err := rt.ListInboundOptions(ctx) if err != nil { - return err + return errors.Join(append(errs, err)...) } remoteTags := make([]string, 0, len(remoteInbounds)) remoteTagSet := make(map[string]struct{}, len(remoteTags)) @@ -154,7 +146,6 @@ func (s *InboundService) ReconcileNode(ctx context.Context, rt *runtime.Remote, } prefix := nodeTagPrefix(&nodeID) desiredTags := make(map[string]struct{}, len(inbounds)*2) - var errs []error for _, ib := range inbounds { desiredTags[ib.Tag] = struct{}{} // existsOnNode: does the node already report this inbound under any of the @@ -248,19 +239,48 @@ type nodeTrafficCounter struct { Down int64 } -func (s *InboundService) upsertNodeBaseline(tx *gorm.DB, nodeID int, email string, counter nodeTrafficCounter, dippedWhileFrozen bool) error { +func upsertNodeBaselines(tx *gorm.DB, changes map[string]model.NodeClientTraffic) error { + if len(changes) == 0 { + return nil + } + rows := make([]model.NodeClientTraffic, 0, len(changes)) + for _, email := range slices.Sorted(maps.Keys(changes)) { + rows = append(rows, changes[email]) + } return tx.Clauses(clause.OnConflict{ Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}}, DoUpdates: clause.AssignmentColumns([]string{"up", "down", "dipped_while_frozen"}), - }).Create(&model.NodeClientTraffic{ - NodeId: nodeID, Email: email, Up: counter.Up, Down: counter.Down, DippedWhileFrozen: dippedWhileFrozen, - }).Error + }).CreateInBatches(rows, sqliteMaxVars/6).Error } -// mergeNodeClientTraffic folds one node-reported client into its central row. -// While frozen (a push pending or just landed) only the counters may move. -func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraffic, canon nodeTrafficCounter, frozen bool, deltaUp, deltaDown, now int64) error { - if frozen { +type nodeClientTrafficWrite struct { + stats xray.ClientTraffic + canon nodeTrafficCounter + deltaUp, deltaDown int64 + frozen, renewed bool +} + +// apply folds a planned change into the existing counter row without touching last_sub_fetch. +func (write nodeClientTrafficWrite) apply(tx *gorm.DB, now int64) error { + cs, canon := write.stats, write.canon + if write.renewed { + if err := tx.Exec( + fmt.Sprintf( + `UPDATE client_traffics + SET up = ?, down = ?, enable = ?, total = ?, + expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s + WHERE email = ?`, + database.GreatestExpr("last_online", "?"), + ), + canon.Up, canon.Down, cs.Enable, cs.Total, + cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount, + cs.LastOnline, cs.Email, + ).Error; err != nil { + return err + } + return clearGlobalTraffic(tx, cs.Email) + } + if write.frozen { return tx.Exec( fmt.Sprintf( `UPDATE client_traffics @@ -270,7 +290,7 @@ func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraff database.ClampedAddExpr("down"), database.GreatestExpr("last_online", "?"), ), - deltaUp, deltaDown, cs.LastOnline, cs.Email, + write.deltaUp, write.deltaDown, cs.LastOnline, cs.Email, ).Error } return tx.Exec( @@ -286,8 +306,8 @@ func (s *InboundService) mergeNodeClientTraffic(tx *gorm.DB, cs xray.ClientTraff database.ClientTrafficExpiryMergeExpr(), database.GreatestExpr("last_online", "?"), ), - deltaUp, deltaDown, - cs.Enable, now, deltaUp, deltaDown, canon.Up, canon.Down, + write.deltaUp, write.deltaDown, + cs.Enable, now, write.deltaUp, write.deltaDown, canon.Up, canon.Down, cs.Total, cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.LastOnline, cs.Email, @@ -432,12 +452,37 @@ 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) + logger.Debugf("node traffic writer: node_id=%d queue_wait_ms=%d writer_ms=%d success=%t", + nodeID, started.Sub(queuedAt).Milliseconds(), time.Since(started).Milliseconds(), inner == nil) return inner }) if err != nil { @@ -793,18 +838,27 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + var claimInputs nodeClaimInputs + if !skipStructure { + claimInputs = readNodeClaimInputs(snap) + } + txStarted := time.Now() tx := db.Begin() + if tx.Error != nil { + return false, tx.Error + } committed := false defer func() { if !committed { tx.Rollback() + logger.Debugf("node traffic transaction: node_id=%d tx_ms=%d committed=false", nodeID, time.Since(txStarted).Milliseconds()) } }() claims := &nodeClientClaims{} rawSettings := make(map[*model.Inbound]string, len(snap.Inbounds)) if !skipStructure { - claims, err = loadNodeClientClaims(tx, nodeID, snap) + claims, err = loadNodeClientClaims(tx, nodeID, claimInputs) if err != nil { return false, err } @@ -1167,6 +1221,19 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } + baselineChanges := make(map[string]model.NodeClientTraffic) + var trafficWrites []nodeClientTrafficWrite + stageBaseline := func(email string, counter nodeTrafficCounter, dipped bool) { + baselineChanges[email] = model.NodeClientTraffic{ + NodeId: nodeID, Email: email, Up: counter.Up, Down: counter.Down, DippedWhileFrozen: dipped, + } + nodeBaselines[email] = counter + if dipped { + dippedWhileFrozen[email] = true + } else { + delete(dippedWhileFrozen, email) + } + } for _, snapIb := range snap.Inbounds { if snapIb == nil { continue @@ -1260,11 +1327,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi activatedEmails[row.Email] = struct{}{} } structuralChange = true - if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon, false); err != nil { - return false, err - } - nodeBaselines[cs.Email] = canon - delete(dippedWhileFrozen, cs.Email) + stageBaseline(cs.Email, canon, false) continue } @@ -1295,23 +1358,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if renewed { // A renewal starts a fresh quota window: adopt the node's counters // and enable state, drop stale pushes (mirrors autoRenewClients). - if err := tx.Exec( - fmt.Sprintf( - `UPDATE client_traffics - SET up = ?, down = ?, enable = ?, total = ?, - expiry_time = ?, reset = ?, reset_day = ?, reset_weekday = ?, reset_count = ?, last_online = %s - WHERE email = ?`, - database.GreatestExpr("last_online", "?"), - ), - canon.Up, canon.Down, cs.Enable, cs.Total, - cs.ExpiryTime, cs.Reset, cs.ResetDay, cs.ResetWeekday, cs.ResetCount, - cs.LastOnline, cs.Email, - ).Error; err != nil { - return false, err - } - if err := clearGlobalTraffic(tx, cs.Email); err != nil { - return false, err - } + trafficWrites = append(trafficWrites, nodeClientTrafficWrite{stats: cs, canon: canon, renewed: true}) existing.Up = canon.Up existing.Down = canon.Down existing.Enable = cs.Enable @@ -1343,9 +1390,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi // A multi-attached client is reported once per inbound and an idle one // every tick: rewriting an unchanged row only holds its lock longer. if next != *row { - if err := s.mergeNodeClientTraffic(tx, cs, canon, clientFrozen, deltaUp, deltaDown, now); err != nil { - return false, err - } + trafficWrites = append(trafficWrites, nodeClientTrafficWrite{ + stats: cs, canon: canon, frozen: clientFrozen, deltaUp: deltaUp, deltaDown: deltaDown, + }) if row.ExpiryTime <= 0 && next.ExpiryTime > 0 { activatedEmails[cs.Email] = struct{}{} } @@ -1358,15 +1405,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if seen && base == canon && stillOwed == dippedWhileFrozen[cs.Email] { continue } - if err := s.upsertNodeBaseline(tx, nodeID, cs.Email, canon, stillOwed); err != nil { - return false, err - } - nodeBaselines[cs.Email] = canon - if stillOwed { - dippedWhileFrozen[cs.Email] = true - } else { - delete(dippedWhileFrozen, cs.Email) - } + stageBaseline(cs.Email, canon, stillOwed) } if skipStructure { @@ -1416,11 +1455,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi syncFailedInbounds := map[int]struct{}{} if !skipStructure || structuralChange { - type oldSet struct { - inboundID int - emails map[string]struct{} - } - var perInboundOld []oldSet + detached := make(map[int]struct{}) for _, snapIb := range snap.Inbounds { if snapIb == nil { continue @@ -1432,20 +1467,6 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if dirty { continue } - var oldEmailsRows []string - if err := tx.Table("clients"). - Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id"). - Where("client_inbounds.inbound_id = ?", c.Id). - Pluck("email", &oldEmailsRows).Error; err == nil { - oldEmails := make(map[string]struct{}, len(oldEmailsRows)) - for _, e := range oldEmailsRows { - if e != "" { - oldEmails[e] = struct{}{} - } - } - perInboundOld = append(perInboundOld, oldSet{inboundID: c.Id, emails: oldEmails}) - } - clients, gcErr := s.GetClients(snapIb) if gcErr != nil { logger.Warningf("setRemoteTraffic: parse clients for tag %q failed: %v", snapIb.Tag, gcErr) @@ -1473,43 +1494,16 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi // A degraded node (reset/restart/removal) reports zero clients for an inbound the // hub populates; adopting it empties links and ReapSyncOrphans deletes shared clients (#6734). if _, degraded := degradedInbounds[c.Id]; degraded { - logger.Warningf("setRemoteTraffic: node %d reported zero clients for tag %q while the hub has %d attached — keeping them and re-pushing", nodeID, snapIb.Tag, len(oldEmailsRows)) + logger.Warningf("setRemoteTraffic: node %d reported zero clients for tag %q while the hub still has attached clients — keeping them and re-pushing", nodeID, snapIb.Tag) syncFailedInbounds[c.Id] = struct{}{} continue } - localEmails := make([]string, 0, len(filtered)) - for i := range filtered { - if filtered[i].Email != "" { - localEmails = append(localEmails, filtered[i].Email) - } - } - commentByEmail := make(map[string]string, len(localEmails)) - for _, batch := range chunkStrings(localEmails, sqlInChunk) { - var localMeta []struct { - Email string - Comment string `gorm:"column:comment"` - } - if err := tx.Table("clients"). - Select("email, comment"). - Where("email IN ?", batch). - Find(&localMeta).Error; err != nil { - continue - } - for _, m := range localMeta { - commentByEmail[m.Email] = m.Comment - } - } - for i := range filtered { - if cmt, ok := commentByEmail[filtered[i].Email]; ok { - filtered[i].Comment = cmt - } - } p, adopt := pendingAdopts[c.Id] _, isNew := newInboundIDs[c.Id] adoptedSettings := p.wireSettings liftChanged := false if adopt && !isNew { - // Use the traffic deltas just applied to this transaction (#6228). + // Use the staged traffic values before flushing their SQL updates (#6228). if lifted, changed := liftClientLifecycleInSettings(p.wireSettings, statByEmail); changed { adoptedSettings, liftChanged = lifted, true } @@ -1522,13 +1516,14 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } updates["settings"] = adoptedSettings } + var linkResult nodeInboundSyncResult rejected, err := withClientSyncSavepoint(tx, func() error { if len(updates) > 0 { if err := tx.Model(model.Inbound{}).Where("id = ?", c.Id).Updates(updates).Error; err != nil { return err } } - return s.clientService.SyncInbound(tx, c.Id, filtered) + return s.clientService.syncInboundClients(tx, c.Id, filtered, nil, true, &linkResult) }) if err != nil { return false, err @@ -1545,6 +1540,9 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi if len(updates) > 0 { structuralChange = true } + for _, id := range linkResult.detached { + detached[id] = struct{}{} + } adoptedSettingsChanged = adoptedSettingsChanged || settingsChanged lifecycleLifted = lifecycleLifted || liftChanged // Stamp the un-lifted wire blob so reconciliation can push lifecycle lifts. @@ -1553,48 +1551,24 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi } } - for _, old := range perInboundOld { - // The sweep's premise is that links were just rebuilt from the snapshot, - // which is exactly what a failed SyncInbound violates. - if _, failed := syncFailedInbounds[old.inboundID]; failed { - continue - } - var stillAttached []string - if err := tx.Table("clients"). - Joins("JOIN client_inbounds ON client_inbounds.client_id = clients.id"). - Where("client_inbounds.inbound_id = ?", old.inboundID). - Pluck("email", &stillAttached).Error; err != nil { - continue - } - stillSet := make(map[string]struct{}, len(stillAttached)) - for _, e := range stillAttached { - stillSet[e] = struct{}{} - } - for email := range old.emails { - if _, kept := stillSet[email]; kept { - continue - } - var attachmentCount int64 - if err := tx.Table("client_inbounds"). - Joins("JOIN clients ON clients.id = client_inbounds.client_id"). - Where("clients.email = ?", email). - Count(&attachmentCount).Error; err != nil { - continue - } - if attachmentCount > 0 { - continue - } - // "Ended the merge unattached" is true for a real remote deletion and - // equally true for a bad merge, so record a strike instead of deleting. - if err := markSyncOrphan(tx, email, nodeID, now); err != nil { - logger.Warningf("setRemoteTraffic: mark orphan %q failed: %v", email, err) - continue - } - structuralChange = true - } + // A client detached here may have been attached to another inbound by the same snapshot. + marked, err := markDetachedSyncOrphans(tx, slices.Sorted(maps.Keys(detached)), nodeID, now) + if err != nil { + return false, fmt.Errorf("mark node %d sync orphans: %w", nodeID, err) } + structuralChange = structuralChange || marked } + if err := upsertNodeBaselines(tx, baselineChanges); err != nil { + return false, err + } + // Client reconciliation used the planned traffic values in memory. Lock + // the existing traffic rows only now, in snapshot order, before commit. + for _, write := range trafficWrites { + if err := write.apply(tx, now); err != nil { + return false, err + } + } for _, emails := range chunkStrings(slices.Sorted(maps.Keys(activatedEmails)), sqlInChunk) { if err := liftActivatedClientRecordExpiries(tx.Model(&model.ClientRecord{}).Where("email IN ?", emails)); err != nil { return false, err @@ -1605,6 +1579,7 @@ func (s *InboundService) setRemoteTrafficLocked(nodeID int, snap *runtime.Traffi return false, err } committed = true + logger.Debugf("node traffic transaction: node_id=%d tx_ms=%d committed=true", nodeID, time.Since(txStarted).Milliseconds()) if adoptedSettingsChanged { InvalidateSubData() } diff --git a/internal/web/service/inbound_node_claims.go b/internal/web/service/inbound_node_claims.go index 1e655a591..248a587c9 100644 --- a/internal/web/service/inbound_node_claims.go +++ b/internal/web/service/inbound_node_claims.go @@ -39,17 +39,20 @@ var nodeKeptSharedKeys = []string{"flow", "privateKey", "publicKey", "allowedIPs type clientLinkScope struct{ here, elsewhere bool } -func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot) (*nodeClientClaims, error) { - claims := &nodeClientClaims{ - refused: map[string]string{}, - shared: map[string]*model.ClientRecord{}, - storedSubID: map[string]string{}, - usageOnly: map[string]struct{}{}, +type nodeClaimInputs struct { + subIDByEmail map[string]string + refused map[string]string + sharesSubID map[string]struct{} +} + +func readNodeClaimInputs(snap *runtime.TrafficSnapshot) nodeClaimInputs { + inputs := nodeClaimInputs{ + subIDByEmail: map[string]string{}, + refused: map[string]string{}, + sharesSubID: map[string]struct{}{}, } - subIDByEmail := map[string]string{} // A subId selects a whole subscription, so within one snapshot it may name one client only. firstEmailBySub := map[string]string{} - sharesSubID := map[string]struct{}{} for _, snapIb := range snap.Inbounds { if snapIb == nil { continue @@ -64,28 +67,38 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot continue } if c.Email != strings.TrimSpace(c.Email) { - claims.refused[c.Email] = "its email carries surrounding white space" + inputs.refused[c.Email] = "its email carries surrounding white space" continue } - if _, seen := subIDByEmail[c.Email]; !seen { + if _, seen := inputs.subIDByEmail[c.Email]; !seen { var subID string _ = json.Unmarshal(c.SubID, &subID) - subIDByEmail[c.Email] = subID + inputs.subIDByEmail[c.Email] = subID if first, taken := firstEmailBySub[subID]; subID != "" && taken && !strings.EqualFold(first, c.Email) { - sharesSubID[c.Email] = struct{}{} + inputs.sharesSubID[c.Email] = struct{}{} } else if subID != "" && !taken { firstEmailBySub[subID] = c.Email } } } } - if len(subIDByEmail) == 0 { + return inputs +} + +func loadNodeClientClaims(tx *gorm.DB, nodeID int, inputs nodeClaimInputs) (*nodeClientClaims, error) { + claims := &nodeClientClaims{ + refused: inputs.refused, + shared: map[string]*model.ClientRecord{}, + storedSubID: map[string]string{}, + usageOnly: map[string]struct{}{}, + } + if len(inputs.subIDByEmail) == 0 { logRefusedClaims(nodeID, claims.refused) return claims, nil } - reported := make([]string, 0, len(subIDByEmail)) - for email := range subIDByEmail { + reported := make([]string, 0, len(inputs.subIDByEmail)) + for email := range inputs.subIDByEmail { reported = append(reported, email) } // SQLite's LOWER folds ASCII only, so a non-ASCII capital is matched by its spellings too. @@ -104,8 +117,8 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot byLower[strings.ToLower(records[i].Email)] = records[i].Email } - subIDs := make([]string, 0, len(subIDByEmail)) - for _, subID := range subIDByEmail { + subIDs := make([]string, 0, len(inputs.subIDByEmail)) + for _, subID := range inputs.subIDByEmail { if subID != "" { subIDs = append(subIDs, subID) } @@ -132,7 +145,7 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot holdersBySub[h.SubID] = append(holdersBySub[h.SubID], h) } subIDTaken := func(email, subID string) bool { - if _, shared := sharesSubID[email]; shared { + if _, shared := inputs.sharesSubID[email]; shared { return true } for _, h := range holdersBySub[subID] { @@ -143,7 +156,7 @@ func loadNodeClientClaims(tx *gorm.DB, nodeID int, snap *runtime.TrafficSnapshot return false } - for email, subID := range subIDByEmail { + for email, subID := range inputs.subIDByEmail { rec, exact := byEmail[email] if !exact { if _, variant := byLower[strings.ToLower(email)]; variant { diff --git a/internal/web/service/inbound_node_ips.go b/internal/web/service/inbound_node_ips.go index 76f75fd46..b3eb2767c 100644 --- a/internal/web/service/inbound_node_ips.go +++ b/internal/web/service/inbound_node_ips.go @@ -2,7 +2,9 @@ package service import ( "cmp" + "context" "encoding/json" + "errors" "slices" "sort" "time" @@ -45,26 +47,28 @@ func mergeModelClientIpEntries(old, incoming []model.ClientIpEntry, cutoff int64 return out } -// upsertNodeClientIps merges fresh observations per (guid, email). -// Empty results delete attribution instead of retaining expired rows. +// Stay under SQLite's 999-parameter limit with up to five binds per row, +// including the compare-and-set predicate. +const nodeClientIpWriteBatch = 190 + +var errNodeClientIpConflict = errors.New("node client IP attribution changed during merge") + +type nodeClientIpChange struct { + email string + ips string + previous *model.NodeClientIp +} + +// upsertNodeClientIps merges fresh observations in email order and retries +// the whole GUID after a concurrent write so no partial merge is committed. func upsertNodeClientIps(guid string, perEmail map[string][]model.ClientIpEntry) error { + return mergeNodeClientIpAttribution(database.GetDB(), nil, guid, perEmail) +} + +func mergeNodeClientIpAttribution(db *gorm.DB, reporter *model.Node, guid string, perEmail map[string][]model.ClientIpEntry) error { if guid == "" || len(perEmail) == 0 { return nil } - db := database.GetDB() - cutoff := time.Now().Unix() - clientIpStaleAfterSeconds - - var existing []model.NodeClientIp - if err := db.Where("node_guid = ?", guid).Find(&existing).Error; err != nil { - return err - } - existingByEmail := make(map[string]*model.NodeClientIp, len(existing)) - for i := range existing { - existingByEmail[existing[i].Email] = &existing[i] - } - - // Deterministic row order keeps concurrent guid merges from deadlocking on - // Postgres (40P01) — same discipline as MergeInboundClientIps. emails := make([]string, 0, len(perEmail)) for email := range perEmail { if email != "" { @@ -73,45 +77,153 @@ func upsertNodeClientIps(guid string, perEmail map[string][]model.ClientIpEntry) } sort.Strings(emails) - tx := db.Begin() - defer func() { - if r := recover(); r != nil { - tx.Rollback() + cutoff := time.Now().Unix() - clientIpStaleAfterSeconds + for range ClientIpCasRetries { + changes, err := planNodeClientIpChanges(db, guid, emails, perEmail, cutoff) + if err != nil || len(changes) == 0 { + return err } - }() - - for _, email := range emails { - incoming := perEmail[email] - var old []model.ClientIpEntry - if cur, ok := existingByEmail[email]; ok && cur.Ips != "" { - _ = json.Unmarshal([]byte(cur.Ips), &old) - } - merged := mergeModelClientIpEntries(old, incoming, cutoff) - if len(merged) == 0 { - // Nothing fresh: drop any stale row so attribution doesn't linger. - if _, ok := existingByEmail[email]; ok { - if err := tx.Where("node_guid = ? AND email = ?", guid, email). - Delete(&model.NodeClientIp{}).Error; err != nil { - tx.Rollback() + err = db.Transaction(func(tx *gorm.DB) error { + if reporter != nil { + if err := lockOnlineNodeIPReporter(tx, reporter); err != nil { return err } } - continue - } - encoded, _ := model.MarshalClientIpEntries(merged) - if current := existingByEmail[email]; current != nil && current.Ips == encoded { - continue - } - row := model.NodeClientIp{NodeGuid: guid, Email: email, Ips: encoded} - if err := tx.Clauses(clause.OnConflict{ - Columns: []clause.Column{{Name: "node_guid"}, {Name: "email"}}, - DoUpdates: clause.AssignmentColumns([]string{"ips"}), - }).Create(&row).Error; err != nil { - tx.Rollback() + return applyNodeClientIpChanges(tx, guid, changes) + }) + if !errors.Is(err, errNodeClientIpConflict) { return err } } - return tx.Commit().Error + return errNodeClientIpConflict +} + +func planNodeClientIpChanges(db *gorm.DB, guid string, emails []string, perEmail map[string][]model.ClientIpEntry, cutoff int64) ([]nodeClientIpChange, error) { + var existing []model.NodeClientIp + if err := db.Where("node_guid = ?", guid).Find(&existing).Error; err != nil { + return nil, err + } + existingByEmail := make(map[string]*model.NodeClientIp, len(existing)) + for i := range existing { + existingByEmail[existing[i].Email] = &existing[i] + } + + changes := make([]nodeClientIpChange, 0, len(emails)) + for _, email := range emails { + previous := existingByEmail[email] + var old []model.ClientIpEntry + if previous != nil && previous.Ips != "" { + _ = json.Unmarshal([]byte(previous.Ips), &old) + } + merged := mergeModelClientIpEntries(old, perEmail[email], cutoff) + if len(merged) == 0 { + if previous != nil { + changes = append(changes, nodeClientIpChange{email: email, previous: previous}) + } + continue + } + encoded, err := model.MarshalClientIpEntries(merged) + if err != nil { + return nil, err + } + if previous == nil || previous.Ips != encoded { + changes = append(changes, nodeClientIpChange{email: email, ips: encoded, previous: previous}) + } + } + return changes, nil +} + +func applyNodeClientIpChanges(tx *gorm.DB, guid string, changes []nodeClientIpChange) error { + for start := 0; start < len(changes); { + deleting := changes[start].ips == "" + end := start + 1 + // A multi-row DELETE does not guarantee row-lock order on PostgreSQL. + for !deleting && end < min(start+nodeClientIpWriteBatch, len(changes)) && changes[end].ips != "" { + end++ + } + batch := changes[start:end] + expected := make([]clause.Expression, 0, len(batch)) + previousIDs := make(map[string]int, len(batch)) + for _, change := range batch { + if change.previous != nil { + expected = append(expected, nodeClientIpSnapshot(*change.previous)) + previousIDs[change.email] = change.previous.Id + } + } + var result *gorm.DB + var rows []model.NodeClientIp + if deleting { + result = tx.Where(expected[0]).Delete(&model.NodeClientIp{}) + } else { + rows = make([]model.NodeClientIp, 0, len(batch)) + for _, change := range batch { + rows = append(rows, model.NodeClientIp{NodeGuid: guid, Email: change.email, Ips: change.ips}) + } + conflict := clause.OnConflict{ + Columns: []clause.Column{{Name: "node_guid"}, {Name: "email"}}, + DoNothing: len(expected) == 0, + } + // For DO NOTHING, GORM skips nonzero RETURNING fields in the + // input slice. Only the generated ID starts out unset. + returning := clause.Returning{Columns: []clause.Column{{Name: "id"}}} + if !conflict.DoNothing { + conflict.DoUpdates = clause.AssignmentColumns([]string{"ips"}) + conflict.Where = clause.Where{Exprs: []clause.Expression{clause.Or(expected...)}} + returning.Columns = append(returning.Columns, clause.Column{Name: "email"}) + } + result = tx.Clauses(conflict, returning).Create(&rows) + } + if result.Error != nil { + return result.Error + } + if result.RowsAffected != int64(len(batch)) { + return errNodeClientIpConflict + } + // An existing row can be deleted after the read. A replacement ID + // requires a retry so the new row cannot inherit the deleted IPs. + for _, row := range rows { + if id, existed := previousIDs[row.Email]; existed && row.Id != id { + return errNodeClientIpConflict + } + } + start = end + } + return nil +} + +func nodeClientIpSnapshot(row model.NodeClientIp) clause.Expression { + id := clause.Column{Table: clause.CurrentTable, Name: "id"} + ips := clause.Column{Table: clause.CurrentTable, Name: "ips"} + content := clause.Expression(clause.Eq{Column: ips, Value: row.Ips}) + if row.Ips == "" { + content = clause.Or(content, clause.Eq{Column: ips, Value: nil}) + } + return clause.And(clause.Eq{Column: id, Value: row.Id}, content) +} + +// ErrIneligibleNodeIPReport identifies work invalidated while in flight. +var ErrIneligibleNodeIPReport = errors.New("node IP report is no longer eligible") + +// Keep the reporter stable through commit. The flat PostgreSQL merge calls +// this after its IP writes. Attribution and node deletion lock the node first. +func lockOnlineNodeIPReporter(tx *gorm.DB, reporter *model.Node) error { + var current model.Node + query := tx.Select("id", "guid", "scheme", "address", "port", "base_path"). + Where("id = ? AND enable = ? AND status = ?", reporter.Id, true, "online") + if tx.Name() == database.DialectPostgres { + query = query.Clauses(clause.Locking{Strength: "SHARE"}) + } + if err := query.Take(¤t).Error; err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return ErrIneligibleNodeIPReport + } + return err + } + if current.Guid != reporter.Guid || current.Scheme != reporter.Scheme || current.Address != reporter.Address || + current.Port != reporter.Port || current.BasePath != reporter.BasePath { + return ErrIneligibleNodeIPReport + } + return nil } // RecordLocalClientIps stores the scanner's local observations under this panel's GUID. @@ -127,6 +239,15 @@ func (s *InboundService) RecordLocalClientIps(panelGuid string, observed map[str // clones don't collapse into one attribution row; descendant subtrees keep their // distinct GUIDs. A nil node merges the report verbatim. func (s *InboundService) MergeClientIpsByGuid(node *model.Node, trees map[string]map[string][]model.ClientIpEntry) error { + return mergeClientIpsByGuid(database.GetDB(), node, trees, false) +} + +// MergePolledClientIpsByGuid commits a node report only while its reporter is eligible. +func (s *InboundService) MergePolledClientIpsByGuid(ctx context.Context, node *model.Node, trees map[string]map[string][]model.ClientIpEntry) error { + return mergeClientIpsByGuid(database.GetDB().WithContext(ctx), node, trees, true) +} + +func mergeClientIpsByGuid(db *gorm.DB, node *model.Node, trees map[string]map[string][]model.ClientIpEntry, checkReporter bool) error { if node != nil && node.Guid != "" { if eff := effectiveNodeKey(node); eff != node.Guid { if sub, ok := trees[node.Guid]; ok { @@ -142,18 +263,22 @@ func (s *InboundService) MergeClientIpsByGuid(node *model.Node, trees map[string } } if node != nil { - scoped, err := scopeNodeClientIps(database.GetDB(), node, trees) + scoped, err := scopeNodeClientIps(db, node, trees) if err != nil { return err } trees = scoped } + var reporter *model.Node + if checkReporter { + reporter = node + } for guid, perEmail := range trees { // Stored once per email: an oversized key would multiply into every row. if len(guid) > maxPanelGuidLen { continue } - if err := upsertNodeClientIps(guid, perEmail); err != nil { + if err := mergeNodeClientIpAttribution(db, reporter, guid, perEmail); err != nil { return err } } @@ -329,7 +454,7 @@ func pruneStaleNodeClientIps(cutoff int64) error { } kept := mergeModelClientIpEntries(nil, entries, cutoff) if len(kept) == 0 { - if err := db.Delete(&model.NodeClientIp{}, row.Id).Error; err != nil { + if err := db.Where(nodeClientIpSnapshot(row)).Delete(&model.NodeClientIp{}).Error; err != nil { return err } continue @@ -338,7 +463,7 @@ func pruneStaleNodeClientIps(cutoff int64) error { continue } encoded, _ := model.MarshalClientIpEntries(kept) - if err := db.Model(&model.NodeClientIp{}).Where("id = ?", row.Id).Update("ips", encoded).Error; err != nil { + if err := db.Model(&model.NodeClientIp{}).Where(nodeClientIpSnapshot(row)).Update("ips", encoded).Error; err != nil { return err } } diff --git a/internal/web/service/inbound_traffic.go b/internal/web/service/inbound_traffic.go index ce6f56f45..bc57a7114 100644 --- a/internal/web/service/inbound_traffic.go +++ b/internal/web/service/inbound_traffic.go @@ -34,6 +34,7 @@ func (s *InboundService) AddTraffic(inboundTraffics []*xray.Traffic, clientTraff func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart bool, clientsDisabled bool, err error) { var disabledNodeIDs []int var remotePlans []trafficInboundUpdatePlan + var remoteTurns []*nodeConfigTurn var renewed []string committed := false // The periodic poll takes the background lane: an operator's save or reset @@ -46,6 +47,9 @@ func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart b committed = true var inner error needRestart, clientsDisabled, disabledNodeIDs, remotePlans, renewed, inner = s.maintainTrafficLocked() + if inner == nil { + remoteTurns = reserveTrafficRemoteTurns(remotePlans) + } return inner }) if err != nil { @@ -55,9 +59,16 @@ func (s *InboundService) addTraffic(account func(*gorm.DB) error) (needRestart b } return } + defer func() { + for _, turn := range remoteTurns { + if turn != nil { + turn.release() + } + } + }() s.resetMtprotoClientQuotas(renewed) // Off the serial writer: a hanging node must not stall traffic accounting. - needRestart = s.applyTrafficRemotePlans(remotePlans) || needRestart + needRestart = s.applyTrafficRemotePlans(remotePlans, remoteTurns) || needRestart if len(disabledNodeIDs) > 0 { s.restartRemoteNodesOnDepletion(disabledNodeIDs) } diff --git a/internal/web/service/inbound_traffic_apply.go b/internal/web/service/inbound_traffic_apply.go index d2d65afd5..f0553c679 100644 --- a/internal/web/service/inbound_traffic_apply.go +++ b/internal/web/service/inbound_traffic_apply.go @@ -7,6 +7,7 @@ import ( "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" "github.com/mhsanaei/3x-ui/v3/internal/xray" "gorm.io/gorm" @@ -60,32 +61,54 @@ func (b *trafficMutationBatch) markNodesTx(tx *gorm.DB) error { return nil } -// applyTrafficRemotePlans is bounded like every per-client node push: the nodes are -// already dirty, so an offline or slow one defers to the reconcile. -func (s *InboundService) applyTrafficRemotePlans(plans []trafficInboundUpdatePlan) bool { +// Reserve on the writer after maintenance commits so a newer client edit cannot pass it. +func reserveTrafficRemoteTurns(plans []trafficInboundUpdatePlan) []*nodeConfigTurn { + if len(plans) == 0 { + return nil + } + turns := make([]*nodeConfigTurn, len(plans)) + for i := range plans { + ib := &plans[i].newInbound + if ib.NodeID != nil { + turns[i] = reserveNodeConfigTurn(*ib.NodeID, ib.Id, nodeClientDelta) + } + } + return turns +} + +// The wait and pushes share one budget per node. Dirty state covers a skipped push. +func (s *InboundService) applyTrafficRemotePlans(plans []trafficInboundUpdatePlan, turns []*nodeConfigTurn) bool { byNode := make(map[int][]int) var nodeIDs []int for i := range plans { - nodeID := 0 - if plans[i].newInbound.NodeID != nil { - nodeID = *plans[i].newInbound.NodeID + id := plans[i].newInbound.NodeID + if id == nil || turns[i] == nil { + continue } + nodeID := *id if _, seen := byNode[nodeID]; !seen { nodeIDs = append(nodeIDs, nodeID) } byNode[nodeID] = append(byNode[nodeID], i) } failed, panics := fanoutInboundResults(nodeIDs, nodeFanoutConcurrency, func(n int) bool { - // One budget per node, not per inbound: a node choosing how many inbounds it reports - // must not choose how long the sync job waits on it before serving other nodes. ctx, cancel := nodePushContext() defer cancel() indexes := byNode[nodeIDs[n]] nodeFailed, nodePanics := fanoutInboundResults(indexes, inboundFanoutConcurrency, func(k int) bool { - plan := &plans[indexes[k]] + index := indexes[k] + turn := turns[index] + defer turn.release() + if !turn.wait(ctx) { + return false + } + plan := &plans[index] rt, push, _, err := s.nodePushPlan(&plan.newInbound) if err == nil && push { err = rt.UpdateInbound(ctx, &plan.oldInbound, &plan.newInbound) + if remote, ok := rt.(*runtime.Remote); ok && err != nil { + remote.ForgetPushedInbound(plan.newInbound.Tag) + } } if err != nil { logger.Debug("traffic post-commit remote apply failed:", err) diff --git a/internal/web/service/node.go b/internal/web/service/node.go index 25ed1f493..f24b6c618 100644 --- a/internal/web/service/node.go +++ b/internal/web/service/node.go @@ -29,6 +29,7 @@ import ( "github.com/mhsanaei/3x-ui/v3/internal/xray" "gorm.io/gorm" + "gorm.io/gorm/clause" ) type HeartbeatPatch struct { @@ -851,41 +852,36 @@ 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 + // Match the attribution reporter's node-before-attribution order. + reporter := tx.Select("guid").Where("id = ?", id) + if tx.Name() == database.DialectPostgres { + reporter = reporter.Clauses(clause.Locking{Strength: "UPDATE"}) + } + if err := reporter.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 } if err := tx.Where("node_id = ?", id).Delete(&model.NodePendingReset{}).Error; err != nil { return err } + if err := tx.Where("node_id = ?", id).Delete(&model.NodePendingClientDelete{}).Error; err != nil { + 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 @@ -904,8 +900,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 { @@ -1076,11 +1073,12 @@ func (s *NodeService) MarkNodeDirtyTx(tx *gorm.DB, id int) error { if tx == nil { return errors.New("nil db transaction") } + now := time.Now().UnixMilli() return tx.Model(model.Node{}). Where("id = ?", id). Updates(map[string]any{ "config_dirty": true, - "config_dirty_at": time.Now().UnixMilli(), + "config_dirty_at": gorm.Expr(database.GreatestExpr("COALESCE(config_dirty_at, 0) + 1", "?"), now), }).Error } diff --git a/internal/web/service/node_bulk_dispatch_test.go b/internal/web/service/node_bulk_dispatch_test.go index 2c572f8d3..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") } @@ -355,8 +355,8 @@ func TestNodeBulkDeleteCompletesAcrossPresentAndMissingSettings(t *testing.T) { if result.Deleted != 1 || len(result.Skipped) != 0 { t.Fatalf("BulkDelete result = %+v, want one deleted client", result) } - if got := fake.deleteClient.Load(); got != 2 { - t.Fatalf("remote DeleteClient calls = %d, want one per node inbound", got) + if got := fake.deleteClient.Load(); got != 1 { + t.Fatalf("remote DeleteClient calls = %d, want one full delete for the node", got) } } diff --git a/internal/web/service/node_client_delete_queue.go b/internal/web/service/node_client_delete_queue.go new file mode 100644 index 000000000..af466dfe2 --- /dev/null +++ b/internal/web/service/node_client_delete_queue.go @@ -0,0 +1,126 @@ +package service + +import ( + "context" + "errors" + "fmt" + "time" + + "github.com/google/uuid" + "gorm.io/gorm" + "gorm.io/gorm/clause" + + "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" +) + +func queueNodeClientDeletes(tx *gorm.DB, nodeID *int, emails []string) ([]model.NodePendingClientDelete, error) { + if nodeID == nil || len(emails) == 0 { + return nil, nil + } + ids := make(map[string]int, len(emails)) + for _, batch := range chunkStrings(emails, sqlInChunk) { + var records []model.ClientRecord + if err := tx.Select("id", "email").Where("email IN ?", batch).Find(&records).Error; err != nil { + return nil, err + } + for _, record := range records { + ids[record.Email] = record.Id + } + } + generation := uuid.NewString() + rows := make([]model.NodePendingClientDelete, 0, len(emails)) + for _, email := range emails { + rows = append(rows, model.NodePendingClientDelete{ + NodeId: *nodeID, Email: email, ClientId: ids[email], Generation: generation, + }) + } + err := tx.Clauses(clause.OnConflict{ + Columns: []clause.Column{{Name: "node_id"}, {Name: "email"}}, + DoUpdates: clause.AssignmentColumns([]string{"client_id", "generation", "last_attempt_at"}), + }).CreateInBatches(rows, 200).Error + return rows, err +} + +func sameNodeClientDelete(db *gorm.DB, row model.NodePendingClientDelete) *gorm.DB { + return db.Model(&model.NodePendingClientDelete{}). + Where("node_pending_client_deletes.node_id = ? AND node_pending_client_deletes.email = ? AND node_pending_client_deletes.generation = ?", + row.NodeId, row.Email, row.Generation) +} + +// 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) (runtime.ClientApplyResult, bool, error) { + db := database.GetDB().WithContext(ctx) + var target struct { + Desired bool + } + result := sameNodeClientDelete(db, row). + Select("EXISTS (" + + "SELECT 1 FROM client_inbounds JOIN inbounds ON inbounds.id = client_inbounds.inbound_id " + + "WHERE client_inbounds.client_id = clients.id AND inbounds.node_id = node_pending_client_deletes.node_id) AS desired"). + Joins("LEFT JOIN clients ON clients.email = node_pending_client_deletes.email"). + Limit(1).Scan(&target) + if result.Error != nil || result.RowsAffected == 0 { + 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 { + var err error + applied, err = rt.DeleteClient(ctx, row.Email) + if err != nil { + return applied, false, err + } + } + return applied, !target.Desired, sameNodeClientDelete(db, row).Delete(&model.NodePendingClientDelete{}).Error +} + +const nodeClientDeletePage = 200 + +// Reconciliation holds the exclusive node turn while delivering one bounded +// page. A failed page keeps the node dirty so snapshots cannot readopt clients. +func deliverNodeClientDeletes(ctx context.Context, nodeID int, rt runtime.Runtime) error { + db := database.GetDB().WithContext(ctx) + var rows []model.NodePendingClientDelete + if err := db.Where("node_id = ?", nodeID).Order("last_attempt_at, email"). + Limit(nodeClientDeletePage).Find(&rows).Error; err != nil { + return err + } + if len(rows) == 0 { + return nil + } + sendCtx, cancel := context.WithTimeout(ctx, nodeClientPushTimeout) + defer cancel() + var firstErr error + for _, row := range rows { + if _, _, err := applyNodeClientDelete(sendCtx, rt, row); err != nil { + if firstErr == nil { + firstErr = err + } + // Rotate a failing row behind entries that have not had a turn. + if err := sameNodeClientDelete(db, row).Update("last_attempt_at", time.Now().UnixNano()).Error; err != nil { + return errors.Join(firstErr, err) + } + if sendCtx.Err() != nil { + break + } + } + } + if firstErr != nil { + return fmt.Errorf("deliver node client deletes: %w", firstErr) + } + if len(rows) == nodeClientDeletePage { + var remaining int64 + if err := db.Model(&model.NodePendingClientDelete{}).Where("node_id = ?", nodeID). + Limit(1).Select("1").Scan(&remaining).Error; err != nil { + return err + } + if remaining != 0 { + return errors.New("more node client deletes awaiting delivery") + } + } + return nil +} diff --git a/internal/web/service/node_client_ips_batch_test.go b/internal/web/service/node_client_ips_batch_test.go new file mode 100644 index 000000000..b808bc8a6 --- /dev/null +++ b/internal/web/service/node_client_ips_batch_test.go @@ -0,0 +1,410 @@ +package service + +import ( + "errors" + "fmt" + "slices" + "sync" + "sync/atomic" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +func TestNodeClientIpRefreshBatchesWrites(t *testing.T) { + setupClientIpTestDB(t) + const clients = 552 + const guid = "edge" + now := time.Now().Unix() + report := make(map[string][]model.ClientIpEntry, clients) + for i := range clients { + report[fmt.Sprintf("client-%04d", i)] = []model.ClientIpEntry{ + {IP: "192.0.2.1", Timestamp: now - 10}, + {IP: "2001:db8::1", Timestamp: now - 20}, + } + } + svc := &InboundService{} + if err := svc.RecordLocalClientIps(guid, report); err != nil { + t.Fatal(err) + } + + counts := countClientIpSQL(t, "node_client_ips") + for _, entries := range report { + entries[0], entries[1] = entries[1], entries[0] + } + if err := svc.MergeClientIpsByGuid(nil, map[string]map[string][]model.ClientIpEntry{guid: report}); err != nil { + t.Fatal(err) + } + if got := counts.creates.Load(); got != 0 { + t.Fatalf("unchanged report executed %d upserts, want none", got) + } + + for email, entries := range report { + if email != "client-0000" { + entries[1].Timestamp = now + } + } + report["new@x"] = slices.Clone(report["client-0001"]) + if err := svc.MergeClientIpsByGuid(nil, map[string]map[string][]model.ClientIpEntry{guid: report}); err != nil { + t.Fatal(err) + } + if got := counts.creates.Load(); got != 3 || counts.affected.Load() != clients { + t.Fatalf("refreshed report executed %d upserts for %d rows, want 3 upserts for %d", got, counts.affected.Load(), clients) + } + + trees, err := svc.GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + if got := len(trees[guid]); got != len(report) { + t.Fatalf("saved clients = %d, want %d", got, len(report)) + } + for email, want := range report { + got := trees[guid][email] + if len(got) != 2 || got[0] != want[0] || got[1] != want[1] { + t.Fatalf("saved IPs for %q = %v, want %v", email, got, want) + } + } +} + +func TestNodeClientIpBatchRetriesConcurrentChange(t *testing.T) { + for _, change := range []string{"insert", "insert in batch", "update", "refresh before delete", "delete before refresh", "replace before refresh"} { + t.Run(change, func(t *testing.T) { + setupClientIpTestDB(t) + db := database.GetDB() + svc := &InboundService{} + now := time.Now().Unix() + first := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - 10} + winner := model.ClientIpEntry{IP: "198.51.100.1", Timestamp: now - 5} + incoming := model.ClientIpEntry{IP: "203.0.113.1", Timestamp: now} + if change == "refresh before delete" { + first.Timestamp = now - clientIpStaleAfterSeconds - 20 + incoming.Timestamp = first.Timestamp + } + + inserting := change == "insert" || change == "insert in batch" + if !inserting { + row := model.NodeClientIp{NodeGuid: "edge", Email: "a@x", Ips: rawClientIpBlob(t, first)} + if err := db.Create(&row).Error; err != nil { + t.Fatal(err) + } + } + replacement := []model.ClientIpEntry{winner} + if change == "delete before refresh" { + replacement = nil + } + if change == "update" { + replacement = []model.ClientIpEntry{first, winner} + } + blob := rawClientIpBlob(t, replacement...) + const callback = "test:node_ip_competing_writer" + wrote := false + if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) { + if wrote || tx.Statement.Table != "node_client_ips" { + return + } + wrote = true + if change == "delete before refresh" || change == "replace before refresh" { + _ = tx.AddError(db.Transaction(func(other *gorm.DB) error { + if err := other.Exec("DELETE FROM node_client_ips WHERE node_guid = ? AND email = ?", "edge", "a@x").Error; err != nil { + return err + } + if change == "replace before refresh" { + return other.Exec("INSERT INTO node_client_ips (node_guid, email, ips) VALUES (?, ?, ?)", "edge", "a@x", blob).Error + } + return nil + })) + return + } + if inserting { + tx.AddError(db.Exec("INSERT INTO node_client_ips (node_guid, email, ips) VALUES (?, ?, ?)", "edge", "a@x", blob).Error) + return + } + tx.AddError(db.Exec("UPDATE node_client_ips SET ips = ? WHERE node_guid = ? AND email = ?", blob, "edge", "a@x").Error) + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) }) + + report := map[string][]model.ClientIpEntry{"a@x": {incoming}} + if change == "insert in batch" { + report["z@x"] = []model.ClientIpEntry{incoming} + } + if err := svc.RecordLocalClientIps("edge", report); err != nil { + t.Fatal(err) + } + tree, err := svc.GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + want := replacement + if change != "refresh before delete" { + want = append(want, incoming) + } + if got := tree["edge"]["a@x"]; !wrote || !slices.Equal(got, want) { + t.Fatalf("saved after concurrent %s = %v, want %v (writer ran: %t)", change, got, want, wrote) + } + if change == "insert in batch" && !slices.Equal(tree["edge"]["z@x"], report["z@x"]) { + t.Fatalf("uncontested row = %v, want %v", tree["edge"]["z@x"], report["z@x"]) + } + }) + } +} + +func TestNodeClientIpBatchRollsBackOnLaterFailure(t *testing.T) { + setupClientIpTestDB(t) + db := database.GetDB() + svc := &InboundService{} + now := time.Now().Unix() + report := make(map[string][]model.ClientIpEntry, 201) + for i := range 201 { + report[fmt.Sprintf("client-%03d", i)] = []model.ClientIpEntry{{IP: "192.0.2.1", Timestamp: now - 10}} + } + if err := svc.RecordLocalClientIps("edge", report); err != nil { + t.Fatal(err) + } + + const callback = "test:node_ip_second_batch_failure" + failure := errors.New("second attribution batch failed") + attempts := 0 + if err := db.Callback().Create().Before("gorm:create").Register(callback, func(tx *gorm.DB) { + if tx.Statement.Table == "node_client_ips" { + attempts++ + if attempts == 2 { + tx.AddError(failure) + } + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Create().Remove(callback) }) + + for _, entries := range report { + entries[0].Timestamp = now + } + if err := svc.RecordLocalClientIps("edge", report); !errors.Is(err, failure) { + t.Fatalf("write error = %v, want %v", err, failure) + } + tree, err := svc.GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + if got := len(tree["edge"]); got != len(report) { + t.Fatalf("saved clients = %d, want %d", got, len(report)) + } + for email, entries := range tree["edge"] { + if len(entries) != 1 || entries[0].Timestamp != now-10 { + t.Fatalf("failed merge changed %q to %v", email, entries) + } + } +} + +func TestPruneNodeClientIpsPreservesConcurrentRefresh(t *testing.T) { + for _, withFreshEntry := range []bool{false, true} { + t.Run(fmt.Sprintf("partially-fresh=%t", withFreshEntry), func(t *testing.T) { + setupClientIpTestDB(t) + db := database.GetDB() + now := time.Now().Unix() + cutoff := now - clientIpStaleAfterSeconds + fresh := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now} + stale := model.ClientIpEntry{IP: fresh.IP, Timestamp: cutoff - 1} + entries := []model.ClientIpEntry{stale} + if withFreshEntry { + entries = append(entries, model.ClientIpEntry{IP: "203.0.113.1", Timestamp: now - 5}) + } + if err := db.Create(&model.NodeClientIp{NodeGuid: "edge", Email: "a@x", Ips: rawClientIpBlob(t, entries...)}).Error; err != nil { + t.Fatal(err) + } + + const callback = "test:refresh_during_prune" + refresh := append(slices.Clone(entries[1:]), fresh) + blob := rawClientIpBlob(t, refresh...) + wrote := false + if err := db.Callback().Query().After("gorm:query").Register(callback, func(tx *gorm.DB) { + if !wrote && tx.Statement.Table == "node_client_ips" { + wrote = true + tx.AddError(db.Exec("UPDATE node_client_ips SET ips = ? WHERE node_guid = ? AND email = ?", blob, "edge", "a@x").Error) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(callback) }) + if err := pruneStaleNodeClientIps(cutoff); err != nil { + t.Fatal(err) + } + tree, err := (&InboundService{}).GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + if got := tree["edge"]["a@x"]; !wrote || !slices.Equal(got, refresh) { + t.Fatalf("saved IPs after prune = %v, want %v (refresh ran: %t)", got, refresh, wrote) + } + }) + } +} + +func TestConcurrentPolledReportsMergeMixedRowsForSharedDescendant(t *testing.T) { + setupClientIpTestDB(t) + db := database.GetDB() + svc := &InboundService{} + const guid = "shared-descendant" + now := time.Now().Unix() + parents := []*model.Node{ + {Name: "parent-a", Guid: "parent-a", Address: "192.0.2.1", Port: 443, Enable: true, Status: "online"}, + {Name: "parent-b", Guid: "parent-b", Address: "192.0.2.2", Port: 443, Enable: true, Status: "online"}, + } + clients := []model.Client{{Email: "a@example.test", Enable: true}, {Email: "z@example.test", Enable: true}} + for i, node := range parents { + if err := db.Create(node).Error; err != nil { + t.Fatal(err) + } + inbound := &model.Inbound{NodeID: &node.Id, OriginNodeGuid: guid, UserId: 1, Protocol: model.VLESS, Port: 25000 + i, Tag: node.Name} + if err := db.Create(inbound).Error; err != nil { + t.Fatal(err) + } + if err := (&ClientService{}).SyncInbound(db, inbound.Id, clients); err != nil { + t.Fatal(err) + } + } + if err := svc.RecordLocalClientIps(guid, map[string][]model.ClientIpEntry{ + clients[0].Email: {{IP: "192.0.2.1", Timestamp: now - 20}}, + }); err != nil { + t.Fatal(err) + } + + read := make(chan struct{}) + continueFirst := make(chan struct{}) + unblock := sync.OnceFunc(func() { close(continueFirst) }) + var reads atomic.Int32 + var workers sync.WaitGroup + const hook = "test:shared-descendant-mixed-insert" + if err := db.Callback().Query().After("gorm:query").Register(hook, func(tx *gorm.DB) { + if tx.Statement.Table == "node_client_ips" && reads.Add(1) == 1 { + close(read) + <-continueFirst + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + unblock() + workers.Wait() + _ = db.Callback().Query().Remove(hook) + }) + report := func(node *model.Node, ip string, timestamp int64) error { + obs := []model.ClientIpEntry{{IP: ip, Timestamp: timestamp}} + return svc.MergePolledClientIpsByGuid(t.Context(), node, map[string]map[string][]model.ClientIpEntry{ + guid: {clients[0].Email: obs, clients[1].Email: obs}, + }) + } + done := make(chan error, 1) + workers.Go(func() { done <- report(parents[0], "198.51.100.1", now-5) }) + select { + case <-read: + case err := <-done: + t.Fatalf("first reporter did not plan an attribution transaction: %v", err) + case <-time.After(3 * time.Second): + t.Fatal("first reporter did not reach the attribution read") + } + if err := report(parents[1], "203.0.113.1", now); err != nil { + t.Fatal(err) + } + unblock() + if err := <-done; err != nil { + t.Fatal(err) + } + if reads.Load() != 3 { + t.Fatalf("read attempts = %d, want initial pair plus one whole-GUID retry", reads.Load()) + } + trees, err := svc.GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + created := []model.ClientIpEntry{{IP: "198.51.100.1", Timestamp: now - 5}, {IP: "203.0.113.1", Timestamp: now}} + if got := trees[guid][clients[1].Email]; !slices.Equal(got, created) { + t.Fatalf("competing insert lost an observation: got %+v, want %+v", got, created) + } + updated := append([]model.ClientIpEntry{{IP: "192.0.2.1", Timestamp: now - 20}}, created...) + if got := trees[guid][clients[0].Email]; !slices.Equal(got, updated) { + t.Fatalf("mixed update lost an observation: got %+v, want %+v", got, updated) + } +} + +func TestNodeClientIpLaterBatchCASRollsBackBeforeRetry(t *testing.T) { + for _, exhaust := range []bool{false, true} { + t.Run(fmt.Sprintf("exhaust=%t", exhaust), func(t *testing.T) { + setupClientIpTestDB(t) + db := database.GetDB() + svc := &InboundService{} + const guid = "later-cas" + now := time.Now().Unix() + original := rawClientIpBlob(t, model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - 30}) + rows := make([]model.NodeClientIp, nodeClientIpWriteBatch+1) + report := make(map[string][]model.ClientIpEntry, len(rows)) + for i := range rows { + email := fmt.Sprintf("client-%03d@x", i) + rows[i] = model.NodeClientIp{NodeGuid: guid, Email: email, Ips: original} + report[email] = []model.ClientIpEntry{{IP: "192.0.2.1", Timestamp: now}} + } + if err := db.CreateInBatches(&rows, 100).Error; err != nil { + t.Fatal(err) + } + first, last := rows[0], rows[len(rows)-1] + attempts := 0 + const hook = "test:conflict-in-last-attribution-batch" + if err := db.Callback().Query().After("gorm:query").Register(hook, func(tx *gorm.DB) { + if tx.Statement.Table != "node_client_ips" { + return + } + attempts++ + var got string + if err := db.Raw("SELECT ips FROM node_client_ips WHERE id = ?", first.Id).Scan(&got).Error; err != nil { + _ = tx.AddError(err) + return + } + if got != original { + _ = tx.AddError(fmt.Errorf("earlier batch committed before attempt %d: %s", attempts, got)) + return + } + if exhaust || attempts == 1 { + blob := fmt.Sprintf(`[{"ip":"198.51.100.2","timestamp":%d}]`, now-int64(attempts)) + _ = tx.AddError(db.Exec("UPDATE node_client_ips SET ips = ? WHERE id = ?", blob, last.Id).Error) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(hook) }) + err := svc.RecordLocalClientIps(guid, report) + if exhaust { + if !errors.Is(err, errNodeClientIpConflict) || attempts != ClientIpCasRetries { + t.Fatalf("exhaustion = %v, attempts=%d", err, attempts) + } + } else if err != nil || attempts != 2 { + t.Fatalf("retry = %v, attempts=%d", err, attempts) + } + var stored string + if err := db.Raw("SELECT ips FROM node_client_ips WHERE id = ?", first.Id).Scan(&stored).Error; err != nil { + t.Fatal(err) + } + want := original + if !exhaust { + want = rawClientIpBlob(t, report[first.Email]...) + var late string + if err := db.Raw("SELECT ips FROM node_client_ips WHERE id = ?", last.Id).Scan(&late).Error; err != nil { + t.Fatal(err) + } + wantLate := rawClientIpBlob(t, model.ClientIpEntry{IP: "198.51.100.2", Timestamp: now - 1}, report[last.Email][0]) + if late != wantLate { + t.Fatalf("retry failed to merge the winning observation: %s want %s", late, wantLate) + } + } + if stored != want { + t.Fatalf("first batch after attempt sequence = %s, want %s", stored, want) + } + }) + } +} 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_full_reconciliation_test.go b/internal/web/service/node_full_reconciliation_test.go new file mode 100644 index 000000000..7ae3cce0d --- /dev/null +++ b/internal/web/service/node_full_reconciliation_test.go @@ -0,0 +1,336 @@ +package service + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "strings" + "sync" + "testing" + "time" + + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/config" + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/testpg" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func TestNodeFullReconciliationReusesLinkDiff(t *testing.T) { + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + const nodeID = 1 + seedNodeRow(t, db, &model.Node{Id: nodeID, Name: "remote", Address: "192.0.2.1", Port: 2053, Enable: true}) + createNodeInbound(t, db, nodeID, "remote-first", 41001) + createNodeInbound(t, db, nodeID, "remote-second", 41002) + var inbounds []model.Inbound + if err := db.Where("node_id = ?", nodeID).Order("id").Find(&inbounds).Error; err != nil { + t.Fatal(err) + } + keep := model.Client{Email: "keep@example.test", Enable: true, Comment: "remote comment"} + move := model.Client{Email: "move@example.test", Enable: true} + local := model.Client{Email: "still-local@example.test", Enable: true} + other := model.Client{Email: "still-on-other-node@example.test", Enable: true} + before := []model.Client{keep, move, local, other} + const dropped = sqlInChunk + 3 + for i := range dropped { + before = append(before, model.Client{Email: fmt.Sprintf("drop-%04d@example.test", i), Enable: true}) + } + clientSvc := &ClientService{} + localInbound := model.Inbound{UserId: 1, Tag: "local-inbound", Port: 41003, Protocol: model.VLESS, Enable: true} + if err := db.Create(&localInbound).Error; err != nil { + t.Fatal(err) + } + if err := clientSvc.SyncInbound(db, localInbound.Id, []model.Client{local}); err != nil { + t.Fatal(err) + } + const otherNodeID = 2 + seedNodeRow(t, db, &model.Node{Id: otherNodeID, Name: "other", Address: "192.0.2.2", Port: 2053, Enable: true}) + createNodeInboundWithClient(t, db, otherNodeID, "other-node-inbound", 41004, other.Email) + if err := clientSvc.SyncInbound(db, inbounds[0].Id, before); err != nil { + t.Fatal(err) + } + if err := clientSvc.SyncInbound(db, inbounds[1].Id, []model.Client{keep}); err != nil { + t.Fatal(err) + } + if err := db.Model(&model.ClientRecord{}).Where("email = ?", keep.Email). + UpdateColumn("comment", "operator note").Error; err != nil { + t.Fatal(err) + } + keep.LimitIP = 3 + last := model.Client{Email: "new@example.test", Enable: true, Comment: "imported note"} + wire := func(tag string, clients ...model.Client) *model.Inbound { + t.Helper() + raw, err := json.Marshal(map[string]any{"clients": clients}) + if err != nil { + t.Fatal(err) + } + return &model.Inbound{Tag: tag, Protocol: model.VLESS, Settings: string(raw)} + } + snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{ + wire(inbounds[0].Tag, keep), wire(inbounds[1].Tag, keep, move, last), + }} + snap.Inbounds[0].ClientStats = []xray.ClientTraffic{{Email: keep.Email, Enable: true}} + queries := recordExecutedSQL(t, db) + const updateCallback = "test:record-node-reconciliation-updates" + if err := db.Callback().Update().After("gorm:update").Register(updateCallback, func(tx *gorm.DB) { + *queries = append(*queries, tx.Statement.SQL.String()) + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(updateCallback) }) + svc := &InboundService{} + if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); err != nil { + t.Fatal(err) + } + markWrites := 0 + for _, sql := range *queries { + stmt := strings.ToLower(sql) + if strings.HasPrefix(stmt, "select email, comment ") || + (strings.Contains(stmt, "count(*)") && strings.Contains(stmt, "clients.email =")) { + t.Fatalf("reconciliation repeated a per-inbound comment or per-client attachment read: %s", sql) + } + if strings.HasPrefix(stmt, "update ") && strings.Contains(stmt, "sync_orphaned_by") && + strings.Contains(stmt, "not exists") { + markWrites++ + } + if strings.HasPrefix(stmt, "update ") && strings.Contains(stmt, "comment") { + t.Fatalf("remote reconciliation unnecessarily wrote the operator's comment: %s", sql) + } + } + if markWrites != 2 { + t.Fatalf("marked a %d-client drop in %d writes, want 2", dropped, markWrites) + } + var marked []model.ClientRecord + if err := db.Where("sync_orphaned_at > 0").Find(&marked).Error; err != nil { + t.Fatal(err) + } + if len(marked) != dropped { + t.Fatalf("marked %d removed clients, want %d", len(marked), dropped) + } + for _, row := range marked { + if row.SyncOrphanedBy != nodeID || !strings.HasPrefix(row.Email, "drop-") { + t.Fatalf("unexpected orphan: %q, node %d", row.Email, row.SyncOrphanedBy) + } + } + for email, want := range map[string]string{keep.Email: "operator note", last.Email: "imported note"} { + var row model.ClientRecord + if err := db.Where("email = ?", email).Take(&row).Error; err != nil || row.Comment != want { + t.Fatalf("comment for %q = %q, want %q (%v)", email, row.Comment, want, err) + } + } + var movedLinks []int + if err := db.Table("client_inbounds").Joins("JOIN clients ON clients.id = client_inbounds.client_id"). + Where("clients.email = ?", move.Email).Pluck("inbound_id", &movedLinks).Error; err != nil { + t.Fatal(err) + } + if len(movedLinks) != 1 || movedLinks[0] != inbounds[1].Id { + t.Fatalf("move lost its destination: %v", movedLinks) + } + snap.Inbounds[0].ClientStats = []xray.ClientTraffic{{Email: keep.Email, Up: 100, Down: 50, Enable: true}} + for range 2 { + if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); err != nil { + t.Fatal(err) + } + } + baseline := model.NodeClientTraffic{} + if err := db.Where("node_id = ? AND email = ?", nodeID, keep.Email).Take(&baseline).Error; err != nil { + t.Fatal(err) + } + traffic := readTraffic(t, db, keep.Email) + if baseline.Up != 100 || baseline.Down != 50 || traffic.Up != 100 || traffic.Down != 50 { + t.Fatalf("reapplied snapshot duplicated traffic or lost the baseline: traffic=%+v baseline=%+v", traffic, baseline) + } + if got := readOrphanMark(t, db, marked[0].Email); got != marked[0].SyncOrphanedAt { + t.Fatalf("replayed snapshot changed the orphan grace timestamp to %d", got) + } +} + +func TestNodeFullReconciliationRollsBackOrphanWriteFailure(t *testing.T) { + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + const nodeID = 1 + const tag = "remote-inbound" + seedNodeRow(t, db, &model.Node{Id: nodeID, Name: "remote", Address: "192.0.2.1", Port: 2053, Enable: true}) + svc := &InboundService{} + const keepEmail = "keep@example.test" + const oldSettings = `{"clients":[{"email":"keep@example.test","enable":true},{"email":"detached@example.test","enable":true}]}` + syncNodeWithSettings(t, svc, nodeID, tag, oldSettings, xray.ClientTraffic{Email: keepEmail, Enable: true, Up: 100}) + var oldInbound model.Inbound + if err := db.Where("tag = ?", tag).Take(&oldInbound).Error; err != nil { + t.Fatal(err) + } + + writeErr := errors.New("injected orphan write failure") + const callbackName = "test:fail-node-orphan-write" + if err := db.Callback().Update().Before("gorm:update").Register(callbackName, func(tx *gorm.DB) { + updates, ok := tx.Statement.Dest.(map[string]any) + if ok && tx.Statement.Table == "clients" && updates["sync_orphaned_by"] == nodeID { + _ = tx.AddError(writeErr) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(callbackName) }) + snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{{ + Tag: tag, Settings: `{"clients":[{"email":"keep@example.test","enable":true}]}`, + ClientStats: []xray.ClientTraffic{{Email: keepEmail, Enable: true, Up: 160}}, + }}} + if _, err := svc.SetRemoteTraffic(nodeID, snap, false, false); !errors.Is(err, writeErr) { + t.Fatalf("merge error = %v, want %v", err, writeErr) + } + var links int64 + if err := db.Model(&model.ClientInbound{}).Count(&links).Error; err != nil || links != 2 { + t.Fatalf("rollback left %d links, want 2 (%v)", links, err) + } + if mark := readOrphanMark(t, db, "detached@example.test"); mark != 0 { + t.Fatalf("rollback left orphan mark %d", mark) + } + var inbound model.Inbound + if err := db.First(&inbound, oldInbound.Id).Error; err != nil { + t.Fatal(err) + } + var baseline model.NodeClientTraffic + if err := db.Where("node_id = ? AND email = ?", nodeID, keepEmail).Take(&baseline).Error; err != nil { + t.Fatal(err) + } + if inbound.Settings != oldInbound.Settings || baseline.Up != 100 || readTraffic(t, db, keepEmail).Up != 100 { + t.Fatalf("rollback leaked snapshot settings, counters or baseline: settings=%s baseline=%+v", inbound.Settings, baseline) + } +} + +func isolateNodeReconciliationDB(t *testing.T) { + t.Helper() + cleanup, err := testpg.IsolatePackage("node_reconciliation") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) +} + +func TestNodeFullReconciliationKeepsConcurrentCommentPostgres(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires concurrent PostgreSQL writes") + } + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + node := &model.Node{Enable: true, Name: "comment-test", Address: "192.0.2.1", Port: 2053} + seedNodeRow(t, db, node) + const email = "comment@example.test" + const tag = "remote-comment" + svc := &InboundService{} + syncNodeWithSettings(t, svc, node.Id, tag, clientsSettings(t, []model.Client{{Email: email, Enable: true, Comment: "old note"}})) + + read, release := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + var gate sync.Once + var wg sync.WaitGroup + const hook = "test:comment-after-reconcile-read" + if err := db.Callback().Update().Before("gorm:update").Register(hook, func(tx *gorm.DB) { + row, ok := tx.Statement.Dest.(*model.ClientRecord) + if ok && row.Email == email && row.LimitIP == 3 { + gate.Do(func() { close(read); <-release }) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + unblock() + wg.Wait() + _ = db.Callback().Update().Remove(hook) + }) + + snap := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{{ + Tag: tag, Protocol: model.VLESS, + Settings: clientsSettings(t, []model.Client{{Email: email, Enable: true, LimitIP: 3, Comment: "remote note"}}), + }}} + done := make(chan error, 1) + wg.Go(func() { + _, err := svc.SetRemoteTraffic(node.Id, snap, false, false) + done <- err + }) + select { + case <-read: + case err := <-done: + t.Fatalf("reconciliation never reached the client write barrier: %v", err) + case <-time.After(5 * time.Second): + t.Fatal("blocked before reaching the client write barrier") + } + + ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second) + defer cancel() + if err := db.WithContext(ctx).Model(&model.ClientRecord{}).Where("email = ?", email). + UpdateColumn("comment", "concurrent master note").Error; err != nil { + t.Fatal(err) + } + unblock() + if err := <-done; err != nil { + t.Fatal(err) + } + var row model.ClientRecord + if err := db.Where("email = ?", email).Take(&row).Error; err != nil { + t.Fatal(err) + } + if row.Comment != "concurrent master note" || row.LimitIP != 3 { + t.Fatalf("reconciliation lost the note or did not apply the remote edit: comment=%q limitIP=%d", row.Comment, row.LimitIP) + } +} + +func TestNodeFullReconciliationExcludesRolledBackDetaches(t *testing.T) { + isolateNodeReconciliationDB(t) + db := initTrafficTestDB(t) + node := &model.Node{Enable: true, Name: "savepoint-test", Address: "192.0.2.1", Port: 2053} + seedNodeRow(t, db, node) + svc := &InboundService{} + const rejectedTag = "rejected-inbound" + const acceptedTag = "accepted-inbound" + const rejectedEmail = "rejected@example.test" + const removedEmail = "removed@example.test" + keep := model.Client{Email: "keep@example.test", Enable: true} + initial := func(tag, email string, port int) *model.Inbound { + return &model.Inbound{ + Tag: tag, Port: port, Protocol: model.VLESS, Enable: true, + Settings: clientsSettings(t, []model.Client{keep, {Email: email, Enable: true}}), + } + } + original := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{ + initial(rejectedTag, rejectedEmail, 41010), initial(acceptedTag, removedEmail, 41011), + }} + if _, err := svc.SetRemoteTraffic(node.Id, original, false, false); err != nil { + t.Fatal(err) + } + var rejected model.Inbound + if err := db.Where("tag = ?", rejectedTag).Take(&rejected).Error; err != nil { + t.Fatal(err) + } + const hook = "test:reject-detach-after-delete" + rejectedDelete := false + if err := db.Callback().Delete().After("gorm:delete").Register(hook, func(tx *gorm.DB) { + if tx.Statement.Table == "client_inbounds" && len(tx.Statement.Vars) > 0 && + tx.Statement.Vars[0] == rejected.Id && tx.RowsAffected == 1 { + rejectedDelete = true + _ = tx.AddError(errors.New("injected failure after link deletion")) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Delete().Remove(hook) }) + snapshot := &runtime.TrafficSnapshot{Inbounds: []*model.Inbound{ + {Tag: rejectedTag, Port: 41010, Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, []model.Client{keep})}, + {Tag: acceptedTag, Port: 41011, Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, []model.Client{keep})}, + }} + if _, err := svc.SetRemoteTraffic(node.Id, snapshot, false, false); err != nil { + t.Fatal(err) + } + if !rejectedDelete || readOrphanMark(t, db, rejectedEmail) != 0 || readOrphanMark(t, db, removedEmail) == 0 { + t.Fatalf("savepoint did not isolate orphan candidates: injected=%v", rejectedDelete) + } + var links int64 + if err := db.Model(&model.ClientInbound{}).Where("inbound_id = ?", rejected.Id).Count(&links).Error; err != nil || links != 2 { + t.Fatalf("failed reconciliation did not restore its two memberships: %d (%v)", links, err) + } +} diff --git a/internal/web/service/node_http_fake_test.go b/internal/web/service/node_http_fake_test.go index 609123e9d..aaf21b930 100644 --- a/internal/web/service/node_http_fake_test.go +++ b/internal/web/service/node_http_fake_test.go @@ -19,11 +19,14 @@ 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 + clientAdds []ClientCreatePayload + clientAddEvents chan ClientCreatePayload // hold makes every non-list request block until the master gives up. hold bool release chan struct{} @@ -31,7 +34,10 @@ type fakeNodeHTTP struct { func newFakeNodeHTTP(t *testing.T) *fakeNodeHTTP { t.Helper() - f := &fakeNodeHTTP{tags: map[string]int{}, hits: map[string]int{}, release: make(chan struct{})} + f := &fakeNodeHTTP{ + tags: map[string]int{}, hits: map[string]int{}, release: make(chan struct{}), + clientAddEvents: make(chan ClientCreatePayload, 16), + } f.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") f.mu.Lock() @@ -56,7 +62,25 @@ 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 strings.HasSuffix(r.URL.Path, "/clients/add") { + var payload ClientCreatePayload + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + f.mu.Lock() + f.clientAdds = append(f.clientAdds, payload) + f.mu.Unlock() + select { + case f.clientAddEvents <- payload: + default: + } + } if hold { // Drain first: the server only notices a client disconnect once the // body is consumed, and Close would otherwise wait on this forever. @@ -67,6 +91,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/service/node_ip_lock_order_postgres_test.go b/internal/web/service/node_ip_lock_order_postgres_test.go new file mode 100644 index 000000000..a35fe9651 --- /dev/null +++ b/internal/web/service/node_ip_lock_order_postgres_test.go @@ -0,0 +1,534 @@ +package service + +import ( + "context" + "errors" + "fmt" + "maps" + "slices" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/jackc/pgx/v5/pgconn" + "gorm.io/gorm" + + "github.com/mhsanaei/3x-ui/v3/internal/config" + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" +) + +type nodeIPLockReportKey struct{} + +type nodeIPLockEvent struct { + PID int + SQL string + Err error +} + +func nodeIPTestBackend(tx *gorm.DB) nodeIPLockEvent { + event := nodeIPLockEvent{SQL: tx.Statement.SQL.String()} + event.Err = tx.Session(&gorm.Session{NewDB: true}).Raw("SELECT pg_backend_pid()").Scan(&event.PID).Error + return event +} + +func waitNodeIPTestValue[T any](t *testing.T, ctx context.Context, ready <-chan T, stage string) T { + t.Helper() + select { + case value := <-ready: + return value + case <-ctx.Done(): + t.Fatalf("%s: %v", stage, ctx.Err()) + var zero T + return zero + } +} + +func nodeIPBlocker(db *gorm.DB, waiter, blocker int) (bool, error) { + var blocked bool + err := db.Raw("SELECT ? = ANY(pg_blocking_pids(?))", blocker, waiter).Scan(&blocked).Error + return blocked, err +} + +func waitNodeIPBlocked(t *testing.T, ctx context.Context, db *gorm.DB, waiter, blocker int) { + t.Helper() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + blocked, err := nodeIPBlocker(db.WithContext(ctx), waiter, blocker) + if err != nil { + t.Fatal(err) + } + if blocked { + return + } + select { + case <-ctx.Done(): + t.Fatalf("backend %d never waited on %d: %v", waiter, blocker, ctx.Err()) + case <-ticker.C: + } + } +} + +func seedNodeIPLockFixture(t *testing.T, name string, port int, emails ...string) (model.Node, []model.Client) { + t.Helper() + db := database.GetDB() + node := model.Node{ + Name: name, Guid: name, Scheme: "http", Address: "127.0.0.1", Port: port, + BasePath: "/", AllowPrivateAddress: true, ApiToken: "test", Enable: true, Status: "online", + } + if err := db.Create(&node).Error; err != nil { + t.Fatal(err) + } + clients := make([]model.Client, 0, len(emails)) + for i, email := range emails { + clients = append(clients, model.Client{ + Email: email, SubID: email, Enable: true, + ID: fmt.Sprintf("00000000-0000-4000-8000-%012d", port*10+i), + }) + } + inbound := model.Inbound{ + NodeID: &node.Id, UserId: 1, Port: port, Tag: name, + Protocol: model.VLESS, Enable: true, Settings: clientsSettings(t, clients), + } + if err := db.Create(&inbound).Error; err != nil { + t.Fatal(err) + } + if err := (&ClientService{}).SyncInbound(db, inbound.Id, clients); err != nil { + t.Fatal(err) + } + return node, clients +} + +func TestPostgresNodeIPReporterClientLockOrder(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires PostgreSQL row locks") + } + for _, operation := range []string{"delete", "rename", "bulk_delete"} { + t.Run(operation, func(t *testing.T) { testNodeIPReporterClientLockOrder(t, operation) }) + } +} + +func testNodeIPReporterClientLockOrder(t *testing.T, operation string) { + t.Helper() + setupClientIpTestDB(t) + resetTrafficWriterForTest(t) + StartTrafficWriter() + t.Cleanup(StopTrafficWriter) + db := database.GetDB() + const target, secondTarget, survivor = "a-target@example.test", "b-target@example.test", "z-survivor@example.test" + const healthyEmail = "healthy@example.test" + nodeEmails := []string{target, survivor} + removed := []string{target} + if operation == "bulk_delete" { + nodeEmails = append(nodeEmails, secondTarget) + removed = append(removed, secondTarget) + } + node, clients := seedNodeIPLockFixture(t, "contended-edge", 23081, nodeEmails...) + healthy, _ := seedNodeIPLockFixture(t, "healthy-edge", 23082, healthyEmail) + inbounds, clientService := &InboundService{}, &ClientService{} + record, err := clientService.GetRecordByEmail(nil, target) + if err != nil { + t.Fatal(err) + } + now := time.Now().Unix() + before := model.ClientIpEntry{IP: "192.0.2.10", Timestamp: now - 20} + refreshed := model.ClientIpEntry{IP: before.IP, Timestamp: now - 2} + fresh := model.ClientIpEntry{IP: "192.0.2.20", Timestamp: now - 1} + seedEmails := append([]string{healthyEmail}, nodeEmails...) + slices.Reverse(seedEmails) + for _, email := range seedEmails { + if err := db.Create(&model.InboundClientIps{ClientEmail: email, Ips: marshalIps(t, before)}).Error; err != nil { + t.Fatal(err) + } + } + payload := marshalIps(t, refreshed, fresh) + ctx, cancel := context.WithTimeout(t.Context(), 12*time.Second) + defer cancel() + reportCtx := context.WithValue(ctx, nodeIPLockReportKey{}, true) + mutationLocked := make(chan nodeIPLockEvent, 1) + reportWriting := make(chan nodeIPLockEvent, 1) + resumeMutation := make(chan struct{}) + releaseMutation := sync.OnceFunc(func() { close(resumeMutation) }) + var mutationStarted, reportStarted bool + mutationDone, reportDone := make(chan struct{}), make(chan struct{}) + var mutationErr, reportErr error + defer func() { + releaseMutation() + if mutationStarted { + <-mutationDone + } + if reportStarted { + <-reportDone + } + }() + blockMutation := func(tx *gorm.DB) { + if tx.Statement.Table != "inbound_client_ips" || tx.RowsAffected == 0 || tx.Error != nil || + tx.Statement.Context.Value(nodeIPLockReportKey{}) != nil { + return + } + select { + case mutationLocked <- nodeIPTestBackend(tx): + <-resumeMutation + default: + } + } + const cb = "test:node_ip_lock_order" + var hookedMutation bool + mutationHook := func(tx *gorm.DB) { + if tx.Statement.Table == "inbound_client_ips" && !hookedMutation { + hookedMutation = true + blockMutation(tx) + } + } + if operation == "rename" { + if err := db.Callback().Update().After("gorm:update").Register(cb+"-mutation", mutationHook); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(cb + "-mutation") }) + } else { + if err := db.Callback().Delete().After("gorm:delete").Register(cb+"-mutation", mutationHook); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Delete().Remove(cb + "-mutation") }) + } + if err := db.Callback().Update().Before("gorm:update").Register(cb+"-report", func(tx *gorm.DB) { + if tx.Statement.Table == "inbound_client_ips" && tx.Statement.Context.Value(nodeIPLockReportKey{}) != nil { + select { + case reportWriting <- nodeIPTestBackend(tx): + default: + } + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(cb + "-report") }) + + mutationStarted = true + go func() { + defer close(mutationDone) + switch operation { + case "delete": + _, mutationErr = clientService.Delete(inbounds, record.Id, false) + case "rename": + updated := clients[0] + updated.Email = "renamed@example.test" + _, mutationErr = clientService.Update(inbounds, record.Id, updated, 0) + case "bulk_delete": + result, _, err := clientService.BulkDelete(inbounds, []string{secondTarget, target}, false) + mutationErr = err + if err == nil && (result.Deleted != len(removed) || len(result.Skipped) != 0) { + mutationErr = fmt.Errorf("bulk delete did not commit: %+v", result) + } + } + }() + mutation := waitNodeIPTestValue(t, ctx, mutationLocked, "mutation holds flat IP row") + if mutation.Err != nil { + t.Fatal(mutation.Err) + } + reportStarted = true + payloadRows := make([]model.InboundClientIps, 0, len(nodeEmails)) + for _, email := range nodeEmails { + payloadRows = append(payloadRows, model.InboundClientIps{ClientEmail: email, Ips: payload}) + } + go func() { + defer close(reportDone) + reportErr = inbounds.MergePolledNodeClientIps(reportCtx, &node, payloadRows) + }() + report := waitNodeIPTestValue(t, ctx, reportWriting, "report attempts flat IP write") + if report.Err != nil { + t.Fatal(report.Err) + } + waitNodeIPBlocked(t, ctx, db, report.PID, mutation.PID) + + healthyCtx, stopHealthy := context.WithTimeout(ctx, 2*time.Second) + err = inbounds.MergePolledNodeClientIps(healthyCtx, &healthy, []model.InboundClientIps{{ClientEmail: healthyEmail, Ips: payload}}) + stopHealthy() + if err != nil { + t.Fatalf("independent reporter stalled: %v", err) + } + releaseMutation() + logNodeIPWaitCycle(t, ctx, db, mutation, report, mutationDone, reportDone) + + for name, err := range map[string]error{"mutation": mutationErr, "report": reportErr} { + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "40P01" { + t.Errorf("%s SQLSTATE %s: %s\n%s", name, pgErr.Code, pgErr.Detail, pgErr.Where) + } else if err != nil { + t.Errorf("%s: %v", name, err) + } + } + if t.Failed() { + return + } + var records int64 + if err := db.Model(&model.ClientRecord{}).Where("email IN ?", removed).Count(&records).Error; err != nil { + t.Fatal(err) + } + for _, email := range removed { + if _, exists := readClientIps(t, email); exists || records != 0 { + t.Fatalf("obsolete email %s survived: IP row=%t, client records=%d", email, exists, records) + } + } + if operation != "rename" { + var pending int64 + if err := db.Model(&model.NodePendingClientDelete{}).Where("node_id = ? AND email IN ?", node.Id, removed). + Count(&pending).Error; err != nil || pending != int64(len(removed)) { + t.Fatalf("permanent-delete outbox count = %d, want %d: %v", pending, len(removed), err) + } + } + if operation == "rename" { + got, exists := readClientIps(t, "renamed@example.test") + if !exists || !maps.Equal(got, map[string]int64{before.IP: before.Timestamp}) { + t.Fatalf("rename should move only the committed history: %v", got) + } + } + _, _, dirty, generation, err := (&NodeService{}).NodeSyncState(node.Id) + if err != nil || !dirty || generation <= node.ConfigDirtyAt { + t.Fatalf("dirty generation after %s: dirty=%t generation=%d err=%v", operation, dirty, generation, err) + } + want := map[string]int64{refreshed.IP: refreshed.Timestamp, fresh.IP: fresh.Timestamp} + for _, email := range []string{survivor, healthyEmail} { + if got, _ := readClientIps(t, email); !maps.Equal(got, want) { + t.Errorf("%s: IP union = %v, want %v", email, got, want) + } + } +} + +func logNodeIPWaitCycle(t *testing.T, ctx context.Context, db *gorm.DB, mutation, report nodeIPLockEvent, mutationDone, reportDone <-chan struct{}) { + t.Helper() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + select { + case <-mutationDone: + waitNodeIPTestValue(t, ctx, reportDone, "report completion") + return + case <-reportDone: + waitNodeIPTestValue(t, ctx, mutationDone, "mutation completion") + return + case <-ticker.C: + cycle, err := nodeIPBlocker(db.WithContext(ctx), mutation.PID, report.PID) + if err != nil { + t.Fatal(err) + } + if !cycle { + continue + } + var queries []struct { + PID int `gorm:"column:pid"` + Query string + WaitEvent string + } + if err := db.WithContext(ctx).Raw( + "SELECT pid, query, wait_event FROM pg_stat_activity WHERE pid IN (?, ?) ORDER BY pid", + mutation.PID, report.PID, + ).Scan(&queries).Error; err != nil { + t.Fatal(err) + } + t.Logf("mutual PostgreSQL blockers: %+v; first mutation: %s", queries, mutation.SQL) + var ungranted []struct { + PID int `gorm:"column:pid"` + Mode string + Type string + } + if err := db.WithContext(ctx).Raw( + "SELECT pid, mode, locktype AS type FROM pg_locks WHERE pid IN (?, ?) AND NOT granted ORDER BY pid", + mutation.PID, report.PID, + ).Scan(&ungranted).Error; err != nil { + t.Fatal(err) + } + t.Logf("ungranted PostgreSQL locks: %+v", ungranted) + waitNodeIPTestValue(t, ctx, mutationDone, "deadlock victim releases mutation") + waitNodeIPTestValue(t, ctx, reportDone, "deadlock victim releases report") + return + case <-ctx.Done(): + t.Fatalf("waiting for database transactions: %v", ctx.Err()) + } + } +} + +func TestPostgresFlatIPReporterLifecycleCommit(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires PostgreSQL row locks") + } + for _, change := range []string{"disable", "delete", "endpoint", "guid"} { + t.Run(change, func(t *testing.T) { testFlatIPReporterLifecycleCommit(t, change) }) + } +} + +func testFlatIPReporterLifecycleCommit(t *testing.T, change string) { + t.Helper() + setupClientIpTestDB(t) + db := database.GetDB() + const first, second = "a@example.test", "z@example.test" + node, _ := seedNodeIPLockFixture(t, "replaced-edge", 23083, first, second) + now := time.Now().Unix() + old := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - 10} + fresh := model.ClientIpEntry{IP: "192.0.2.2", Timestamp: now - 1} + var rows []model.InboundClientIps + for _, email := range []string{first, second} { + rows = append(rows, model.InboundClientIps{ClientEmail: email, Ips: marshalIps(t, old)}) + } + if err := db.Create(&rows).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&model.NodeClientIp{NodeGuid: node.Guid, Email: first, Ips: rows[0].Ips}).Error; err != nil { + t.Fatal(err) + } + payload := marshalIps(t, fresh) + for i := range rows { + rows[i].Ips = payload + } + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + reportCtx := context.WithValue(ctx, nodeIPLockReportKey{}, true) + staged, resume := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(resume) }) + writes := 0 + const cb = "test:flat_ip_lifecycle_commit" + if err := db.Callback().Update().After("gorm:update").Register(cb, func(tx *gorm.DB) { + if tx.Statement.Table == "inbound_client_ips" && tx.Statement.Context.Value(nodeIPLockReportKey{}) != nil && tx.RowsAffected == 1 { + writes++ + if writes == len(rows) { + close(staged) + <-resume + } + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Update().Remove(cb) }) + inbounds, nodes := &InboundService{}, &NodeService{} + reportDone := make(chan error, 1) + var reportExited bool + defer func() { + unblock() + if !reportExited { + <-reportDone + } + }() + go func() { reportDone <- inbounds.MergePolledNodeClientIps(reportCtx, &node, rows) }() + waitNodeIPTestValue(t, ctx, staged, "flat report staged both rows") + + mutationDone := make(chan error, 1) + go func() { + switch change { + case "disable": + mutationDone <- nodes.SetEnable(node.Id, false) + case "delete": + var row model.Inbound + if err := db.WithContext(ctx).Where("node_id = ?", node.Id).Take(&row).Error; err != nil { + mutationDone <- err + return + } + if _, err := inbounds.DelInbound(row.Id); err != nil { + mutationDone <- err + return + } + mutationDone <- nodes.Delete(node.Id) + case "endpoint": + replacement := node + replacement.ApiToken = "" + replacement.Port++ + mutationDone <- nodes.Update(node.Id, &replacement) + case "guid": + mutationDone <- nodes.UpdateHeartbeat(node.Id, HeartbeatPatch{Guid: "new-guid", Status: "online", LastHeartbeat: now}) + } + }() + var mutationExited bool + defer func() { + unblock() + if !mutationExited { + <-mutationDone + } + }() + mutationCtx, stopMutation := context.WithTimeout(ctx, 3*time.Second) + defer stopMutation() + err := waitNodeIPTestValue(t, mutationCtx, mutationDone, "lifecycle update completes while flat rows are staged") + mutationExited = true + if err != nil { + t.Fatal(err) + } + unblock() + err = waitNodeIPTestValue(t, ctx, reportDone, "obsolete report rolls back") + reportExited = true + if !errors.Is(err, ErrIneligibleNodeIPReport) { + t.Fatalf("report error = %v, want ineligible reporter", err) + } + for _, email := range []string{first, second} { + got, _ := readClientIps(t, email) + if !maps.Equal(got, map[string]int64{old.IP: old.Timestamp}) { + t.Errorf("%s committed some of the obsolete report: %v", email, got) + } + } + if change == "delete" { + var count int64 + if err := db.Model(&model.NodeClientIp{}).Where("node_guid = ?", node.Guid).Count(&count).Error; err != nil || count != 0 { + t.Fatalf("deleted reporter left %d attribution rows: %v", count, err) + } + } +} + +func TestPostgresPolledAttributionSurvivesConcurrentPrune(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires PostgreSQL") + } + setupClientIpTestDB(t) + db := database.GetDB() + const email = "a@example.test" + node, _ := seedNodeIPLockFixture(t, "prune-edge", 23084, email) + now := time.Now().Unix() + stale := model.ClientIpEntry{IP: "192.0.2.1", Timestamp: now - clientIpStaleAfterSeconds - 60} + renewed := model.ClientIpEntry{IP: stale.IP, Timestamp: now - 1} + fresh := model.ClientIpEntry{IP: "192.0.2.2", Timestamp: now} + if err := db.Create(&model.NodeClientIp{NodeGuid: node.Guid, Email: email, Ips: marshalIps(t, stale)}).Error; err != nil { + t.Fatal(err) + } + read, resume := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(resume) }) + var readStale atomic.Bool + const cb = "test:park_attribution_prune" + if err := db.Callback().Query().After("gorm:query").Register(cb, func(tx *gorm.DB) { + if tx.Statement.Table == "node_client_ips" && readStale.CompareAndSwap(false, true) { + close(read) + <-resume + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(cb) }) + inbounds := &InboundService{} + ctx, cancel := context.WithTimeout(t.Context(), 8*time.Second) + defer cancel() + pruneDone := make(chan error, 1) + go func() { pruneDone <- inbounds.PruneStaleClientIps() }() + var pruneExited bool + defer func() { + unblock() + if !pruneExited { + <-pruneDone + } + }() + waitNodeIPTestValue(t, ctx, read, "pruner has stale attribution snapshot") + want := []model.ClientIpEntry{renewed, fresh} + if err := inbounds.MergePolledClientIpsByGuid(ctx, &node, map[string]map[string][]model.ClientIpEntry{ + node.Guid: {email: slices.Clone(want)}, + }); err != nil { + t.Fatal(err) + } + unblock() + err := waitNodeIPTestValue(t, ctx, pruneDone, "stale pruner completes") + pruneExited = true + if err != nil { + t.Fatal(err) + } + trees, err := inbounds.GetClientIpsByGuid() + if err != nil { + t.Fatal(err) + } + if got := trees[node.Guid][email]; !slices.Equal(got, want) { + t.Fatalf("pruner lost refreshed attribution: %v, want %v", got, want) + } +} diff --git a/internal/web/service/node_merge_contention_test.go b/internal/web/service/node_merge_contention_test.go new file mode 100644 index 000000000..b5721132b --- /dev/null +++ b/internal/web/service/node_merge_contention_test.go @@ -0,0 +1,172 @@ +package service + +import ( + "context" + "fmt" + "path/filepath" + "strings" + "testing" + "time" + + "gorm.io/gorm" + "gorm.io/gorm/logger" + + "github.com/mhsanaei/3x-ui/v3/internal/config" + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + "github.com/mhsanaei/3x-ui/v3/internal/web/runtime" + "github.com/mhsanaei/3x-ui/v3/internal/xray" +) + +func TestNodeMergeLetsSubscriptionTouchDuringClientReconciliationPostgres(t *testing.T) { + if config.GetDBKind() != database.DialectPostgres { + t.Skip("requires PostgreSQL row locks") + } + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "contention.db")) + node := &model.Node{Name: "merge-lock-window", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const email = "subscription-touch@example.test" + snapshot := func(up, quota int64) *runtime.TrafficSnapshot { + settings := fmt.Sprintf(`{"clients":[{"email":%q,"subId":"touch-sub","enable":true,"totalGB":%d}]}`, email, quota) + return snapshotWithClients(t, "contention", settings, xray.ClientTraffic{Email: email, Up: up, Enable: true, Total: quota}) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100, 1000), false, false); err != nil { + t.Fatal(err) + } + before := readTraffic(t, db, email) + + const touchedAt = 1730000000123 + probed := false + var probeErr error + if err := db.Callback().Update().Before("gorm:update").Register("test:touch_during_reconcile", func(tx *gorm.DB) { + if tx.Statement.Table != "clients" || probed { + return + } + probed = true + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + probeErr = db.WithContext(ctx).Transaction(func(other *gorm.DB) error { + if err := other.Exec("SET LOCAL lock_timeout = '150ms'").Error; err != nil { + return err + } + return other.Model(&xray.ClientTraffic{}). + Where("email IN (SELECT email FROM clients WHERE sub_id = ?)", "touch-sub"). + Update("last_sub_fetch", touchedAt).Error + }) + }); err != nil { + t.Fatal(err) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err != nil { + t.Fatal(err) + } + if !probed || probeErr != nil { + t.Fatalf("subscription update during client reconciliation: probed=%t err=%v", probed, probeErr) + } + if after := readTraffic(t, db, email); after.Up != before.Up+30 || after.Total != 2000 || after.LastSubFetch != touchedAt { + t.Fatalf("merge or subscription touch lost data: before=%+v after=%+v", before, after) + } +} + +func TestNodeMergeBatchesBaselinesForActiveClients(t *testing.T) { + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "batch.db")) + node := &model.Node{Name: "batch-baselines", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const clients = 24 + snapshot := func(up int64) *runtime.TrafficSnapshot { + rows := make([]xray.ClientTraffic, 0, clients) + entries := make([]model.Client, 0, clients) + for i := range clients { + email := fmt.Sprintf("batch-%d@x", i) + rows = append(rows, xray.ClientTraffic{Email: email, Enable: true, Up: up}) + entries = append(entries, model.Client{Email: email, Enable: true}) + } + return snapshotWithClients(t, "batch-baselines", clientsSettings(t, entries), rows...) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100), false, false); err != nil { + t.Fatal(err) + } + trace := &snapshotReadLog{Interface: logger.Discard} + previous := db.Logger + db.Logger = trace + t.Cleanup(func() { db.Logger = previous }) + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(107), false, false); err != nil { + t.Fatal(err) + } + writes := 0 + for _, sql := range trace.statements { + if strings.HasPrefix(strings.ToUpper(sql), "INSERT INTO") && strings.Contains(sql, "node_client_traffics") { + writes++ + } + } + if writes != 1 { + t.Errorf("baseline upserts=%d for %d changed clients, want one", writes, clients) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(107), false, false); err != nil { + t.Fatal(err) + } + var rows []model.NodeClientTraffic + if err := db.Where("node_id = ?", node.Id).Find(&rows).Error; err != nil { + t.Fatal(err) + } + if len(rows) != clients { + t.Fatalf("stored %d baselines, want %d", len(rows), clients) + } + for _, row := range rows { + if row.Up != 107 { + t.Errorf("%s baseline up=%d, want 107", row.Email, row.Up) + } + if traffic := readTraffic(t, db, row.Email); traffic.Up != 107 { + t.Errorf("%s stored up=%d, want one 7-byte delta on top of adoption", row.Email, traffic.Up) + } + } +} + +func TestNodeMergeRollsBackConfigTrafficAndBaselineOnLateWriteFailure(t *testing.T) { + if config.GetDBKind() == database.DialectPostgres { + t.Skip("uses a SQLite trigger to fail the final traffic update") + } + db := initNodeSnapshotDB(t, filepath.Join(t.TempDir(), "rollback.db")) + node := &model.Node{Name: "late-traffic-rollback", Enable: true} + seedNodeRow(t, db, node) + svc := &InboundService{} + const email = "late-traffic@x" + snapshot := func(up, quota int64) *runtime.TrafficSnapshot { + settings := fmt.Sprintf(`{"clients":[{"email":%q,"enable":true,"totalGB":%d}]}`, email, quota) + return snapshotWithClients(t, "late-write", settings, xray.ClientTraffic{Email: email, Up: up, Enable: true, Total: quota}) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(100, 1000), false, false); err != nil { + t.Fatal(err) + } + if err := db.Exec(`CREATE TRIGGER fail_late_traffic BEFORE UPDATE OF up ON client_traffics + WHEN NEW.email = 'late-traffic@x' AND NEW.up > OLD.up + BEGIN SELECT RAISE(ABORT, 'injected late traffic failure'); END`).Error; err != nil { + t.Fatal(err) + } + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err == nil || !strings.Contains(err.Error(), "injected late traffic failure") { + t.Fatalf("merge failure=%v, want triggered write failure", err) + } + assertState := func(up, quota int64) { + t.Helper() + var baseline model.NodeClientTraffic + if err := db.Where("node_id = ? AND email = ?", node.Id, email).Take(&baseline).Error; err != nil { + t.Fatal(err) + } + traffic := readTraffic(t, db, email) + record := lookupClientRecord(t, email) + if baseline.Up != up || traffic.Up != up || traffic.Total != quota || record.TotalGB != quota { + t.Fatalf("inconsistent merge: baseline=%d up=%d traffic quota=%d record quota=%d", baseline.Up, traffic.Up, traffic.Total, record.TotalGB) + } + } + assertState(100, 1000) + if err := db.Exec("DROP TRIGGER fail_late_traffic").Error; err != nil { + t.Fatal(err) + } + for range 2 { + if _, err := svc.SetRemoteTraffic(node.Id, snapshot(130, 2000), false, false); err != nil { + t.Fatal(err) + } + } + assertState(130, 2000) +} diff --git a/internal/web/service/node_reset_undelivered_test.go b/internal/web/service/node_reset_undelivered_test.go index 278d1c2b0..00d300357 100644 --- a/internal/web/service/node_reset_undelivered_test.go +++ b/internal/web/service/node_reset_undelivered_test.go @@ -388,7 +388,7 @@ func TestTrafficRemotePlansWaitOneBudgetPerNode(t *testing.T) { plans[i] = trafficInboundUpdatePlan{oldInbound: ib, newInbound: ib} } start := time.Now() - (&InboundService{}).applyTrafficRemotePlans(plans) + (&InboundService{}).applyTrafficRemotePlans(plans, reserveTrafficRemoteTurns(plans)) if took := time.Since(start); took > nodeClientPushTimeout+2*time.Second { t.Fatalf("pushing %d inbounds to one hanging node took %v", len(plans), took) } diff --git a/internal/web/service/traffic_writer.go b/internal/web/service/traffic_writer.go index a40b17484..017fc8acf 100644 --- a/internal/web/service/traffic_writer.go +++ b/internal/web/service/traffic_writer.go @@ -167,6 +167,11 @@ func drainTrafficWriter(adminQueue, bgQueue chan *trafficWriteRequest) { // remote node call would stall all traffic accounting for up to the remote // timeout. Apply runtime changes after this returns. func runSerializedTx(fn func(tx *gorm.DB) error) error { + return runSerializedTxThen(fn, nil) +} + +// afterCommit runs on the writer in commit order and must not wait or perform I/O. +func runSerializedTxThen(fn func(tx *gorm.DB) error, afterCommit func()) error { return submitTrafficWrite(func() error { state := &serializedTx{} err := database.GetDB().Transaction(func(tx *gorm.DB) error { @@ -176,6 +181,9 @@ func runSerializedTx(fn func(tx *gorm.DB) error) error { if err == nil { // Still on the writer, so no node merge runs between the commit and the lift. withdrawClientTombstones(state.createdClientEmails...) + if afterCommit != nil { + afterCommit() + } } return err }) diff --git a/internal/web/service/xray.go b/internal/web/service/xray.go index ed1a6f5d4..3f9c5306e 100644 --- a/internal/web/service/xray.go +++ b/internal/web/service/xray.go @@ -202,8 +202,6 @@ func (s *XrayService) GetXrayConfig() (*xray.Config, error) { xrayConfig.OutboundConfigs = forceUserspaceWireGuardTun(xrayConfig.OutboundConfigs) } - _, _, _ = s.inboundService.AddTraffic(nil, nil) - inbounds, err := s.inboundService.GetAllInbounds() if err != nil { return nil, err @@ -1555,6 +1553,13 @@ func (s *XrayService) RestartXrayFrom(isForce bool, origin XrayOrigin) error { // dropSessions replaces a running core whatever its config says: only a new process // ends the sessions of clients the API has already removed. func (s *XrayService) restartXrayFrom(isForce bool, origin, trigger XrayOrigin, dropSessions bool) error { + if !isForce && isManuallyStopped.Load() { + return nil + } + // Committed traffic maintenance can take the Xray lock to update the live snapshot. + if _, _, err := s.inboundService.AddTraffic(nil, nil); err != nil { + logger.Warning("traffic maintenance before Xray restart failed:", err) + } lock.Lock() defer lock.Unlock() logger.Debug("restart Xray, force:", isForce) diff --git a/internal/web/service/xray_restart_writer_test.go b/internal/web/service/xray_restart_writer_test.go new file mode 100644 index 000000000..d84df7d58 --- /dev/null +++ b/internal/web/service/xray_restart_writer_test.go @@ -0,0 +1,83 @@ +package service + +import ( + "errors" + "sync" + "sync/atomic" + "testing" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/database/model" + + "gorm.io/gorm" +) + +func TestPendingXrayRestartDoesNotHoldLifecycleLockWhileWaitingForWriter(t *testing.T) { + db := initTrafficTestDB(t) + stopped := isManuallyStopped.Swap(false) + pending := pendingXrayRestart.Swap(nil) + reconcile := isNeedXrayReconcile.Swap(false) + depletion := pendingXraySessionDrop.Swap(false) + t.Cleanup(func() { + isManuallyStopped.Store(stopped) + pendingXrayRestart.Store(pending) + isNeedXrayReconcile.Store(reconcile) + pendingXraySessionDrop.Store(depletion) + }) + var configRead atomic.Bool + const hook = "test:reject-restart-config-before-starting-core" + if err := db.Callback().Query().Before("gorm:query").Register(hook, func(tx *gorm.DB) { + if _, ok := tx.Statement.Dest.(*[]*model.Inbound); ok && tx.Statement.ConnPool == db.Statement.ConnPool { + configRead.Store(true) + _ = tx.AddError(errors.New("injected config read failure")) + } + }); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = db.Callback().Query().Remove(hook) }) + + StartTrafficWriter() + t.Cleanup(StopTrafficWriter) + parked, release, writerDone := make(chan struct{}), make(chan struct{}), make(chan struct{}) + var once sync.Once + unblock := func() { once.Do(func() { close(release) }) } + var lifecycleAvailable bool + go func() { + defer close(writerDone) + _ = submitTrafficWriteBackground(func() error { + close(parked) + <-release + lifecycleAvailable = lock.TryLock() + if lifecycleAvailable { + lock.Unlock() + } + return nil + }) + }() + t.Cleanup(func() { unblock(); <-writerDone }) + select { + case <-parked: + case <-time.After(3 * time.Second): + t.Fatal("traffic writer did not start") + } + + svc := &XrayService{} + svc.SetToNeedRestartFrom(XrayOriginConfigChange) + restartDone := make(chan struct{}) + go func() { defer close(restartDone); svc.ApplyPendingRestart() }() + t.Cleanup(func() { unblock(); <-restartDone }) + for deadline := time.Now().Add(3 * time.Second); trafficWriterQueueLen() == 0; time.Sleep(time.Millisecond) { + if time.Now().After(deadline) { + t.Fatal("pending restart never queued lifecycle maintenance") + } + } + unblock() + <-writerDone + <-restartDone + if !lifecycleAvailable { + t.Fatal("restart held the Xray lifecycle lock while waiting for the traffic writer") + } + if !configRead.Load() || pendingXrayRestart.Load() == nil { + t.Fatal("restart skipped config construction or failed to re-arm the request") + } +} diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index 7238b0965..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": "تم إعادة تعيين حركة المرور", @@ -1339,7 +1339,7 @@ "infoDesc": "كل تغيير هتعمله هنا لازم يتخزن. ياريت تعيد تشغيل البانل عشان التعديلات تتفعل.", "restartPanel": "إعادة تشغيل اللوحة", "restartPanelDesc": "متأكد إنك عايز تعيد تشغيل البانل؟ لو ماقدرتش تدخل بعد إعادة التشغيل، شوف سجل البانل على السيرفر.", - "restartPanelSuccess": "تم إعادة تشغيل اللوحة بنجاح", + "restartPanelAccepted": "تم قبول طلب إعادة تشغيل اللوحة.", "actions": "إجراءات", "resetDefaultConfig": "استرجاع الافتراضي", "panelSettings": "عام", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 5df5f1e61..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.", @@ -1460,7 +1460,7 @@ "infoDesc": "Every change made here needs to be saved. Please restart the panel to apply changes.", "restartPanel": "Restart Panel", "restartPanelDesc": "Are you sure you want to restart the panel? If you cannot access the panel after restarting, please view the panel log info on the server.", - "restartPanelSuccess": "The panel was successfully restarted.", + "restartPanelAccepted": "Panel restart request accepted.", "actions": "Actions", "resetDefaultConfig": "Reset to Default", "panelSettings": "General", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index df05bd18f..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", @@ -1339,7 +1339,7 @@ "infoDesc": "Cada cambio realizado aquí debe ser guardado. Por favor, reinicie el panel para aplicar los cambios.", "restartPanel": "Reiniciar panel", "restartPanelDesc": "¿Está seguro de que desea reiniciar el panel? Haga clic en Aceptar para reiniciar después de 3 segundos. Si no puede acceder al panel después de reiniciar, por favor, consulte la información de registro del panel en el servidor.", - "restartPanelSuccess": "El panel se reinició correctamente", + "restartPanelAccepted": "Se aceptó la solicitud de reinicio del panel.", "actions": "Acciones", "resetDefaultConfig": "Restablecer a Configuración Predeterminada", "panelSettings": "Configuraciones del Panel", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index b89862162..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": "ترافیک بازنشانی شد", @@ -1339,7 +1339,7 @@ "infoDesc": "برای اعمال تغییرات در این بخش باید پس از ذخیره کردن، پنل را ریستارت کنید", "restartPanel": "راه‌اندازی مجدد پنل", "restartPanelDesc": "آیا مطمئن به ریستارت پنل هستید؟ اگر پس‌از ریستارت نمی‌توانید به پنل دسترسی پیدا کنید، لطفاً گزارش‌های موجود در اسکریپت پنل را بررسی کنید", - "restartPanelSuccess": "پنل با موفقیت راه‌اندازی مجدد شد", + "restartPanelAccepted": "درخواست راه‌اندازی مجدد پنل پذیرفته شد.", "actions": "عملیات ها", "resetDefaultConfig": "برگشت به پیش‌فرض", "panelSettings": "پیکربندی", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 77df99297..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", @@ -1339,7 +1339,7 @@ "infoDesc": "Setiap perubahan yang dibuat di sini perlu disimpan. Harap restart panel untuk menerapkan perubahan.", "restartPanel": "Mulai ulang panel", "restartPanelDesc": "Apakah Anda yakin ingin merestart panel? Jika Anda tidak dapat mengakses panel setelah merestart, lihat info log panel di server.", - "restartPanelSuccess": "Panel berhasil dimulai ulang", + "restartPanelAccepted": "Permintaan untuk memulai ulang panel telah diterima.", "actions": "Tindakan", "resetDefaultConfig": "Reset ke Default", "panelSettings": "Umum", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 34cdd4de0..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": "トラフィックがリセットされました", @@ -1339,7 +1339,7 @@ "infoDesc": "ここでのすべての変更は、保存してパネルを再起動する必要があります", "restartPanel": "パネルを再起動", "restartPanelDesc": "パネルを再起動してもよろしいですか?再起動後にパネルにアクセスできない場合は、サーバーでパネルログを確認してください", - "restartPanelSuccess": "パネルの再起動に成功しました", + "restartPanelAccepted": "パネルの再起動リクエストを受け付けました。", "actions": "操作", "resetDefaultConfig": "デフォルト設定にリセット", "panelSettings": "一般", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index 781f6cdb6..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", @@ -1339,7 +1339,7 @@ "infoDesc": "Toda alteração feita aqui precisa ser salva. Reinicie o painel para aplicar as alterações.", "restartPanel": "Reiniciar painel", "restartPanelDesc": "Tem certeza de que deseja reiniciar o painel? Se não conseguir acessar o painel após reiniciar, consulte os logs do painel no servidor.", - "restartPanelSuccess": "O painel foi reiniciado com sucesso", + "restartPanelAccepted": "A solicitação de reinicialização do painel foi aceita.", "actions": "Ações", "resetDefaultConfig": "Redefinir para Padrão", "panelSettings": "Geral", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 5b5065d8f..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": "Трафик сброшен", @@ -1339,7 +1339,7 @@ "infoDesc": "Сохраните изменения и перезапустите панель для их применения.", "restartPanel": "Перезапустить панель", "restartPanelDesc": "Вы уверены, что хотите перезапустить панель? Подтвердите, и перезапуск произойдёт через 3 секунды. Если панель будет недоступна, проверьте лог сервера", - "restartPanelSuccess": "Панель успешно перезапущена", + "restartPanelAccepted": "Запрос на перезапуск панели принят.", "actions": "Действия", "resetDefaultConfig": "Восстановить настройки по умолчанию", "panelSettings": "Панель", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index 175906240..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á.", @@ -1460,7 +1460,7 @@ "infoDesc": "Každú zmenu najprv uložte. Na jej použitie reštartujte panel.", "restartPanel": "Reštartovať panel", "restartPanelDesc": "Naozaj chcete reštartovať panel? Ak sa po reštarte nedá otvoriť, skontrolujte záznamy panelu na serveri.", - "restartPanelSuccess": "Panel bol úspešne reštartovaný.", + "restartPanelAccepted": "Požiadavka na reštart panela bola prijatá.", "actions": "Akcie", "resetDefaultConfig": "Obnoviť predvolené nastavenia", "panelSettings": "Všeobecné", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index fbab4b889..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ı.", @@ -1339,7 +1339,7 @@ "infoDesc": "Burada yapılan her değişikliğin kaydedilmesi gerekir. Değişikliklerin uygulanması için paneli yeniden başlatın.", "restartPanel": "Paneli Yeniden Başlat", "restartPanelDesc": "Paneli yeniden başlatmak istediğinizden emin misiniz? Yeniden başlattıktan sonra panele erişemezseniz, sunucudaki panel loglarını kontrol edin.", - "restartPanelSuccess": "Panel başarıyla yeniden başlatıldı.", + "restartPanelAccepted": "Paneli yeniden başlatma isteği kabul edildi.", "actions": "İşlemler", "resetDefaultConfig": "Varsayılana Sıfırla", "panelSettings": "Genel", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index fb302d746..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": "Трафік скинуто", @@ -1339,7 +1339,7 @@ "infoDesc": "Кожна внесена тут зміна повинна бути збережена. Перезапустіть панель, щоб застосувати зміни.", "restartPanel": "Перезапустити панель", "restartPanelDesc": "Ви впевнені, що бажаєте перезапустити панель? Якщо ви не можете отримати доступ до панелі після перезапуску, будь ласка, перегляньте інформацію журналу панелі на сервері.", - "restartPanelSuccess": "Панель успішно перезапущено", + "restartPanelAccepted": "Запит на перезапуск панелі прийнято.", "actions": "Дії", "resetDefaultConfig": "Відновити значення за замовчуванням", "panelSettings": "Загальні", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 52570f998..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", @@ -1339,7 +1339,7 @@ "infoDesc": "Mọi thay đổi được thực hiện ở đây cần phải được lưu. Vui lòng khởi động lại bảng điều khiển để áp dụng các thay đổi.", "restartPanel": "Khởi động lại bảng điều khiển", "restartPanelDesc": "Bạn có chắc chắn muốn khởi động lại bảng điều khiển? Nhấn OK để khởi động lại sau 3 giây. Nếu bạn không thể truy cập bảng điều khiển sau khi khởi động lại, vui lòng xem thông tin nhật ký của bảng điều khiển trên máy chủ.", - "restartPanelSuccess": "Đã khởi động lại bảng điều khiển thành công", + "restartPanelAccepted": "Yêu cầu khởi động lại bảng điều khiển đã được chấp nhận.", "actions": "Hành động", "resetDefaultConfig": "Đặt lại cấu hình mặc định", "panelSettings": "Bảng điều khiển", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index d10a4f91b..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": "流量已重置", @@ -1339,7 +1339,7 @@ "infoDesc": "此处的所有更改都需要保存并重启面板才能生效", "restartPanel": "重启面板", "restartPanelDesc": "确定要重启面板吗?若重启后无法访问面板,请前往服务器查看面板日志信息", - "restartPanelSuccess": "面板已成功重启", + "restartPanelAccepted": "已接受面板重启请求。", "actions": "操作", "resetDefaultConfig": "重置为默认配置", "panelSettings": "常规", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index a736e06b7..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": "流量已重置", @@ -1339,7 +1339,7 @@ "infoDesc": "此處的所有更改都需要儲存並重啟面板才能生效", "restartPanel": "重新啟動面板", "restartPanelDesc": "確定要重啟面板嗎?若重啟後無法訪問面板,請前往伺服器檢視面板日誌資訊", - "restartPanelSuccess": "面板已成功重新啟動", + "restartPanelAccepted": "已接受面板重新啟動請求。", "actions": "操作", "resetDefaultConfig": "重置為預設配置", "panelSettings": "常規", diff --git a/internal/web/web.go b/internal/web/web.go index 65a49d319..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()) @@ -789,24 +791,38 @@ func (s *Server) start(restartXray bool, startTgBot bool) (err error) { // Stop gracefully shuts down the web server, stops Xray, cron jobs, and Telegram bot. func (s *Server) Stop() error { - return s.stop(true, true) + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + return s.stop(ctx, true, true) } -func (s *Server) StopPanelOnly() error { - return s.stop(false, true) +func (s *Server) StopPanelOnly(ctx context.Context) error { + return s.stop(ctx, false, true) } -func (s *Server) stop(stopXray bool, stopTgBot bool) error { +func (s *Server) stop(ctx context.Context, stopXray bool, stopTgBot bool) error { s.cancel() var err1 error var err2 error if s.httpServer != nil { - shutdownCtx, shutdownCancel := context.WithTimeout(context.Background(), 10*time.Second) - err1 = s.httpServer.Shutdown(shutdownCtx) - shutdownCancel() + err1 = runPanelStopPhase("http drain", func() error { + return s.httpServer.Shutdown(ctx) + }) + if err1 != nil && !stopXray { + return fmt.Errorf("drain old panel HTTP requests: %w", err1) + } } if s.cron != nil { - <-s.cron.Stop().Done() + _ = runPanelStopPhase("cron drain", func() error { + <-s.cron.Stop().Done() + return nil + }) + } + if s.nodeTrafficJob != nil { + _ = runPanelStopPhase("node traffic drain", func() error { + s.nodeTrafficJob.Close() + return nil + }) } if stopXray { tuic.GetManager().StopAll() @@ -830,9 +846,12 @@ func (s *Server) stop(stopXray bool, stopTgBot bool) error { s.tgbotService.Stop() } if s.bus != nil { - s.bus.Stop() + _ = runPanelStopPhase("event subscribers", func() error { + s.bus.Stop() + return nil + }) } - if err := service.PersistSystemMetrics(); err != nil { + if err := runPanelStopPhase("system metrics", service.PersistSystemMetrics); err != nil { logger.Warning("persist system metrics on shutdown failed:", err) } if stopXray { @@ -854,6 +873,14 @@ func (s *Server) stop(stopXray bool, stopTgBot bool) error { return common.Combine(err1, err2) } +func runPanelStopPhase(name string, run func() error) error { + started := time.Now() + logger.Infof("panel stop phase=%s state=started", name) + err := run() + logger.Infof("panel stop phase=%s state=finished duration=%s error=%v", name, time.Since(started), err) + return err +} + // GetCtx returns the server's context for cancellation and deadline management. func (s *Server) GetCtx() context.Context { return s.ctx diff --git a/internal/web/web_shutdown_test.go b/internal/web/web_shutdown_test.go index 599c1cd77..0d5c9c24b 100644 --- a/internal/web/web_shutdown_test.go +++ b/internal/web/web_shutdown_test.go @@ -2,6 +2,7 @@ package web import ( "context" + "errors" "net" "net/http" "testing" @@ -32,7 +33,47 @@ func TestServerStopPanelOnlyWithPreclosedListenerSucceeds(t *testing.T) { defer cancel() _ = s.httpServer.Shutdown(shutdownCtx) - if err := s.StopPanelOnly(); err != nil { + if err := s.StopPanelOnly(context.Background()); err != nil { t.Fatalf("expected nil error when listener is already closed, got: %v", err) } } + +func TestServerStopPanelOnlyHonorsCallerDeadline(t *testing.T) { + t.Setenv("XUI_DB_FOLDER", t.TempDir()) + s := NewServer(nil) + ln, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + s.listener = ln + entered, release := make(chan struct{}), make(chan struct{}) + s.httpServer = &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(entered) + <-release + w.WriteHeader(http.StatusNoContent) + })} + t.Cleanup(func() { + close(release) + _ = s.httpServer.Close() + }) + go func() { _ = s.httpServer.Serve(ln) }() + requestDone := make(chan error, 1) + go func() { + client := &http.Client{Timeout: 3 * time.Second} + res, err := client.Get("http://" + ln.Addr().String()) + if err == nil { + _ = res.Body.Close() + } + requestDone <- err + }() + select { + case <-entered: + case err := <-requestDone: + t.Fatalf("handler did not start: %v", err) + } + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) + defer cancel() + if err := s.StopPanelOnly(ctx); !errors.Is(err, context.DeadlineExceeded) { + t.Fatalf("active HTTP drain ignored its caller deadline: %v", err) + } +} diff --git a/main.go b/main.go index 70bbfd739..0f53f15cf 100644 --- a/main.go +++ b/main.go @@ -5,6 +5,7 @@ package main import ( "context" _ "embed" + "errors" "flag" "fmt" "log" @@ -161,7 +162,7 @@ func runWebServer() { monitor, err := tunnelmonitor.New(monitorCfg, func(_ context.Context) error { logger.Warning("Tunnel health monitor threshold reached, restarting xray-core") - return server.RestartXray(service.XrayOriginTunnelHealth) + return (&service.XrayService{}).RestartXrayFrom(true, service.XrayOriginTunnelHealth) }) if err != nil { logger.Warning("Tunnel health monitor disabled: ", err) @@ -169,38 +170,42 @@ func runWebServer() { go monitor.Run(monitorCtx) } } - for { - sig := <-sigCh - - switch sig { + for shutdown := false; !shutdown; { + switch <-sigCh { case syscall.SIGHUP: logger.Info("Received SIGHUP signal. Restarting servers...") - err := server.StopPanelOnly() + var nextWeb *web.Server + var nextSub *sub.Server + pending, err := runPanelRestart(sigCh, panelRestartTimeout, + panelRestartPhase{"panel shutdown", server.StopPanelOnly}, + panelRestartPhase{"subscription shutdown", subServer.StopWithContext}, + panelRestartPhase{"panel startup", func(context.Context) error { + nextWeb = web.NewServer(sub.NewLinkProvider()) + global.SetWebServer(nextWeb) + return nextWeb.StartPanelOnly() + }}, + panelRestartPhase{"subscription startup", func(context.Context) error { + nextSub = sub.NewServer() + global.SetSubServer(nextSub) + return nextSub.Start() + }}, + ) if err != nil { - logger.Debug("Error stopping web server:", err) - } - err = subServer.Stop() - if err != nil { - logger.Debug("Error stopping sub server:", err) - } - - server = web.NewServer(sub.NewLinkProvider()) - global.SetWebServer(server) - err = server.StartPanelOnly() - if err != nil { - log.Fatalf("Error restarting web server: %v", err) + if errors.Is(err, context.DeadlineExceeded) { + logPanelRestartStacks() + } + log.Fatalf("Panel restart failed, exiting for supervisor recovery: %v", err) } + server, subServer = nextWeb, nextSub log.Println("Web server restarted successfully.") - - sub.SetDistFS(web.EmbeddedDist()) - subServer = sub.NewServer() - global.SetSubServer(subServer) - err = subServer.Start() - if err != nil { - log.Fatalf("Error restarting sub server: %v", err) - } log.Println("Sub server restarted successfully.") + shutdown = pending.shutdown + if pending.restartXray && !shutdown { + if err := server.RestartXray(service.XrayOriginSignal); err != nil { + logger.Error("Failed to restart xray-core:", err) + } + } case sys.SIGUSR1: logger.Info("Received USR1 signal, restarting xray-core...") err := server.RestartXray(service.XrayOriginSignal) @@ -209,22 +214,20 @@ func runWebServer() { } default: - if stopTunnelHealthMonitor != nil { - stopTunnelHealthMonitor() - } - - // --- FIX FOR TELEGRAM BOT CONFLICT (409) on full shutdown --- - tgbot.StopBot() - // ------------------------------------------------------------ - - if err := server.Stop(); err != nil { - logger.Error("Server shutdown failed:", err) - } - _ = subServer.Stop() - log.Println("Shutting down servers.") - return + shutdown = true } } + + if stopTunnelHealthMonitor != nil { + stopTunnelHealthMonitor() + } + // Stop polling before process exit to avoid Telegram 409 conflicts. + tgbot.StopBot() + if err := server.Stop(); err != nil { + logger.Error("Server shutdown failed:", err) + } + _ = subServer.Stop() + log.Println("Shutting down servers.") } // resetSetting resets all panel settings to their default values. diff --git a/panel_restart.go b/panel_restart.go new file mode 100644 index 000000000..8db21a60a --- /dev/null +++ b/panel_restart.go @@ -0,0 +1,114 @@ +package main + +import ( + "context" + "errors" + "fmt" + "log" + "os" + "runtime" + "strings" + "sync/atomic" + "syscall" + "time" + + "github.com/mhsanaei/3x-ui/v3/internal/util/sys" +) + +// Each listener can take up to 30 seconds to drain ordinary HTTP traffic. +const panelRestartTimeout = 75 * time.Second + +type panelRestartPhase struct { + name string + run func(context.Context) error +} + +type panelRestartSignals struct { + shutdown bool + restartXray bool +} + +func runPanelRestart(signals <-chan os.Signal, budget time.Duration, phases ...panelRestartPhase) (panelRestartSignals, error) { + ctx, cancel := context.WithTimeout(context.Background(), budget) + defer cancel() + var phase atomic.Pointer[panelRestartPhase] + result := make(chan error, 1) + go func() { + for i := range phases { + if err := ctx.Err(); err != nil { + result <- err + return + } + step := &phases[i] + phase.Store(step) + started := time.Now() + log.Printf("panel restart phase=%s state=started", step.name) + err := step.run(ctx) + log.Printf("panel restart phase=%s state=finished duration=%s error=%v", step.name, time.Since(started), err) + if err != nil { + result <- fmt.Errorf("%s: %w", step.name, err) + return + } + } + result <- ctx.Err() + }() + + var pending panelRestartSignals + phaseName := func() string { + if current := phase.Load(); current != nil { + return current.name + } + return "dispatch" + } + for { + select { + case err := <-result: + if errors.Is(ctx.Err(), context.DeadlineExceeded) { + return pending, fmt.Errorf("%s exceeded the %s panel restart deadline: %w", phaseName(), budget, ctx.Err()) + } + return pending, err + case <-ctx.Done(): + return pending, fmt.Errorf("%s exceeded the %s panel restart deadline: %w", phaseName(), budget, ctx.Err()) + case sig, ok := <-signals: + if !ok { + signals = nil + continue + } + switch sig { + case syscall.SIGHUP: + continue + case sys.SIGUSR1: + pending.restartXray = true + default: + // Let the current restart finish within its existing deadline, + // then let the signal loop stop the new generation gracefully. + pending.shutdown = true + } + } + } +} + +// Log function names only. Argument values and goroutine labels can contain panel data. +func logPanelRestartStacks() { + records := make([]runtime.StackRecord, 2048) + n, ok := runtime.GoroutineProfile(records) + if !ok { + log.Printf("panel restart goroutine profile omitted: %d goroutines exceed diagnostic capacity", n) + return + } + log.Printf("panel restart goroutine profile: %d goroutines, showing up to 24 stacks", n) + for _, record := range records[:min(n, 24)] { + frames := runtime.CallersFrames(record.Stack()) + names := make([]string, 0, 12) + for range cap(names) { + frame, more := frames.Next() + if frame.Function != "" { + names = append(names, frame.Function) + } + if !more { + break + } + } + log.Print(strings.Join(names, " <- ")) + } +} diff --git a/panel_restart_test.go b/panel_restart_test.go new file mode 100644 index 000000000..75a32707c --- /dev/null +++ b/panel_restart_test.go @@ -0,0 +1,86 @@ +package main + +import ( + "context" + "errors" + "os" + "strings" + "sync" + "syscall" + "testing" + "time" +) + +func TestPanelRestartDeadlineFencesBlockedDrain(t *testing.T) { + entered, release, drained := make(chan struct{}), make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + t.Cleanup(unblock) + newGeneration := make(chan struct{}) + _, err := runPanelRestart(nil, 250*time.Millisecond, + panelRestartPhase{"panel drain", func(context.Context) error { + close(entered) + <-release + close(drained) + return nil + }}, + panelRestartPhase{"panel startup", func(context.Context) error { close(newGeneration); return nil }}, + ) + if !errors.Is(err, context.DeadlineExceeded) || !strings.Contains(err.Error(), "panel drain") { + t.Fatalf("blocked drain: %v", err) + } + <-entered + unblock() + <-drained + select { + case <-newGeneration: + t.Fatal("new workers started after a failed drain") + case <-time.After(75 * time.Millisecond): + } +} + +func TestPanelRestartDrainsBeforeGracefulShutdown(t *testing.T) { + entered, release := make(chan struct{}), make(chan struct{}) + unblock := sync.OnceFunc(func() { close(release) }) + t.Cleanup(unblock) + signals := make(chan os.Signal) + type outcome struct { + pending panelRestartSignals + err error + } + result := make(chan outcome, 1) + started := false + go func() { + pending, err := runPanelRestart(signals, 3*time.Second, + panelRestartPhase{"panel shutdown", func(context.Context) error { + close(entered) + <-release + return nil + }}, + panelRestartPhase{"panel startup", func(context.Context) error { + started = true + return nil + }}, + ) + result <- outcome{pending, err} + }() + <-entered + signals <- syscall.SIGHUP + signals <- syscall.SIGTERM + unblock() + got := <-result + if got.err != nil || !got.pending.shutdown || !started { + t.Fatalf("current restart must finish before graceful cleanup: started=%v, result=%+v", started, got) + } +} + +func TestPanelRestartDoesNotStartListenersAfterShutdownFailure(t *testing.T) { + failure := errors.New("old listener did not drain") + started := false + _, err := runPanelRestart(nil, time.Second, + panelRestartPhase{"panel shutdown", func(context.Context) error { return failure }}, + panelRestartPhase{"panel startup", func(context.Context) error { started = true; return nil }}, + ) + if started || !errors.Is(err, failure) { + t.Fatalf("started=%t, error=%v", started, err) + } +} 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", diff --git a/x-ui.sh b/x-ui.sh index a2ba4170b..cafceef8e 100644 --- a/x-ui.sh +++ b/x-ui.sh @@ -2262,6 +2262,115 @@ run_speedtest() { speedtest } +run_librespeed() { + local nc=$'\033[0m' + local ls_user="librespeed" # username + local ls_bin="/usr/local/bin/librespeed-cli" # path to binary file + local action launch=0 + + if [ "$(id -u)" -ne 0 ]; then # block launch as root + echo -e "${red}Run as root (needed for install and user management).${nc}" + return 1 + fi + + echo -e "${yellow}What do you want to do?\n1) Use\n2) Install/Update\n3) Delete${nc}" # Menu section + read -rp ": " action + + case "$action" in #Launch + 1) + if [ -x "$ls_bin" ]; then + launch=1 + else + echo -e "${red}LibreSpeed is not installed!${nc}" + return 1 + fi + ;; + + 2) + echo -e "${yellow}Installing/Updating LibreSpeed...${nc}" + ( + set -euo pipefail + + for dep in curl jq tar sha256sum install awk; do + command -v "$dep" &>/dev/null || { echo -e "${red}Missing dependency: $dep${nc}"; exit 1; } + done + + # Architecture detection + local arch + case "$(uname -m)" in + x86_64|amd64) arch=amd64 ;; + aarch64|arm64) arch=arm64 ;; + armv7l|armv8l) arch=armv7 ;; + armv6l) arch=armv6 ;; + i386|i686) arch=386 ;; + *) echo -e "${red}Unsupported architecture: $(uname -m)${nc}"; exit 1 ;; + esac + + local tmp release_json version asset url sums_url expected actual + local curl_opts=(--proto '=https' --tlsv1.2 -fsSL) + tmp=$(mktemp -d) + trap 'rm -rf "$tmp"' EXIT + + release_json=$(curl "${curl_opts[@]}" "https://api.github.com/repos/librespeed/speedtest-cli/releases/latest") # official github api + version=$(jq -r '.tag_name | ltrimstr("v")' <<<"$release_json") + asset="librespeed-cli_${version}_linux_${arch}.tar.gz" + + url=$(jq -r --arg n "$asset" '.assets[] | select(.name==$n) | .browser_download_url' <<<"$release_json") + [ -n "$url" ] || { echo -e "${red}No release asset named $asset${nc}"; exit 1; } + + echo -e "${yellow}Downloading $asset...${nc}" + curl "${curl_opts[@]}" -o "$tmp/$asset" "$url" + + # checking hashsum, but it'll stil empty for else function + sums_url=$(jq -r '[.assets[] | select(.name | test("checksum|sha256";"i"))][0].browser_download_url // empty' <<<"$release_json") + if [ -n "$sums_url" ]; then + curl "${curl_opts[@]}" -o "$tmp/checksums" "$sums_url" + expected=$(awk -v f="$asset" '$2==f || $2=="*" f {print $1}' "$tmp/checksums") + else + expected=$(jq -r --arg n "$asset" '.assets[] | select(.name==$n) | .digest // empty' <<<"$release_json") + expected=${expected#sha256:} + fi + [ -n "$expected" ] || { echo -e "${red}No checksum available, aborting.${nc}"; exit 1; } + + actual=$(sha256sum "$tmp/$asset" | awk '{print $1}') + if [ "$actual" != "$expected" ]; then + echo -e "${red}Checksum mismatch!\n expected: $expected\n actual: $actual${nc}" #something is wrong with hashsum + exit 1 + fi + echo -e "${green}Checksum OK.${nc}" # all good with hashsum + + # Extract only the binary; install root-owned so the service user can't modify it + tar -xzf "$tmp/$asset" -C "$tmp" librespeed-cli + install -o root -g root -m 0755 "$tmp/librespeed-cli" "$ls_bin" # very low privilage permissions + rm -f /usr/bin/librespeed-cli + ) || { echo -e "${red}Install failed.${nc}"; return 1; } + launch=1 + ;; + + 3) + rm -f "$ls_bin" /usr/bin/librespeed-cli # Deleting librespeed-cli + id -u "$ls_user" &>/dev/null && userdel "$ls_user" + echo -e "${green}LibreSpeed was deleted!${nc}" + ;; + + *) + echo -e "${red}Invalid option.${nc}" + return 1 + ;; + esac + + if [ "$launch" -eq 1 ]; then + # Create the locked-down system account + if ! id -u "$ls_user" &>/dev/null; then + useradd --system --no-create-home --home-dir /nonexistent \ + --shell "$(command -v nologin || echo /usr/sbin/nologin)" "$ls_user" \ + || { echo -e "${red}Could not create user $ls_user${nc}"; return 1; } + fi + echo -e "${green}Starting LibreSpeed...${nc}" + runuser -u "$ls_user" -- env -i HOME=/nonexistent PATH=/usr/bin:/bin "$ls_bin" + fi +} + ip_validation() { ipv6_regex="^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$" ipv4_regex="^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)$" @@ -3776,10 +3885,11 @@ show_menu() { │ ${green}26.${plain} Enable BBR │ │ ${green}27.${plain} Update Geo Files │ │ ${green}28.${plain} Speedtest by Ookla │ +│ ${green}29.${plain} Librespeed │ ╚────────────────────────────────────────────────╝ " show_status - echo && read -rp "Please enter your selection [0-28]: " num + echo && read -rp "Please enter your selection [0-29]: " num case "${num}" in 0) @@ -3869,8 +3979,11 @@ show_menu() { 28) run_speedtest ;; + 29) + run_librespeed + ;; *) - LOGE "Please enter the correct number [0-28]" + LOGE "Please enter the correct number [0-29]" ;; esac }