From c483882e561503c14657338ab911afde0ca2ab39 Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 14:24:47 +0330 Subject: [PATCH] fix(inbounds): keep Detach Clients responsive on large inbounds (#7332) Replace the unbounded Detach Clients modal with server-paged candidate loading, debounced search and a virtualized list. Preserve explicit-ID selection and add frozen all-matching scopes with exclusions so selection remains stable across pages and searches without sending an N-sized client list from the browser. Execute large detach requests as idempotent background jobs. Revalidate source-inbound membership in bounded batches, atomically apply membership deltas, preserve ClientRecords and traffic, and queue reconciliation for remote nodes. Keep the legacy email-based bulkDetach API compatible. Add PostgreSQL/SQLite regression coverage for concurrent membership changes, stale scopes, exclusions, retries, rollback and legacy callers, plus real master/node coverage for offline-node reconciliation. Regenerate and validate the API contract and OpenAPI artifacts. --- .github/workflows/ci.yml | 6 + .../content/docs/en/reference/api/clients.mdx | 73 ++- docs/public/openapi.json | 322 ++++++++++- frontend/public/openapi.json | 322 ++++++++++- frontend/src/generated/examples.ts | 37 ++ frontend/src/generated/schemas.ts | 118 ++++ frontend/src/generated/types.ts | 34 ++ frontend/src/generated/zod.ts | 39 ++ frontend/src/pages/api-docs/endpoints.ts | 68 ++- .../clients/DetachClientsModal.stories.tsx | 134 +++++ .../inbounds/clients/DetachClientsModal.tsx | 507 +++++++++++++----- .../src/test/detach-clients-modal.test.tsx | 154 +++++- internal/database/db.go | 40 ++ internal/database/model/model.go | 2 + internal/nodee2e/node_detach_scoped_test.go | 77 +++ internal/web/controller/client.go | 13 +- internal/web/controller/client_detach_jobs.go | 253 +++++++++ .../web/controller/client_detach_jobs_test.go | 140 +++++ .../web/service/client_detach_selection.go | 352 ++++++++++++ .../service/client_detach_selection_test.go | 290 ++++++++++ internal/web/service/client_inbound_apply.go | 11 +- internal/web/translation/ar-EG.json | 2 + internal/web/translation/en-US.json | 2 + internal/web/translation/es-ES.json | 2 + internal/web/translation/fa-IR.json | 2 + internal/web/translation/id-ID.json | 2 + internal/web/translation/ja-JP.json | 2 + internal/web/translation/pt-BR.json | 2 + internal/web/translation/ru-RU.json | 2 + internal/web/translation/sk-SK.json | 2 + internal/web/translation/tr-TR.json | 2 + internal/web/translation/uk-UA.json | 2 + internal/web/translation/vi-VN.json | 2 + internal/web/translation/zh-CN.json | 2 + internal/web/translation/zh-TW.json | 2 + tools/openapigen/main.go | 6 +- 36 files changed, 2851 insertions(+), 175 deletions(-) create mode 100644 frontend/src/pages/inbounds/clients/DetachClientsModal.stories.tsx create mode 100644 internal/nodee2e/node_detach_scoped_test.go create mode 100644 internal/web/controller/client_detach_jobs.go create mode 100644 internal/web/controller/client_detach_jobs_test.go create mode 100644 internal/web/service/client_detach_selection.go create mode 100644 internal/web/service/client_detach_selection_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 267bbb0eb..ef6285dd8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -258,6 +258,12 @@ jobs: exit 1 fi + - name: PostgreSQL scoped detach regressions + run: | + set -o pipefail + go test ./internal/web/service -run '^TestScopedDetach' -count=1 -v | tee /tmp/postgres-scoped-detach.log + test "$(grep -c -- '^--- PASS: TestScopedDetach' /tmp/postgres-scoped-detach.log)" -eq 3 + - name: PostgreSQL depletion query regressions run: | set -o pipefail diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx index 9ee16d78a..bd82d8b12 100644 --- a/docs/content/docs/en/reference/api/clients.mdx +++ b/docs/content/docs/en/reference/api/clients.mdx @@ -224,16 +224,31 @@ _openapi: process. url: '#poll-a-scoped-attachment-job-the-result-contains-counts-per-target-attached-skipped-errors-an-operation-failure-sets-error-instead-completed-results-are-retained-for-up-to-15-minutes-in-the-running-panel-process' - depth: 2 - title: "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." - url: '#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' + title: Read up to 100 clients currently attached to one inbound. Search matches + email or comment. The response includes filtered and attached totals, + and marks candidates belonging to an optional frozen scope. + url: '#read-up-to-100-clients-currently-attached-to-one-inbound-search-matches-email-or-comment-the-response-includes-filtered-and-attached-totals-and-marks-candidates-belonging-to-an-optional-frozen-scope' + - depth: 2 + title: Freeze up to 100,000 current memberships of one inbound and return their + count and an opaque token. Search does not narrow this selection. Tokens + expire after 15 minutes and are held in a bounded in-memory history. + url: '#freeze-up-to-100000-current-memberships-of-one-inbound-and-return-their-count-and-an-opaque-token-search-does-not-narrow-this-selection-tokens-expire-after-15-minutes-and-are-held-in-a-bounded-in-memory-history' + - depth: 2 + title: Detach client memberships while keeping records and traffic. Legacy email + requests accept multiple inbounds and return detached/skipped/errors + lists. Scoped requests take exactly one inbound and either explicit + clientIds or a frozen allMatching scopeToken with excludedClientIds. + Supply a requestId UUID and reuse it with the same payload when + retrying. The scoped response is {jobId}. Poll GET /bulkDetach/:id for + progress and counts. Changed memberships are skipped and newly attached + clients stay outside a frozen scope. + url: '#detach-client-memberships-while-keeping-records-and-traffic-legacy-email-requests-accept-multiple-inbounds-and-return-detachedskippederrors-lists-scoped-requests-take-exactly-one-inbound-and-either-explicit-clientids-or-a-frozen-allmatching-scopetoken-with-excludedclientids-supply-a-requestid-uuid-and-reuse-it-with-the-same-payload-when-retrying-the-scoped-response-is-jobid-poll-get-bulkdetachid-for-progress-and-counts-changed-memberships-are-skipped-and-newly-attached-clients-stay-outside-a-frozen-scope' + - depth: 2 + title: Poll a scoped detachment job. A completed result reports detached, + skipped and failed client counts and whether node reconciliation is + pending. Jobs are retained in a bounded in-memory history for up to 15 + minutes after completion. + url: '#poll-a-scoped-detachment-job-a-completed-result-reports-detached-skipped-and-failed-client-counts-and-whether-node-reconciliation-is-pending-jobs-are-retained-in-a-bounded-in-memory-history-for-up-to-15-minutes-after-completion' - depth: 2 title: Zero up/down counters for many clients in one call. Loops the single-reset path so each client its quota had disabled is re-enabled @@ -586,16 +601,30 @@ _openapi: Completed results are retained for up to 15 minutes in the running panel process. id: poll-a-scoped-attachment-job-the-result-contains-counts-per-target-attached-skipped-errors-an-operation-failure-sets-error-instead-completed-results-are-retained-for-up-to-15-minutes-in-the-running-panel-process - - content: "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." - id: 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 + - content: Read up to 100 clients currently attached to one inbound. Search + matches email or comment. The response includes filtered and attached + totals, and marks candidates belonging to an optional frozen scope. + id: read-up-to-100-clients-currently-attached-to-one-inbound-search-matches-email-or-comment-the-response-includes-filtered-and-attached-totals-and-marks-candidates-belonging-to-an-optional-frozen-scope + - content: Freeze up to 100,000 current memberships of one inbound and return + their count and an opaque token. Search does not narrow this + selection. Tokens expire after 15 minutes and are held in a bounded + in-memory history. + id: freeze-up-to-100000-current-memberships-of-one-inbound-and-return-their-count-and-an-opaque-token-search-does-not-narrow-this-selection-tokens-expire-after-15-minutes-and-are-held-in-a-bounded-in-memory-history + - content: Detach client memberships while keeping records and traffic. Legacy + email requests accept multiple inbounds and return + detached/skipped/errors lists. Scoped requests take exactly one + inbound and either explicit clientIds or a frozen allMatching + scopeToken with excludedClientIds. Supply a requestId UUID and reuse + it with the same payload when retrying. The scoped response is + {jobId}. Poll GET /bulkDetach/:id for progress and counts. Changed + memberships are skipped and newly attached clients stay outside a + frozen scope. + id: detach-client-memberships-while-keeping-records-and-traffic-legacy-email-requests-accept-multiple-inbounds-and-return-detachedskippederrors-lists-scoped-requests-take-exactly-one-inbound-and-either-explicit-clientids-or-a-frozen-allmatching-scopetoken-with-excludedclientids-supply-a-requestid-uuid-and-reuse-it-with-the-same-payload-when-retrying-the-scoped-response-is-jobid-poll-get-bulkdetachid-for-progress-and-counts-changed-memberships-are-skipped-and-newly-attached-clients-stay-outside-a-frozen-scope + - content: Poll a scoped detachment job. A completed result reports detached, + skipped and failed client counts and whether node reconciliation is + pending. Jobs are retained in a bounded in-memory history for up to 15 + minutes after completion. + id: poll-a-scoped-detachment-job-a-completed-result-reports-detached-skipped-and-failed-client-counts-and-whether-node-reconciliation-is-pending-jobs-are-retained-in-a-bounded-in-memory-history-for-up-to-15-minutes-after-completion - content: Zero up/down counters for many clients in one call. Loops the single-reset path so each client its quota had disabled is re-enabled across its attached inbounds and pushed to Xray/remote nodes; a client @@ -1042,7 +1071,7 @@ _openapi: 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 + heading: detach-client-memberships-while-keeping-records-and-traffic-legacy-email-requests-accept-multiple-inbounds-and-return-detachedskippederrors-lists-scoped-requests-take-exactly-one-inbound-and-either-explicit-clientids-or-a-frozen-allmatching-scopetoken-with-excludedclientids-supply-a-requestid-uuid-and-reuse-it-with-the-same-payload-when-retrying-the-scoped-response-is-jobid-poll-get-bulkdetachid-for-progress-and-counts-changed-memberships-are-skipped-and-newly-attached-clients-stay-outside-a-frozen-scope - content: Add mode excludes current members. Remove mode selects current members. Links mode selects members with a subscription ID. Search matches email, comment and group. freeze=true returns only the matching count, @@ -1059,7 +1088,7 @@ export default function Layout(props) { return ( <> {props.children} - + ); } \ No newline at end of file diff --git a/docs/public/openapi.json b/docs/public/openapi.json index 8b68fdee1..2f5c4c0cd 100644 --- a/docs/public/openapi.json +++ b/docs/public/openapi.json @@ -3432,6 +3432,124 @@ ], "type": "object" }, + "DetachCandidate": { + "properties": { + "comment": { + "type": "string" + }, + "email": { + "type": "string" + }, + "enable": { + "type": "boolean" + }, + "id": { + "type": "integer" + }, + "inScope": { + "type": "boolean" + } + }, + "required": [ + "comment", + "email", + "enable", + "id", + "inScope" + ], + "type": "object" + }, + "DetachCandidatePage": { + "properties": { + "attached": { + "format": "int64", + "type": "integer" + }, + "items": { + "items": { + "$ref": "#/components/schemas/DetachCandidate" + }, + "type": "array" + }, + "total": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "attached", + "items", + "total" + ], + "type": "object" + }, + "DetachJobStatus": { + "properties": { + "error": { + "type": "string" + }, + "processed": { + "type": "integer" + }, + "result": { + "allOf": [ + { + "$ref": "#/components/schemas/DetachSelectionResult" + } + ], + "nullable": true + }, + "running": { + "type": "boolean" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "processed", + "running", + "total" + ], + "type": "object" + }, + "DetachScopeSummary": { + "properties": { + "scopeToken": { + "type": "string" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "scopeToken", + "total" + ], + "type": "object" + }, + "DetachSelectionResult": { + "properties": { + "detached": { + "type": "integer" + }, + "errors": { + "type": "integer" + }, + "nodePending": { + "type": "boolean" + }, + "skipped": { + "type": "integer" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "ExternalLinkInput": { "description": "ExternalLinkInput is one row from the client form's Links tab.", "properties": { @@ -13695,12 +13813,150 @@ } } }, + "/panel/api/clients/detachCandidates": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Read up to 100 clients currently attached to one inbound. Search matches email or comment. The response includes filtered and attached totals, and marks candidates belonging to an optional frozen scope.", + "operationId": "get_panel_api_clients_detachCandidates", + "parameters": [ + { + "name": "inboundId", + "in": "query", + "required": true, + "description": "Source inbound ID.", + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "1-indexed page, defaults to 1.", + "schema": { + "type": "integer" + } + }, + { + "name": "search", + "in": "query", + "required": false, + "description": "Email or comment substring.", + "schema": { + "type": "string" + } + }, + { + "name": "scopeToken", + "in": "query", + "required": false, + "description": "Token from the freeze endpoint.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachCandidatePage" + } + } + }, + "example": { + "success": true, + "obj": { + "attached": 0, + "items": [ + { + "comment": "", + "email": "", + "enable": false, + "id": 0, + "inScope": false + } + ], + "total": 0 + } + } + } + } + } + } + } + }, + "/panel/api/clients/detachCandidates/freeze": { + "post": { + "tags": [ + "Clients" + ], + "summary": "Freeze up to 100,000 current memberships of one inbound and return their count and an opaque token. Search does not narrow this selection. Tokens expire after 15 minutes and are held in a bounded in-memory history.", + "operationId": "post_panel_api_clients_detachCandidates_freeze", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + }, + "example": { + "inboundId": 7 + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachScopeSummary" + } + } + }, + "example": { + "success": true, + "obj": { + "scopeToken": "", + "total": 0 + } + } + } + } + } + } + } + }, "/panel/api/clients/bulkDetach": { "post": { "tags": [ "Clients" ], - "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.", + "summary": "Detach client memberships while keeping records and traffic. Legacy email requests accept multiple inbounds and return detached/skipped/errors lists. Scoped requests take exactly one inbound and either explicit clientIds or a frozen allMatching scopeToken with excludedClientIds. Supply a requestId UUID and reuse it with the same payload when retrying. The scoped response is {jobId}. Poll GET /bulkDetach/:id for progress and counts. Changed memberships are skipped and newly attached clients stay outside a frozen scope.", "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": { @@ -13715,7 +13971,15 @@ "items": { "type": "string" }, - "description": "Emails of existing clients to detach." + "description": "Emails of existing clients to detach. Use either emails or selection." + }, + "selection": { + "type": "object", + "description": "Explicit IDs or a frozen scope with exclusions." + }, + "requestId": { + "type": "string", + "description": "UUID required for scoped requests. Retries are idempotent while job history is retained." }, "inboundIds": { "type": "array", @@ -13726,7 +13990,6 @@ } }, "required": [ - "emails", "inboundIds" ] }, @@ -13790,6 +14053,59 @@ } } }, + "/panel/api/clients/bulkDetach/{id}": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Poll a scoped detachment job. A completed result reports detached, skipped and failed client counts and whether node reconciliation is pending. Jobs are retained in a bounded in-memory history for up to 15 minutes after completion.", + "operationId": "get_panel_api_clients_bulkDetach_id", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Job ID returned by bulkDetach.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachJobStatus" + } + } + }, + "example": { + "success": true, + "obj": { + "error": "", + "processed": 0, + "result": null, + "running": false, + "total": 0 + } + } + } + } + } + } + } + }, "/panel/api/clients/bulkResetTraffic": { "post": { "tags": [ diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json index 8b68fdee1..2f5c4c0cd 100644 --- a/frontend/public/openapi.json +++ b/frontend/public/openapi.json @@ -3432,6 +3432,124 @@ ], "type": "object" }, + "DetachCandidate": { + "properties": { + "comment": { + "type": "string" + }, + "email": { + "type": "string" + }, + "enable": { + "type": "boolean" + }, + "id": { + "type": "integer" + }, + "inScope": { + "type": "boolean" + } + }, + "required": [ + "comment", + "email", + "enable", + "id", + "inScope" + ], + "type": "object" + }, + "DetachCandidatePage": { + "properties": { + "attached": { + "format": "int64", + "type": "integer" + }, + "items": { + "items": { + "$ref": "#/components/schemas/DetachCandidate" + }, + "type": "array" + }, + "total": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "attached", + "items", + "total" + ], + "type": "object" + }, + "DetachJobStatus": { + "properties": { + "error": { + "type": "string" + }, + "processed": { + "type": "integer" + }, + "result": { + "allOf": [ + { + "$ref": "#/components/schemas/DetachSelectionResult" + } + ], + "nullable": true + }, + "running": { + "type": "boolean" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "processed", + "running", + "total" + ], + "type": "object" + }, + "DetachScopeSummary": { + "properties": { + "scopeToken": { + "type": "string" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "scopeToken", + "total" + ], + "type": "object" + }, + "DetachSelectionResult": { + "properties": { + "detached": { + "type": "integer" + }, + "errors": { + "type": "integer" + }, + "nodePending": { + "type": "boolean" + }, + "skipped": { + "type": "integer" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "ExternalLinkInput": { "description": "ExternalLinkInput is one row from the client form's Links tab.", "properties": { @@ -13695,12 +13813,150 @@ } } }, + "/panel/api/clients/detachCandidates": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Read up to 100 clients currently attached to one inbound. Search matches email or comment. The response includes filtered and attached totals, and marks candidates belonging to an optional frozen scope.", + "operationId": "get_panel_api_clients_detachCandidates", + "parameters": [ + { + "name": "inboundId", + "in": "query", + "required": true, + "description": "Source inbound ID.", + "schema": { + "type": "integer" + } + }, + { + "name": "page", + "in": "query", + "required": false, + "description": "1-indexed page, defaults to 1.", + "schema": { + "type": "integer" + } + }, + { + "name": "search", + "in": "query", + "required": false, + "description": "Email or comment substring.", + "schema": { + "type": "string" + } + }, + { + "name": "scopeToken", + "in": "query", + "required": false, + "description": "Token from the freeze endpoint.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachCandidatePage" + } + } + }, + "example": { + "success": true, + "obj": { + "attached": 0, + "items": [ + { + "comment": "", + "email": "", + "enable": false, + "id": 0, + "inScope": false + } + ], + "total": 0 + } + } + } + } + } + } + } + }, + "/panel/api/clients/detachCandidates/freeze": { + "post": { + "tags": [ + "Clients" + ], + "summary": "Freeze up to 100,000 current memberships of one inbound and return their count and an opaque token. Search does not narrow this selection. Tokens expire after 15 minutes and are held in a bounded in-memory history.", + "operationId": "post_panel_api_clients_detachCandidates_freeze", + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "type": "object" + }, + "example": { + "inboundId": 7 + } + } + } + }, + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachScopeSummary" + } + } + }, + "example": { + "success": true, + "obj": { + "scopeToken": "", + "total": 0 + } + } + } + } + } + } + } + }, "/panel/api/clients/bulkDetach": { "post": { "tags": [ "Clients" ], - "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.", + "summary": "Detach client memberships while keeping records and traffic. Legacy email requests accept multiple inbounds and return detached/skipped/errors lists. Scoped requests take exactly one inbound and either explicit clientIds or a frozen allMatching scopeToken with excludedClientIds. Supply a requestId UUID and reuse it with the same payload when retrying. The scoped response is {jobId}. Poll GET /bulkDetach/:id for progress and counts. Changed memberships are skipped and newly attached clients stay outside a frozen scope.", "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": { @@ -13715,7 +13971,15 @@ "items": { "type": "string" }, - "description": "Emails of existing clients to detach." + "description": "Emails of existing clients to detach. Use either emails or selection." + }, + "selection": { + "type": "object", + "description": "Explicit IDs or a frozen scope with exclusions." + }, + "requestId": { + "type": "string", + "description": "UUID required for scoped requests. Retries are idempotent while job history is retained." }, "inboundIds": { "type": "array", @@ -13726,7 +13990,6 @@ } }, "required": [ - "emails", "inboundIds" ] }, @@ -13790,6 +14053,59 @@ } } }, + "/panel/api/clients/bulkDetach/{id}": { + "get": { + "tags": [ + "Clients" + ], + "summary": "Poll a scoped detachment job. A completed result reports detached, skipped and failed client counts and whether node reconciliation is pending. Jobs are retained in a bounded in-memory history for up to 15 minutes after completion.", + "operationId": "get_panel_api_clients_bulkDetach_id", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "description": "Job ID returned by bulkDetach.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "success": { + "type": "boolean" + }, + "msg": { + "type": "string" + }, + "obj": { + "$ref": "#/components/schemas/DetachJobStatus" + } + } + }, + "example": { + "success": true, + "obj": { + "error": "", + "processed": 0, + "result": null, + "running": false, + "total": 0 + } + } + } + } + } + } + } + }, "/panel/api/clients/bulkResetTraffic": { "post": { "tags": [ diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts index 92a67521a..c8ca0d3d9 100644 --- a/frontend/src/generated/examples.ts +++ b/frontend/src/generated/examples.ts @@ -949,6 +949,43 @@ export const EXAMPLES: Record = { "onlineCount": 1, "total": 2000 }, + "DetachCandidate": { + "comment": "", + "email": "", + "enable": false, + "id": 0, + "inScope": false + }, + "DetachCandidatePage": { + "attached": 0, + "items": [ + { + "comment": "", + "email": "", + "enable": false, + "id": 0, + "inScope": false + } + ], + "total": 0 + }, + "DetachJobStatus": { + "error": "", + "processed": 0, + "result": null, + "running": false, + "total": 0 + }, + "DetachScopeSummary": { + "scopeToken": "", + "total": 0 + }, + "DetachSelectionResult": { + "detached": 0, + "errors": 0, + "nodePending": false, + "skipped": 0 + }, "ExternalLinkInput": { "enable": true, "expiryTime": 0, diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts index f9406a3b4..ebc2d304c 100644 --- a/frontend/src/generated/schemas.ts +++ b/frontend/src/generated/schemas.ts @@ -3406,6 +3406,124 @@ export const SCHEMAS: Record = { ], "type": "object" }, + "DetachCandidate": { + "properties": { + "comment": { + "type": "string" + }, + "email": { + "type": "string" + }, + "enable": { + "type": "boolean" + }, + "id": { + "type": "integer" + }, + "inScope": { + "type": "boolean" + } + }, + "required": [ + "comment", + "email", + "enable", + "id", + "inScope" + ], + "type": "object" + }, + "DetachCandidatePage": { + "properties": { + "attached": { + "format": "int64", + "type": "integer" + }, + "items": { + "items": { + "$ref": "#/components/schemas/DetachCandidate" + }, + "type": "array" + }, + "total": { + "format": "int64", + "type": "integer" + } + }, + "required": [ + "attached", + "items", + "total" + ], + "type": "object" + }, + "DetachJobStatus": { + "properties": { + "error": { + "type": "string" + }, + "processed": { + "type": "integer" + }, + "result": { + "allOf": [ + { + "$ref": "#/components/schemas/DetachSelectionResult" + } + ], + "nullable": true + }, + "running": { + "type": "boolean" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "processed", + "running", + "total" + ], + "type": "object" + }, + "DetachScopeSummary": { + "properties": { + "scopeToken": { + "type": "string" + }, + "total": { + "type": "integer" + } + }, + "required": [ + "scopeToken", + "total" + ], + "type": "object" + }, + "DetachSelectionResult": { + "properties": { + "detached": { + "type": "integer" + }, + "errors": { + "type": "integer" + }, + "nodePending": { + "type": "boolean" + }, + "skipped": { + "type": "integer" + } + }, + "required": [ + "detached", + "errors", + "skipped" + ], + "type": "object" + }, "ExternalLinkInput": { "description": "ExternalLinkInput is one row from the client form's Links tab.", "properties": { diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts index 2f6d4934a..0a49bf41c 100644 --- a/frontend/src/generated/types.ts +++ b/frontend/src/generated/types.ts @@ -788,6 +788,40 @@ export interface ClientsSummary { total: number; } +export interface DetachCandidate { + comment: string; + email: string; + enable: boolean; + id: number; + inScope: boolean; +} + +export interface DetachCandidatePage { + attached: number; + items: DetachCandidate[]; + total: number; +} + +export interface DetachJobStatus { + error?: string; + processed: number; + result?: DetachSelectionResult | null; + running: boolean; + total: number; +} + +export interface DetachScopeSummary { + scopeToken: string; + total: number; +} + +export interface DetachSelectionResult { + detached: number; + errors: number; + nodePending?: boolean; + skipped: number; +} + export interface ExternalLinkInput { enable?: boolean | null; expiryTime?: number; diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts index 3885815c8..9078e9286 100644 --- a/frontend/src/generated/zod.ts +++ b/frontend/src/generated/zod.ts @@ -838,6 +838,45 @@ export const ClientsSummarySchema = z.object({ }); export type ClientsSummary = z.infer; +export const DetachCandidateSchema = z.object({ + comment: z.string(), + email: z.string(), + enable: z.boolean(), + id: z.number().int(), + inScope: z.boolean(), +}); +export type DetachCandidate = z.infer; + +export const DetachCandidatePageSchema = z.object({ + attached: z.number().int(), + items: z.array(z.lazy(() => DetachCandidateSchema)), + total: z.number().int(), +}); +export type DetachCandidatePage = z.infer; + +export const DetachJobStatusSchema = z.object({ + error: z.string().optional(), + processed: z.number().int(), + result: z.lazy(() => DetachSelectionResultSchema).nullable().optional(), + running: z.boolean(), + total: z.number().int(), +}); +export type DetachJobStatus = z.infer; + +export const DetachScopeSummarySchema = z.object({ + scopeToken: z.string(), + total: z.number().int(), +}); +export type DetachScopeSummary = z.infer; + +export const DetachSelectionResultSchema = z.object({ + detached: z.number().int(), + errors: z.number().int(), + nodePending: z.boolean().optional(), + skipped: z.number().int(), +}); +export type DetachSelectionResult = z.infer; + export const ExternalLinkInputSchema = z.object({ enable: z.boolean().nullable().optional(), expiryTime: z.number().int().optional(), diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts index cc420f88a..973fe5c5a 100644 --- a/frontend/src/pages/api-docs/endpoints.ts +++ b/frontend/src/pages/api-docs/endpoints.ts @@ -1931,18 +1931,72 @@ export const sections: readonly Section[] = [ ], responseSchema: 'AttachJobStatus', }, + { + method: 'GET', + path: '/panel/api/clients/detachCandidates', + summary: + 'Read up to 100 clients currently attached to one inbound. Search matches email or comment. The response includes filtered and attached totals, and marks candidates belonging to an optional frozen scope.', + params: [ + { name: 'inboundId', in: 'query', type: 'integer', desc: 'Source inbound ID.' }, + { + name: 'page', + in: 'query', + type: 'integer', + desc: '1-indexed page, defaults to 1.', + optional: true, + }, + { + name: 'search', + in: 'query', + type: 'string', + desc: 'Email or comment substring.', + optional: true, + }, + { + name: 'scopeToken', + in: 'query', + type: 'string', + desc: 'Token from the freeze endpoint.', + optional: true, + }, + ], + responseSchema: 'DetachCandidatePage', + }, + { + method: 'POST', + path: '/panel/api/clients/detachCandidates/freeze', + summary: + 'Freeze up to 100,000 current memberships of one inbound and return their count and an opaque token. Search does not narrow this selection. Tokens expire after 15 minutes and are held in a bounded in-memory history.', + body: '{\n "inboundId": 7\n}', + responseSchema: 'DetachScopeSummary', + }, { 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.", + 'Detach client memberships while keeping records and traffic. Legacy email requests accept multiple inbounds and return detached/skipped/errors lists. Scoped requests take exactly one inbound and either explicit clientIds or a frozen allMatching scopeToken with excludedClientIds. Supply a requestId UUID and reuse it with the same payload when retrying. The scoped response is {jobId}. Poll GET /bulkDetach/:id for progress and counts. Changed memberships are skipped and newly attached clients stay outside a frozen scope.', params: [ { name: 'emails', in: 'body (json)', type: 'string[]', - desc: 'Emails of existing clients to detach.', + desc: 'Emails of existing clients to detach. Use either emails or selection.', + optional: true, + }, + { + name: 'selection', + in: 'body (json)', + type: 'object', + desc: 'Explicit IDs or a frozen scope with exclusions.', + optional: true, + }, + { + name: 'requestId', + in: 'body (json)', + type: 'string', + desc: 'UUID required for scoped requests. Retries are idempotent while job history is retained.', + optional: true, }, { name: 'inboundIds', @@ -1954,6 +2008,16 @@ export const sections: readonly Section[] = [ body: '{\n "emails": ["alice", "bob"],\n "inboundIds": [7, 9]\n}', responseSchema: 'BulkDetachResult', }, + { + method: 'GET', + path: '/panel/api/clients/bulkDetach/:id', + summary: + 'Poll a scoped detachment job. A completed result reports detached, skipped and failed client counts and whether node reconciliation is pending. Jobs are retained in a bounded in-memory history for up to 15 minutes after completion.', + params: [ + { name: 'id', in: 'path', type: 'string', desc: 'Job ID returned by bulkDetach.' }, + ], + responseSchema: 'DetachJobStatus', + }, { method: 'POST', path: '/panel/api/clients/bulkResetTraffic', diff --git a/frontend/src/pages/inbounds/clients/DetachClientsModal.stories.tsx b/frontend/src/pages/inbounds/clients/DetachClientsModal.stories.tsx new file mode 100644 index 000000000..6273d36da --- /dev/null +++ b/frontend/src/pages/inbounds/clients/DetachClientsModal.stories.tsx @@ -0,0 +1,134 @@ +import type { Meta, StoryObj } from '@storybook/react-vite'; +import { expect, waitFor, within } from 'storybook/test'; +import { DBInbound } from '@/models/dbinbound'; +import { HttpUtil, Msg } from '@/utils'; +import DetachClientsModal from './DetachClientsModal'; + +function Fixture({ population }: { population: number }) { + const source = new DBInbound({ + id: population, + tag: 'large-inbound', + protocol: 'vless', + settings: JSON.stringify({ + clients: Array.from({ length: population }, (_, i) => ({ + email: 'client-' + (i + 1) + '@test', + })), + }), + }); + return {}} />; +} + +const meta = { title: 'Inbounds/Detach Clients', component: Fixture } satisfies Meta< + typeof Fixture +>; +export default meta; +type Story = StoryObj; + +function largeInbound(population: number): Story { + let submitted: unknown; + let openedAt = 0; + let longTasks: number[] = []; + return { + args: { population }, + beforeEach: () => { + const { get, post } = HttpUtil; + submitted = undefined; + openedAt = performance.now(); + longTasks = []; + const observer = new PerformanceObserver((list) => { + for (const task of list.getEntries()) longTasks.push(task.duration); + }); + if (PerformanceObserver.supportedEntryTypes.includes('longtask')) { + observer.observe({ entryTypes: ['longtask'] }); + } + HttpUtil.get = async (url: string, params?: unknown) => { + if (url.endsWith('/fixture-job')) { + return new Msg(true, '', { + running: false, + processed: population - 1, + total: population - 1, + result: { detached: population - 1, skipped: 0, errors: 0 }, + } as T); + } + const { page, search, scopeToken } = params as { + page: number; + search: string; + scopeToken?: string; + }; + const ids = + search === 'client-101@test' + ? [101] + : Array.from({ length: 100 }, (_, i) => (page - 1) * 100 + i + 1); + return new Msg(true, '', { + items: ids.map((id) => ({ + id, + email: 'client-' + id + '@test', + enable: true, + inScope: Boolean(scopeToken), + })), + total: search ? 1 : population, + attached: population, + } as T); + }; + HttpUtil.post = async (url: string, payload?: unknown) => { + if (url.endsWith('/freeze')) { + return new Msg(true, '', { scopeToken: 'fixture-scope', total: population } as T); + } + submitted = payload; + return new Msg(true, '', { jobId: 'fixture-job' } as T); + }; + return () => { + observer.disconnect(); + HttpUtil.get = get; + HttpUtil.post = post; + }; + }, + play: async ({ canvasElement, userEvent }) => { + const screen = within(canvasElement.ownerDocument.body); + const first = await screen.findByRole('checkbox', { name: 'client-1@test' }); + const openMs = performance.now() - openedAt; + const dialog = await screen.findByRole('dialog'); + const rendered = dialog.querySelectorAll('[data-row-key]').length; + await expect(rendered).toBeGreaterThan(0); + await expect(rendered).toBeLessThanOrEqual(100); + const toggleStart = performance.now(); + await userEvent.click(first); + await expect(first).toBeChecked(); + const toggleMs = performance.now() - toggleStart; + await userEvent.click(screen.getByRole('button', { name: 'Select this page' })); + await expect(screen.getByText('100 selected')).toBeVisible(); + + await userEvent.click(screen.getByText('2', { exact: true })); + await screen.findByRole('checkbox', { name: 'client-101@test' }); + await userEvent.click(screen.getByRole('button', { name: 'Select all attached clients' })); + const row = () => screen.getByRole('checkbox', { name: 'client-101@test' }); + await waitFor(() => expect(row()).toBeChecked()); + await userEvent.click(row()); + + const searchStart = performance.now(); + await userEvent.type(screen.getByRole('searchbox', { name: 'Search' }), 'client-101@test'); + await waitFor(() => expect(row()).not.toBeChecked()); + const searchMs = performance.now() - searchStart; + await userEvent.click(screen.getByRole('button', { name: 'Detach Clients' })); + await waitFor(() => + expect(submitted).toEqual({ + requestId: expect.any(String), + inboundIds: [population], + selection: { mode: 'allMatching', scopeToken: 'fixture-scope', excludedClientIds: [101] }, + }), + ); + console.info('Detach picker', { + population, + rendered, + openMs, + toggleMs, + searchMs, + longestTaskMs: Math.max(0, ...longTasks), + }); + }, + }; +} + +export const Thousand = largeInbound(1_000); +export const TenThousand = largeInbound(10_000); +export const FiftyThousand = largeInbound(50_000); diff --git a/frontend/src/pages/inbounds/clients/DetachClientsModal.tsx b/frontend/src/pages/inbounds/clients/DetachClientsModal.tsx index bbf3b5e19..8f091b1f1 100644 --- a/frontend/src/pages/inbounds/clients/DetachClientsModal.tsx +++ b/frontend/src/pages/inbounds/clients/DetachClientsModal.tsx @@ -1,10 +1,32 @@ -import { useMemo, useState } from 'react'; +import { useEffect, useRef, useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Input, Modal, Space, Table, Tag, Typography, message } from 'antd'; +import { + Alert, + Button, + Input, + Modal, + Pagination, + Progress, + Space, + Table, + Tag, + Typography, + message, +} from 'antd'; import type { ColumnsType } from 'antd/es/table'; -import { HttpUtil } from '@/utils'; -import { coerceInboundJsonField, type DBInbound } from '@/models/dbinbound'; +import type { + DetachCandidate as ClientRow, + DetachCandidatePage as CandidatePage, + DetachJobStatus as JobStatus, + DetachScopeSummary as FrozenSelection, +} from '@/generated/types'; +import { HttpUtil, PromiseUtil, RandomUtil } from '@/utils'; +import type { DBInbound } from '@/models/dbinbound'; + +const PAGE_SIZE = 100; +const CANDIDATES = '/panel/api/clients/detachCandidates'; +const DETACH = '/panel/api/clients/bulkDetach'; interface DetachClientsModalProps { open: boolean; @@ -13,175 +35,392 @@ interface DetachClientsModalProps { onDetached?: () => void; } -interface BulkDetachResult { - detached?: string[]; - skipped?: string[]; - errors?: string[]; -} - -interface ClientRow { - email: string; - comment: string; - enable: boolean; -} - -function readClientRows(settings: unknown): ClientRow[] { - const parsed = coerceInboundJsonField(settings) as { - clients?: Array<{ email?: string; comment?: string; enable?: boolean }>; - }; - const clients = Array.isArray(parsed?.clients) ? parsed.clients : []; - return clients - .map((c) => ({ - email: (c?.email || '').trim(), - comment: (c?.comment || '').trim(), - enable: c?.enable !== false, - })) - .filter((r) => r.email); -} - export default function DetachClientsModal({ open, source, + ...callbacks +}: DetachClientsModalProps) { + if (!open || !source) return null; + return ; +} + +function DetachClientPicker({ + id, + tag, onClose, onDetached, -}: DetachClientsModalProps) { +}: Pick & { id: number; tag: string }) { const { t } = useTranslation(); - const [messageApi, messageContextHolder] = message.useMessage(); - const [saving, setSaving] = useState(false); - const [clientRows, setClientRows] = useState([]); - const [selectedEmails, setSelectedEmails] = useState([]); + const [messages, holder] = message.useMessage(); const [search, setSearch] = useState(''); + const [page, setPage] = useState(1); + const [rows, setRows] = useState(); + const [loading, setLoading] = useState(true); + const [loadError, setLoadError] = useState(''); + const [retry, setRetry] = useState(0); + const [busy, setBusy] = useState<'freeze' | 'submit'>(); + const [frozen, setFrozen] = useState(); + const [choices, setChoices] = useState(new Map()); + const [exclusionPage, setExclusionPage] = useState(1); + const [jobId, setJobId] = useState(); + const [progress, setProgress] = useState(); + const action = useRef(undefined); + const requestId = useRef(undefined); + const scopeToken = frozen?.scopeToken; + const selected = frozen ? frozen.total - choices.size : choices.size; + const locked = Boolean(busy || jobId); + const pageRows = rows?.items ?? []; - // Reset during render, not in an effect, so the first frame is already clean. - const openSource = open ? source : null; - const [syncedSource, setSyncedSource] = useState(null); - if (openSource !== syncedSource) { - setSyncedSource(openSource); - if (openSource) { - setClientRows(readClientRows(openSource.settings)); - setSelectedEmails([]); - setSearch(''); - } + useEffect(() => () => action.current?.abort(), []); + + useEffect(() => { + const request = new AbortController(); + const timer = window.setTimeout( + async () => { + const response = await HttpUtil.get( + CANDIDATES, + { inboundId: id, page, search, scopeToken }, + { signal: request.signal, silent: true }, + ); + if (request.signal.aborted) return; + if (response?.success && response.obj) { + const lastPage = Math.max(1, Math.ceil(response.obj.total / PAGE_SIZE)); + if (page > lastPage) { + setPage(lastPage); + return; + } + setRows(response.obj); + setLoadError(''); + } else { + setRows(undefined); + setLoadError(response?.msg || t('somethingWentWrong')); + } + setLoading(false); + }, + search.trim() ? 220 : 0, + ); + return () => { + window.clearTimeout(timer); + request.abort(); + }; + }, [id, page, search, scopeToken, retry, t]); + + function reloadPage() { + setRows((previous) => (previous ? { ...previous, items: [] } : undefined)); + setLoadError(''); + setLoading(true); } - const filteredRows = useMemo(() => { - const q = search.trim().toLowerCase(); - if (!q) return clientRows; - return clientRows.filter( - (r) => r.email.toLowerCase().includes(q) || r.comment.toLowerCase().includes(q), - ); - }, [clientRows, search]); + function changeSelection(next: Map) { + setChoices(next); + setExclusionPage((current) => Math.min(current, Math.max(1, Math.ceil(next.size / 10)))); + requestId.current = undefined; + } - const columns: ColumnsType = useMemo( - () => [ - { - title: t('pages.inbounds.email'), - dataIndex: 'email', - key: 'email', - ellipsis: true, - }, - { - title: t('comment'), - dataIndex: 'comment', - key: 'comment', - ellipsis: true, - }, - { - title: t('enable'), - dataIndex: 'enable', - key: 'enable', - width: 90, - render: (enabled: boolean) => - enabled ? ( - {t('enable')} - ) : ( - {t('pages.inbounds.attachClientsStatusDisabled')} - ), - }, - ], - [t], - ); + function clearSelection() { + if (frozen) reloadPage(); + setFrozen(undefined); + changeSelection(new Map()); + setExclusionPage(1); + } - async function submit() { - if (!source || selectedEmails.length === 0) return; - setSaving(true); + function pickPage(keys: React.Key[]) { + const checked = new Set(keys); + const next = new Map(choices); + for (const row of pageRows) { + if (frozen && !row.inScope) continue; + if (checked.has(row.id) !== Boolean(frozen)) next.set(row.id, row.email); + else next.delete(row.id); + } + changeSelection(next); + } + + async function freeze() { + if (action.current || locked) return; + const operation = new AbortController(); + action.current = operation; + setBusy('freeze'); try { - const msg = await HttpUtil.post( - '/panel/api/clients/bulkDetach', - { emails: selectedEmails, inboundIds: [source.id] }, - { headers: { 'Content-Type': 'application/json' } }, + const response = await HttpUtil.post( + CANDIDATES + '/freeze', + { inboundId: id }, + { signal: operation.signal, silent: true }, ); - if (!msg?.success) { - messageApi.error(msg?.msg || t('somethingWentWrong')); + if (operation.signal.aborted) return; + if (!response?.success || !response.obj?.scopeToken) { + messages.error(response?.msg || t('somethingWentWrong')); return; } - const result = (msg.obj || {}) as BulkDetachResult; - const detached = result.detached?.length ?? 0; - const skipped = result.skipped?.length ?? 0; - const errors = result.errors?.length ?? 0; - if (errors > 0) { - messageApi.warning( - t('pages.inbounds.detachClientsResultMixed', { detached, skipped, errors }), - ); - } else { - messageApi.success(t('pages.inbounds.detachClientsResult', { detached, skipped })); - } - onDetached?.(); - onClose(); + reloadPage(); + changeSelection(new Map()); + setExclusionPage(1); + setFrozen(response.obj); } finally { - setSaving(false); + action.current = undefined; + if (!operation.signal.aborted) setBusy(undefined); } } + async function submit() { + if (action.current || (!jobId && selected <= 0)) return; + const operation = new AbortController(); + action.current = operation; + setBusy('submit'); + try { + let job = jobId; + if (!job) { + const selection = frozen + ? { + mode: 'allMatching', + scopeToken: frozen.scopeToken, + excludedClientIds: [...choices.keys()], + } + : { mode: 'explicit', clientIds: [...choices.keys()] }; + requestId.current ??= RandomUtil.randomUUID(); + const response = await HttpUtil.post<{ jobId: string }>( + DETACH, + { inboundIds: [id], selection, requestId: requestId.current }, + { signal: operation.signal, silent: true }, + ); + if (operation.signal.aborted) return; + if (!response?.success || !response.obj?.jobId) { + messages.error(response?.msg || t('somethingWentWrong')); + return; + } + job = response.obj.jobId; + setJobId(job); + } + + let failures = 0; + const deadline = Date.now() + 6 * 60_000; + while (!operation.signal.aborted && Date.now() < deadline) { + const response = await HttpUtil.get( + DETACH + '/' + encodeURIComponent(job), + undefined, + { signal: operation.signal, silent: true }, + ); + if (operation.signal.aborted) return; + if (!response?.success || !response.obj) { + if (++failures >= 3) { + messages.error(response?.msg || t('somethingWentWrong')); + return; + } + } else { + failures = 0; + const status = response.obj; + setProgress(status); + if (!status.running) { + setJobId(undefined); + requestId.current = undefined; + if (status.error && status.result?.detached) { + messages.warning(status.error); + onDetached?.(); + onClose(); + return; + } + if (status.result) { + const { detached, skipped, errors, nodePending } = status.result; + if (errors > 0) + messages.warning( + t('pages.inbounds.detachClientsResultMixed', { detached, skipped, errors }), + ); + else messages.success(t('pages.inbounds.detachClientsResult', { detached, skipped })); + if (nodePending) messages.warning(t('pages.inbounds.detachNodePending')); + } + if (status.error || !status.result) { + messages.error(status.error || t('somethingWentWrong')); + return; + } + onDetached?.(); + onClose(); + return; + } + } + await PromiseUtil.sleep(750); + } + if (!operation.signal.aborted) messages.error(t('somethingWentWrong')); + } finally { + action.current = undefined; + if (!operation.signal.aborted) setBusy(undefined); + } + } + + const columns: ColumnsType = [ + { title: t('pages.inbounds.email'), dataIndex: 'email', ellipsis: true }, + { title: t('comment'), dataIndex: 'comment', ellipsis: true }, + { + title: t('enable'), + dataIndex: 'enable', + width: 90, + render: (enabled: boolean) => + enabled ? ( + {t('enable')} + ) : ( + {t('pages.inbounds.attachClientsStatusDisabled')} + ), + }, + ]; + const selectedKeys = pageRows + .filter((row) => (frozen ? row.inScope && !choices.has(row.id) : choices.has(row.id))) + .map((row) => row.id); + return ( { + if (!busy) onClose(); + }} onOk={submit} okButtonProps={{ danger: true, - disabled: selectedEmails.length === 0, - loading: saving, + disabled: busy === 'freeze' || (!jobId && selected <= 0), + loading: busy === 'submit', }} - okText={t('pages.inbounds.detachClients')} + cancelButtonProps={{ disabled: Boolean(busy) }} + okText={t(jobId ? 'refresh' : 'pages.inbounds.detachClients')} cancelText={t('cancel')} - title={t('pages.inbounds.detachClientsTitle', { remark: source?.tag ?? '' })} + title={t('pages.inbounds.detachClientsTitle', { remark: tag })} width={680} > - {messageContextHolder} - - {t('pages.inbounds.detachClientsDesc', { count: clientRows.length })} - - + {holder} {t('pages.inbounds.detachClientsSelectLabel')} - - setSearch(e.target.value)} - placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} - style={{ maxWidth: 320 }} + {rows && ( + + {t('pages.inbounds.detachClientsDesc', { count: rows.attached })} + + )} + { + reloadPage(); + setPage(1); + setSearch(event.target.value); + }} + placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')} + /> + {loadError && ( + { + reloadPage(); + setRetry(retry + 1); + }} + > + {t('refresh')} + + } /> - - {t('pages.inbounds.attachClientsSelectedCount', { - selected: selectedEmails.length, - total: clientRows.length, - })} + )} + + + + + + {t('pages.inbounds.selectedCount', { count: selected })} + {frozen && choices.size > 0 && ( +
+ + {t('pages.inbounds.attachExcludedClients')} ({choices.size}) + + {Array.from(choices) + .slice((exclusionPage - 1) * 10, exclusionPage * 10) + .map(([clientId, email]) => ( + + ))} + +
+ )} + {progress && ( + + )} size="small" - rowKey="email" + rowKey="id" columns={columns} - dataSource={filteredRows} + dataSource={pageRows} + loading={loading} pagination={false} - scroll={{ y: 280 }} + virtual + scroll={{ x: 540, y: 280 }} rowSelection={{ - selectedRowKeys: selectedEmails, - onChange: (keys) => setSelectedEmails(keys as string[]), - preserveSelectedRowKeys: true, + hideSelectAll: true, + columnTitle: ( + + {t('pages.inbounds.detachClientsSelectLabel')} + + ), + selectedRowKeys: selectedKeys, + getCheckboxProps: (row) => ({ + disabled: locked || Boolean(frozen && !row.inScope), + 'aria-label': row.email, + }), + onChange: pickPage, + }} + /> + { + reloadPage(); + setPage(next); }} />
diff --git a/frontend/src/test/detach-clients-modal.test.tsx b/frontend/src/test/detach-clients-modal.test.tsx index 89d3352bb..5b9928308 100644 --- a/frontend/src/test/detach-clients-modal.test.tsx +++ b/frontend/src/test/detach-clients-modal.test.tsx @@ -1,8 +1,9 @@ -import { describe, expect, it } from 'vitest'; -import { screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { act, fireEvent, screen, waitFor } from '@testing-library/react'; import DetachClientsModal from '@/pages/inbounds/clients/DetachClientsModal'; import { DBInbound } from '@/models/dbinbound'; +import { HttpUtil, Msg } from '@/utils'; import { renderWithProviders } from './test-utils'; @@ -27,10 +28,153 @@ function sourceInbound() { } describe('DetachClientsModal', () => { - it('lists the attached clients when first mounted already open', async () => { + it('uses the bounded server page instead of rendering embedded settings clients', async () => { + const get = vi.spyOn(HttpUtil, 'get').mockResolvedValue( + new Msg(true, '', { + items: [{ id: 12, email: 'server@test', comment: '', enable: true, inScope: false }], + total: 50000, + attached: 50000, + }), + ); renderWithProviders( {}} />); - expect(await screen.findByText('alice@test')).toBeTruthy(); - expect(screen.getByText('bob@test')).toBeTruthy(); + expect(await screen.findByText('server@test')).toBeTruthy(); + expect(screen.queryByText('alice@test')).toBeNull(); + expect(get).toHaveBeenCalledWith( + '/panel/api/clients/detachCandidates', + expect.objectContaining({ inboundId: 7, page: 1 }), + expect.anything(), + ); + }); + + it('keeps page and frozen selections separate and sends only the scope and exclusions', async () => { + const status = '/panel/api/clients/bulkDetach/job-1'; + const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (url, params) => { + if (url === status) { + return new Msg(true, '', { + running: false, + processed: 49999, + total: 49999, + result: { detached: 49998, skipped: 1, errors: 0 }, + }); + } + const { page, search, scopeToken } = params as { + page: number; + search: string; + scopeToken?: string; + }; + const id = page === 2 || search ? 101 : 1; + return new Msg(true, '', { + items: [ + { + id, + email: 'client-' + id + '@test', + comment: '', + enable: true, + inScope: Boolean(scopeToken), + }, + ], + total: search ? 1 : 50000, + attached: 50000, + }); + }); + const post = vi + .spyOn(HttpUtil, 'post') + .mockImplementation( + async (url) => + new Msg( + true, + '', + url.endsWith('/freeze') ? { scopeToken: 'frozen', total: 50000 } : { jobId: 'job-1' }, + ), + ); + const detached = vi.fn(); + const close = vi.fn(); + renderWithProviders( + , + ); + await screen.findByText('client-1@test'); + fireEvent.click(screen.getByRole('button', { name: 'Select this page' })); + expect(screen.getByText('1 selected')).toBeTruthy(); + fireEvent.click(screen.getByText('2', { exact: true })); + await waitFor(() => + expect(get).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ page: 2 }), + expect.anything(), + ), + ); + await screen.findByText('client-101@test'); + expect(screen.getByText('1 selected')).toBeTruthy(); + expect( + screen.getByRole('checkbox', { name: 'client-101@test' }).checked, + ).toBe(false); + fireEvent.click(screen.getByRole('button', { name: 'Select all attached clients' })); + const choice = () => + screen.getByRole('checkbox', { name: 'client-101@test' }); + await waitFor(() => expect(choice().checked).toBe(true)); + fireEvent.click(choice()); + expect(screen.getByText('49999 selected')).toBeTruthy(); + fireEvent.change(screen.getByRole('searchbox', { name: 'Search' }), { + target: { value: '101' }, + }); + await waitFor(() => expect(choice().checked).toBe(false)); + fireEvent.click(choice()); + expect(screen.getByText('50000 selected')).toBeTruthy(); + fireEvent.click(choice()); + fireEvent.click(screen.getByRole('button', { name: 'Detach Clients' })); + await waitFor(() => expect(detached).toHaveBeenCalledTimes(1)); + expect(close).toHaveBeenCalledTimes(1); + expect(post).toHaveBeenCalledWith( + '/panel/api/clients/bulkDetach', + { + requestId: expect.any(String), + inboundIds: [7], + selection: { mode: 'allMatching', scopeToken: 'frozen', excludedClientIds: [101] }, + }, + expect.anything(), + ); + }); + + it('ignores an older search response after the server page has changed', async () => { + let release!: (value: Msg) => void; + const old = new Promise((resolve) => { + release = resolve; + }); + const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (_url, params) => { + const { search } = params as { search: string }; + if (search === 'old') return old; + return new Msg(true, '', { + items: [ + { id: 2, email: search + '-current@test', comment: '', enable: true, inScope: false }, + ], + total: 1, + attached: 2, + }); + }); + renderWithProviders( {}} />); + await screen.findByText('-current@test'); + const search = screen.getByRole('searchbox', { name: 'Search' }); + fireEvent.change(search, { target: { value: 'old' } }); + await waitFor(() => + expect(get).toHaveBeenCalledWith( + expect.any(String), + expect.objectContaining({ search: 'old' }), + expect.anything(), + ), + ); + fireEvent.change(search, { target: { value: 'new' } }); + await screen.findByText('new-current@test'); + await act(async () => + release( + new Msg(true, '', { + items: [{ id: 3, email: 'stale@test', comment: '', enable: true }], + total: 1, + attached: 2, + }), + ), + ); + expect(screen.queryByText('stale@test')).toBeNull(); + expect(screen.getByText('new-current@test')).toBeTruthy(); }); }); diff --git a/internal/database/db.go b/internal/database/db.go index 150ff175c..98410f506 100644 --- a/internal/database/db.go +++ b/internal/database/db.go @@ -158,6 +158,40 @@ func migrateClientKeepAliveRangeColumn() error { return migrator.AddColumn(&model.ClientRecord{}, "KeepAliveRange") } +func migrateClientInboundIncarnationColumn() error { + migrator := db.Migrator() + if !migrator.HasTable(&model.ClientInbound{}) || migrator.HasColumn(&model.ClientInbound{}, "incarnation") { + return nil + } + // Existing links can retain the empty identity. Every later insert receives a new one. + return migrator.AddColumn(&model.ClientInbound{}, "Incarnation") +} + +func ensureClientInboundIncarnationTrigger() error { + return db.Transaction(func(tx *gorm.DB) error { + if tx.Name() == DialectSQLite { + return tx.Exec(`CREATE TRIGGER IF NOT EXISTS client_inbounds_incarnation_insert + AFTER INSERT ON client_inbounds BEGIN + UPDATE client_inbounds SET incarnation = lower(hex(randomblob(16))) + WHERE client_id = NEW.client_id AND inbound_id = NEW.inbound_id; + END`).Error + } + if err := tx.Exec(`CREATE OR REPLACE FUNCTION set_client_inbound_incarnation() + RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + NEW.incarnation := md5(random()::text || random()::text || random()::text || clock_timestamp()::text); + RETURN NEW; + END $$`).Error; err != nil { + return err + } + if err := tx.Exec("DROP TRIGGER IF EXISTS client_inbounds_incarnation_insert ON client_inbounds").Error; err != nil { + return err + } + return tx.Exec(`CREATE TRIGGER client_inbounds_incarnation_insert + BEFORE INSERT ON client_inbounds FOR EACH ROW EXECUTE FUNCTION set_client_inbound_incarnation()`).Error + }) +} + func initModels() error { if err := dropSnapshotRevisionTriggers(db); err != nil { return err @@ -165,6 +199,9 @@ func initModels() error { if err := migrateClientKeepAliveRangeColumn(); err != nil { return err } + if err := migrateClientInboundIncarnationColumn(); err != nil { + return err + } if err := migrateClientTrafficLastSubFetchColumn(); err != nil { return err } @@ -269,6 +306,9 @@ func initModels() error { return err } } + if err := ensureClientInboundIncarnationTrigger(); err != nil { + return err + } return migrateSnapshotRevisions(db) } diff --git a/internal/database/model/model.go b/internal/database/model/model.go index dbeaa349e..f797e9227 100644 --- a/internal/database/model/model.go +++ b/internal/database/model/model.go @@ -1187,6 +1187,8 @@ type ClientInbound struct { InboundId int `json:"inboundId" gorm:"primaryKey;column:inbound_id;index"` FlowOverride string `json:"flowOverride" gorm:"column:flow_override"` CreatedAt int64 `json:"createdAt" gorm:"autoCreateTime:milli"` + // Incarnation changes only when the membership is inserted. + Incarnation string `json:"-" gorm:"->;not null;default:''"` } func (ClientInbound) TableName() string { return "client_inbounds" } diff --git a/internal/nodee2e/node_detach_scoped_test.go b/internal/nodee2e/node_detach_scoped_test.go new file mode 100644 index 000000000..e92628705 --- /dev/null +++ b/internal/nodee2e/node_detach_scoped_test.go @@ -0,0 +1,77 @@ +package nodee2e + +import ( + "encoding/json" + "fmt" + "net/http" + "testing" + "time" + + "github.com/google/uuid" +) + +func TestScopedDetachReconcilesOfflineNode(t *testing.T) { + bin := panelBinary(t) + master, node := newPanel(t, bin, "detach-master"), newPanel(t, bin, "detach-node") + master.start() + node.start() + port := freePort(t) + node.call(http.MethodPost, "/panel/api/inbounds/add", + vlessInbound("detach-source", port, nil, vlessClient("detach-me"), vlessClient("keep-me"))) + enrollTrafficNode(t, master, node) + var source inboundView + eventually(t, settleTimeout, "master adopts both clients", func() (bool, string) { + var ok bool + source, ok = master.inboundOnPort(port) + return ok && len(source.emails()) == 2, fmt.Sprint(source.emails()) + }) + var page struct { + Items []struct { + ID int `json:"id"` + Email string `json:"email"` + } + } + if err := json.Unmarshal(master.call(http.MethodGet, fmt.Sprintf("/panel/api/clients/detachCandidates?inboundId=%d", source.Id), nil), &page); err != nil { + t.Fatal(err) + } + var keep int + for _, item := range page.Items { + if item.Email == "keep-me" { + keep = item.ID + } + } + if keep == 0 || len(page.Items) != 2 { + t.Fatalf("source candidates: %+v", page) + } + var frozen struct{ ScopeToken string } + if err := json.Unmarshal(master.call(http.MethodPost, "/panel/api/clients/detachCandidates/freeze", map[string]any{"inboundId": source.Id}), &frozen); err != nil { + t.Fatal(err) + } + node.stop() + id := uuid.NewString() + master.call(http.MethodPost, "/panel/api/clients/bulkDetach", map[string]any{ + "inboundIds": []int{source.Id}, "requestId": id, + "selection": map[string]any{"mode": "allMatching", "scopeToken": frozen.ScopeToken, "excludedClientIds": []int{keep}}, + }) + eventually(t, 10*time.Second, "scoped detachment commits and queues reconciliation", func() (bool, string) { + var status struct { + Running bool + Error string + Result struct { + Detached, Skipped, Errors int + NodePending bool + } + } + raw := master.call(http.MethodGet, "/panel/api/clients/bulkDetach/"+id, nil) + if err := json.Unmarshal(raw, &status); err != nil { + t.Fatal(err) + } + return !status.Running && status.Error == "" && status.Result.Detached == 1 && + status.Result.Skipped == 0 && status.Result.Errors == 0 && status.Result.NodePending, string(raw) + }) + node.start() + eventually(t, 90*time.Second, "node applies detach and keeps the excluded client", func() (bool, string) { + ib, ok := node.inboundOnPort(port) + return ok && len(ib.emails()) == 1 && ib.client("keep-me") != nil, fmt.Sprint(ib.emails()) + }) +} diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go index 2fd268a56..d89d48290 100644 --- a/internal/web/controller/client.go +++ b/internal/web/controller/client.go @@ -56,6 +56,8 @@ func (a *ClientController) initRouter(g *gin.RouterGroup) { g.GET("/list/paged", a.listPaged) g.GET("/userSuggestions", a.userSuggestions) g.GET("/attachCandidates", a.attachCandidates) + g.GET("/detachCandidates", a.detachCandidates) + g.POST("/detachCandidates/freeze", a.freezeDetachCandidates) g.GET("/get", a.get) g.GET("/get/:email", a.get) g.GET("/get/subId/:subId", a.getBySubId) @@ -93,6 +95,7 @@ func (a *ClientController) initRouter(g *gin.RouterGroup) { g.POST("/bulkAttach", a.bulkAttach) g.GET("/bulkAttach/:id", a.attachStatus) g.POST("/bulkDetach", a.bulkDetach) + g.GET("/bulkDetach/:id", a.detachStatus) g.POST("/bulkResetTraffic", a.bulkResetTraffic) g.POST("/resetTraffic/:email", a.resetTrafficByEmail) g.POST("/updateTraffic/:email", a.updateTrafficByEmail) @@ -521,8 +524,10 @@ func (a *ClientController) bulkAttach(c *gin.Context) { } type bulkDetachRequest struct { - Emails []string `json:"emails"` - InboundIds []int `json:"inboundIds"` + Emails []string `json:"emails"` + InboundIds []int `json:"inboundIds"` + Selection *service.DetachSelection `json:"selection,omitempty"` + RequestID string `json:"requestId,omitempty"` } func (a *ClientController) bulkDetach(c *gin.Context) { @@ -531,6 +536,10 @@ func (a *ClientController) bulkDetach(c *gin.Context) { jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) return } + if req.Selection != nil { + a.beginBulkDetach(c, req) + return + } clientSvc := a.clientService.TrackNodeApplies() result, needRestart, err := clientSvc.BulkDetach(&a.inboundService, req.Emails, req.InboundIds) if err != nil { diff --git a/internal/web/controller/client_detach_jobs.go b/internal/web/controller/client_detach_jobs.go new file mode 100644 index 000000000..1b56b70a4 --- /dev/null +++ b/internal/web/controller/client_detach_jobs.go @@ -0,0 +1,253 @@ +package controller + +import ( + "context" + "crypto/sha256" + "encoding/json" + "errors" + "sync" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "github.com/mhsanaei/3x-ui/v3/internal/database" + "github.com/mhsanaei/3x-ui/v3/internal/util/common" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +const detachHistoryTTL = 15 * time.Minute + +type savedDetachScope struct { + scope *service.DetachScope + issued time.Time +} + +type detachScopeStore struct { + mu sync.Mutex + entries map[string]savedDetachScope +} + +var ( + detachScopes detachScopeStore + freezeDetachMu sync.Mutex +) + +func (s *detachScopeStore) save(scope *service.DetachScope) string { + s.mu.Lock() + defer s.mu.Unlock() + if s.entries == nil { + s.entries = make(map[string]savedDetachScope) + } + now := time.Now() + var oldest string + for token, entry := range s.entries { + if now.Sub(entry.issued) >= detachHistoryTTL { + delete(s.entries, token) + } else if oldest == "" || entry.issued.Before(s.entries[oldest].issued) { + oldest = token + } + } + if len(s.entries) >= 8 { + delete(s.entries, oldest) + } + token := uuid.NewString() + s.entries[token] = savedDetachScope{scope: scope, issued: now} + return token +} + +func (s *detachScopeStore) get(token string) *service.DetachScope { + s.mu.Lock() + defer s.mu.Unlock() + entry, ok := s.entries[token] + if !ok || time.Since(entry.issued) >= detachHistoryTTL { + delete(s.entries, token) + return nil + } + return entry.scope +} + +type DetachJobStatus struct { + Running bool `json:"running"` + Processed int `json:"processed"` + Total int `json:"total"` + Result *service.DetachSelectionResult `json:"result,omitempty"` + Error string `json:"error,omitempty"` +} + +type detachJob struct { + status DetachJobStatus + request [sha256.Size]byte + generation uint64 + ended time.Time +} + +type detachJobStore struct { + mu sync.Mutex + running bool + entries map[string]detachJob +} + +var detachJobs detachJobStore + +func (s *detachJobStore) start(id string, inboundID int, selection service.DetachSelection, run func(*service.DetachPlan, func(int)) (*service.DetachSelectionResult, error)) error { + parsed, err := uuid.Parse(id) + if err != nil || parsed == uuid.Nil || id != parsed.String() || + len(selection.ClientIDs) > service.DetachSelectionLimit || len(selection.ExcludedClientIDs) > service.DetachSelectionLimit { + return errors.New("invalid client detachment request") + } + encoded, err := json.Marshal(struct { + InboundID int + Selection service.DetachSelection + }{inboundID, selection}) + if err != nil { + return err + } + fingerprint := sha256.Sum256(encoded) + generation := database.ConnectionGeneration() + s.mu.Lock() + defer s.mu.Unlock() + if s.entries == nil { + s.entries = make(map[string]detachJob) + } + var oldest string + for key, entry := range s.entries { + if entry.status.Running { + continue + } + if time.Since(entry.ended) >= detachHistoryTTL || entry.generation != generation { + delete(s.entries, key) + } else if oldest == "" || entry.ended.Before(s.entries[oldest].ended) { + oldest = key + } + } + if entry, ok := s.entries[id]; ok { + if entry.request != fingerprint || entry.generation != generation { + return errors.New("detachment request ID is already in use") + } + return nil + } + if s.running { + return errors.New("another client detachment is running") + } + plan, err := service.NewDetachPlan(inboundID, selection, detachScopes.get(selection.ScopeToken)) + if err != nil { + return err + } + if len(s.entries) >= 32 { + delete(s.entries, oldest) + } + s.entries[id] = detachJob{request: fingerprint, generation: generation, status: DetachJobStatus{ + Running: true, Total: plan.Total(), + }} + s.running = true + common.GoRecover("client-detachment", func() { + var result *service.DetachSelectionResult + failure := "client detachment interrupted" + defer func() { + s.mu.Lock() + defer s.mu.Unlock() + entry := s.entries[id] + entry.ended = time.Now() + entry.status.Running, entry.status.Result, entry.status.Error = false, result, failure + s.entries[id] = entry + s.running = false + }() + var err error + result, err = run(plan, func(n int) { + s.mu.Lock() + defer s.mu.Unlock() + entry := s.entries[id] + entry.status.Processed = n + s.entries[id] = entry + }) + if err != nil { + failure = err.Error() + } else { + failure = "" + } + }) + return nil +} + +func (s *detachJobStore) get(id string) (DetachJobStatus, bool) { + s.mu.Lock() + defer s.mu.Unlock() + entry, ok := s.entries[id] + if !ok || entry.generation != database.ConnectionGeneration() || + (!entry.status.Running && time.Since(entry.ended) >= detachHistoryTTL) { + return DetachJobStatus{}, false + } + return entry.status, true +} + +func (a *ClientController) detachCandidates(c *gin.Context) { + c.Header("Cache-Control", "no-store") + var params service.DetachCandidateParams + if err := c.ShouldBindQuery(¶ms); err != nil { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + return + } + var scope *service.DetachScope + if token := c.Query("scopeToken"); token != "" { + scope = detachScopes.get(token) + if scope == nil { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("client detachment selection expired")) + return + } + } + page, err := a.clientService.ListDetachCandidates(c.Request.Context(), params, scope) + jsonObj(c, page, err) +} + +func (a *ClientController) freezeDetachCandidates(c *gin.Context) { + var req struct { + InboundID int `json:"inboundId"` + } + if err := c.ShouldBindJSON(&req); err != nil { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + return + } + if !freezeDetachMu.TryLock() { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("another detachment selection is being prepared")) + return + } + defer freezeDetachMu.Unlock() + scope, total, err := a.clientService.FreezeDetachScope(c.Request.Context(), req.InboundID) + if err != nil { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + return + } + jsonObj(c, service.DetachScopeSummary{ScopeToken: detachScopes.save(scope), Total: total}, nil) +} + +func (a *ClientController) beginBulkDetach(c *gin.Context, req bulkDetachRequest) { + if len(req.Emails) != 0 || len(req.InboundIds) != 1 { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("a scoped detachment requires one inbound and no email list")) + return + } + err := detachJobs.start(req.RequestID, req.InboundIds[0], *req.Selection, func(plan *service.DetachPlan, progress func(int)) (*service.DetachSelectionResult, error) { + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + result, err := a.clientService.ApplyDetachPlan(ctx, plan, progress) + if err == nil || (result != nil && result.Detached > 0) { + notifyClientsChanged() + } + return result, err + }) + if err != nil { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err) + return + } + jsonObj(c, gin.H{"jobId": req.RequestID}, nil) +} + +func (a *ClientController) detachStatus(c *gin.Context) { + c.Header("Cache-Control", "no-store") + status, ok := detachJobs.get(c.Param("id")) + if !ok { + jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("client detachment status unavailable")) + return + } + jsonObj(c, status, nil) +} diff --git a/internal/web/controller/client_detach_jobs_test.go b/internal/web/controller/client_detach_jobs_test.go new file mode 100644 index 000000000..3de3e5547 --- /dev/null +++ b/internal/web/controller/client_detach_jobs_test.go @@ -0,0 +1,140 @@ +package controller + +import ( + "bytes" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + + "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/util/crypto" + "github.com/mhsanaei/3x-ui/v3/internal/web/locale" + "github.com/mhsanaei/3x-ui/v3/internal/web/service" +) + +func TestScopedDetachAPIAndIdempotency(t *testing.T) { + cleanup, err := testpg.IsolatePackage("scoped_detach_api") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + engine, auth := newAPIAuthTestEngine(t) + clients := engine.Group("/panel/api/clients", auth.checkAPIAuth, auth.enforceTokenScope) + clients.Use(func(c *gin.Context) { + c.Set("I18n", func(_ locale.I18nType, key string, _ ...string) string { return key }) + c.Next() + }) + controller := &ClientController{} + clients.GET("/detachCandidates", controller.detachCandidates) + clients.POST("/detachCandidates/freeze", controller.freezeDetachCandidates) + clients.POST("/bulkDetach", controller.bulkDetach) + clients.GET("/bulkDetach/:id", controller.detachStatus) + db := database.GetDB() + for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeNodeSync} { + if err := db.Create(&model.ApiToken{Name: scope, Token: crypto.HashTokenSHA256(scope), Scope: scope, Enabled: true}).Error; err != nil { + t.Fatal(err) + } + } + inbound := model.Inbound{Tag: "detach-api", Protocol: model.VLESS, Settings: `{"clients":[{"email":"detach-api@test","enable":false}]}`} + record := model.ClientRecord{Email: "detach-api@test"} + if err := db.Create(&inbound).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&record).Error; err != nil { + t.Fatal(err) + } + if err := db.Create(&model.ClientInbound{ClientId: record.Id, InboundId: inbound.Id}).Error; err != nil { + t.Fatal(err) + } + request := func(method, path, scope string, body any) *httptest.ResponseRecorder { + t.Helper() + raw, err := json.Marshal(body) + if err != nil { + t.Fatal(err) + } + req := httptest.NewRequest(method, "/panel/api/clients"+path, bytes.NewReader(raw)) + req.Header.Set("Authorization", "Bearer "+scope) + req.Header.Set("Content-Type", "application/json") + out := httptest.NewRecorder() + engine.ServeHTTP(out, req) + return out + } + type envelope struct { + Success bool `json:"success"` + Obj json.RawMessage `json:"obj"` + Msg string `json:"msg"` + } + admin := model.ApiScopeAdmin + candidatePath := fmt.Sprintf("/detachCandidates?inboundId=%d", inbound.Id) + if response := request(http.MethodGet, candidatePath, model.ApiScopeNodeSync, nil); response.Code != http.StatusForbidden { + t.Fatalf("node-sync got %d: %s", response.Code, response.Body) + } + read := func(out *httptest.ResponseRecorder) envelope { + t.Helper() + var res envelope + if err := json.Unmarshal(out.Body.Bytes(), &res); err != nil { + t.Fatalf("read response: %v (%s)", err, out.Body) + } + return res + } + page := read(request(http.MethodGet, candidatePath, admin, nil)) + var candidates service.DetachCandidatePage + if err := json.Unmarshal(page.Obj, &candidates); err != nil || !page.Success || len(candidates.Items) != 1 || + candidates.Items[0].ID != record.Id || candidates.Attached != 1 { + t.Fatalf("candidate response = %+v (%s), error %v", candidates, page.Msg, err) + } + freeze := read(request(http.MethodPost, "/detachCandidates/freeze", admin, gin.H{"inboundId": inbound.Id})) + var scoped service.DetachScopeSummary + if err := json.Unmarshal(freeze.Obj, &scoped); err != nil || !freeze.Success || scoped.Total != 1 || scoped.ScopeToken == "" { + t.Fatalf("freeze response = %+v (%s), error %v", scoped, freeze.Msg, err) + } + jobID := uuid.NewString() + body := bulkDetachRequest{ + InboundIds: []int{inbound.Id}, + RequestID: jobID, + Selection: &service.DetachSelection{Mode: "allMatching", ScopeToken: scoped.ScopeToken}, + } + start := func(req bulkDetachRequest) envelope { + return read(request(http.MethodPost, "/bulkDetach", admin, req)) + } + if res := start(body); !res.Success || !bytes.Contains(res.Obj, []byte(jobID)) { + t.Fatalf("job submission: %+v", res) + } + if res := start(body); !res.Success || !bytes.Contains(res.Obj, []byte(jobID)) { + t.Fatalf("duplicate submission: %+v", res) + } + deadline := time.Now().Add(5 * time.Second) + for { + res := read(request(http.MethodGet, "/bulkDetach/"+jobID, admin, nil)) + var status DetachJobStatus + if err := json.Unmarshal(res.Obj, &status); err != nil || !res.Success { + t.Fatalf("job status: %+v, error %v", res, err) + } + if !status.Running { + if status.Error != "" || status.Processed != 1 || status.Result == nil || status.Result.Detached != 1 { + t.Fatalf("unexpected terminal status %+v", status) + } + break + } + if time.Now().After(deadline) { + t.Fatal("detachment job did not finish") + } + time.Sleep(10 * time.Millisecond) + } + if res := start(body); !res.Success || !bytes.Contains(res.Obj, []byte(jobID)) { + t.Fatalf("identical retry did not return the same job: %+v", res) + } + changed := body + changed.Selection = &service.DetachSelection{Mode: "explicit", ClientIDs: []int{record.Id}} + if res := start(changed); res.Success { + t.Fatal("changed payload reused a request ID") + } +} diff --git a/internal/web/service/client_detach_selection.go b/internal/web/service/client_detach_selection.go new file mode 100644 index 000000000..1850b5690 --- /dev/null +++ b/internal/web/service/client_detach_selection.go @@ -0,0 +1,352 @@ +package service + +import ( + "cmp" + "context" + "encoding/json" + "errors" + "fmt" + "maps" + "slices" + "strings" + + "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/xray" +) + +const ( + detachCandidatePageSize = 100 + DetachSelectionLimit = 100_000 +) + +type DetachCandidateParams struct { + InboundID int `form:"inboundId"` + Page int `form:"page"` + Search string `form:"search"` +} + +type DetachCandidate struct { + ID int `json:"id"` + Email string `json:"email"` + Comment string `json:"comment"` + Enable bool `json:"enable"` + InScope bool `json:"inScope"` + Incarnation string `json:"-"` +} + +type DetachCandidatePage struct { + Items []DetachCandidate `json:"items"` + Total int64 `json:"total"` + Attached int64 `json:"attached"` +} + +type DetachScopeSummary struct { + ScopeToken string `json:"scopeToken"` + Total int `json:"total"` +} + +type DetachSelection struct { + Mode string `json:"mode"` + ClientIDs []int `json:"clientIds"` + ExcludedClientIDs []int `json:"excludedClientIds"` + ScopeToken string `json:"scopeToken"` +} + +type DetachSelectionResult struct { + Detached int `json:"detached"` + Skipped int `json:"skipped"` + Errors int `json:"errors"` + NodePending bool `json:"nodePending,omitempty"` +} + +type detachMembership struct { + ID int + Incarnation string +} + +type DetachScope struct { + inboundID int + generation uint64 + members []detachMembership +} + +func detachCandidates(db *gorm.DB, id int, search string) *gorm.DB { + return filteredAttachCandidates( + db.Table("client_inbounds AS ci").Joins("JOIN clients AS c ON c.id = ci.client_id"). + Where("ci.inbound_id = ? AND c.email <> ''", id), + id, search, "", + ) +} + +func (s *DetachScope) matches(id int) bool { + return s != nil && s.inboundID == id && s.generation == database.ConnectionGeneration() +} + +func (s *DetachScope) has(id int, incarnation string) bool { + n, found := slices.BinarySearchFunc(s.members, id, func(m detachMembership, id int) int { + return cmp.Compare(m.ID, id) + }) + return found && s.members[n].Incarnation == incarnation +} + +func (s *ClientService) ListDetachCandidates(ctx context.Context, p DetachCandidateParams, scope *DetachScope) (*DetachCandidatePage, error) { + if p.InboundID <= 0 || p.Page < 0 || p.Page > 1_000_000 || len(p.Search) > 256 { + return nil, errors.New("invalid client detachment page") + } + if scope != nil && !scope.matches(p.InboundID) { + return nil, errors.New("client detachment selection expired") + } + db := database.GetDB().WithContext(ctx) + if _, err := attachScope(db, p.InboundID, nil); err != nil { + return nil, err + } + resp := &DetachCandidatePage{Items: []DetachCandidate{}} + q := detachCandidates(db, p.InboundID, p.Search) + if err := q.Count(&resp.Total).Error; err != nil { + return nil, err + } + resp.Attached = resp.Total + if strings.TrimSpace(p.Search) != "" { + if err := detachCandidates(db, p.InboundID, "").Count(&resp.Attached).Error; err != nil { + return nil, err + } + } + if err := q.Select("c.id, c.email, c.comment, c.enable, ci.incarnation"). + Order("c.id").Offset(max(0, p.Page-1) * detachCandidatePageSize). + Limit(detachCandidatePageSize).Scan(&resp.Items).Error; err != nil { + return nil, err + } + for i := range resp.Items { + row := &resp.Items[i] + row.InScope = scope != nil && scope.has(row.ID, row.Incarnation) + } + return resp, nil +} + +func (s *ClientService) FreezeDetachScope(ctx context.Context, inboundID int) (*DetachScope, int, error) { + if inboundID <= 0 { + return nil, 0, errors.New("invalid source inbound") + } + generation := database.ConnectionGeneration() + db := database.GetDB().WithContext(ctx) + if _, err := attachScope(db, inboundID, nil); err != nil { + return nil, 0, err + } + var members []detachMembership + err := detachCandidates(db, inboundID, "").Select("c.id, ci.incarnation"). + Order("c.id").Limit(DetachSelectionLimit + 1).Scan(&members).Error + if err != nil { + return nil, 0, err + } + if len(members) == 0 || len(members) > DetachSelectionLimit { + return nil, 0, errors.New("no attached clients or detachment selection exceeds the limit") + } + return &DetachScope{inboundID: inboundID, generation: generation, members: members}, len(members), nil +} + +type DetachPlan struct { + inboundID int + generation uint64 + ids []int + scope *DetachScope +} + +func NewDetachPlan(inboundID int, selection DetachSelection, scope *DetachScope) (*DetachPlan, error) { + if inboundID <= 0 || len(selection.ClientIDs) > DetachSelectionLimit || len(selection.ExcludedClientIDs) > DetachSelectionLimit { + return nil, errors.New("invalid client detachment selection") + } + plan := &DetachPlan{inboundID: inboundID, generation: database.ConnectionGeneration()} + switch selection.Mode { + case "explicit": + if len(selection.ExcludedClientIDs) != 0 || selection.ScopeToken != "" { + return nil, errors.New("invalid explicit client detachment selection") + } + plan.ids = uniqueInts(selection.ClientIDs) + for _, id := range plan.ids { + if id <= 0 { + return nil, errors.New("invalid client ID") + } + } + case "allMatching": + if len(selection.ClientIDs) != 0 || !scope.matches(inboundID) { + return nil, errors.New("client detachment selection expired or belongs to another inbound") + } + plan.scope = scope + excluded := make(map[int]struct{}, len(selection.ExcludedClientIDs)) + for _, id := range selection.ExcludedClientIDs { + excluded[id] = struct{}{} + } + for _, m := range scope.members { + if _, skip := excluded[m.ID]; skip { + delete(excluded, m.ID) + } else { + plan.ids = append(plan.ids, m.ID) + } + } + if len(excluded) != 0 { + return nil, errors.New("excluded client is outside the frozen selection") + } + default: + return nil, errors.New("invalid client detachment selection mode") + } + if len(plan.ids) == 0 { + return nil, errors.New("no clients selected for detachment") + } + return plan, nil +} + +func (p *DetachPlan) Total() int { return len(p.ids) } + +// ApplyDetachPlan updates the source settings once, even for a large selection. +// SQL lookup/delta batches are bounded and commit with the same membership check. +func (s *ClientService) ApplyDetachPlan(ctx context.Context, p *DetachPlan, progress func(int)) (*DetachSelectionResult, error) { + defer lockInbound(p.inboundID).Unlock() + result := &DetachSelectionResult{} + var previous, inbound model.Inbound + var detachedEmails []string + err := runSerializedTx(func(tx *gorm.DB) error { + if p.generation != database.ConnectionGeneration() || (p.scope != nil && !p.scope.matches(p.inboundID)) { + return errors.New("client detachment selection expired") + } + tx = tx.WithContext(context.WithValue(ctx, serializedTxContextKey{}, serializedTxOf(tx))) + if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).First(&inbound, p.inboundID).Error; err != nil { + return err + } + if _, err := attachScope(tx, p.inboundID, nil); err != nil { + return err + } + emails := make(map[string]struct{}) + processed := 0 + for _, ids := range chunkInts(p.ids, sqlInChunk) { + var rows []DetachCandidate + err := detachCandidates(tx, p.inboundID, "").Where("c.id IN ?", ids). + Select("c.id, c.email, ci.incarnation").Scan(&rows).Error + if err != nil { + return err + } + for _, row := range rows { + if p.scope == nil || p.scope.has(row.ID, row.Incarnation) { + emails[row.Email] = struct{}{} + } + } + processed += len(ids) + if progress != nil { + progress(processed) + } + } + result.Detached, result.Skipped = len(emails), p.Total()-len(emails) + if len(emails) == 0 { + return nil + } + settings, err := detachClientSettings(inbound.Settings, emails) + if err != nil { + return err + } + previous = inbound + // The running core can have users that are missing or disabled in settings. + detachedEmails = slices.Collect(maps.Keys(emails)) + if settings != inbound.Settings { + if err := tx.Model(&inbound).Update("settings", settings).Error; err != nil { + return err + } + } + if err := s.ApplyInboundClientDelta(tx, inbound.Id, nil, detachedEmails); err != nil { + return err + } + if inbound.NodeID != nil { + result.NodePending = true + return (&NodeService{}).MarkNodeDirtyTx(tx, *inbound.NodeID) + } + return nil + }) + if err != nil { + return &DetachSelectionResult{Skipped: result.Skipped, Errors: p.Total() - result.Skipped}, err + } + if result.Detached > 0 { + InvalidateSubData() + } + if inbound.NodeID == nil && inbound.Enable && len(detachedEmails) > 0 { + if err := applyLocalScopedDetach(ctx, &previous, &inbound, detachedEmails); err != nil { + (&XrayService{}).SetToNeedReconcile() + return result, fmt.Errorf("memberships detached, but the local runtime has not applied the change: %w", err) + } + } + return result, nil +} + +// Apply runtime changes after commit so the traffic writer stays free during RPC. +func applyLocalScopedDetach(ctx context.Context, previous, inbound *model.Inbound, emails []string) error { + inbounds := &InboundService{} + core := &XrayService{} + rt, err := inbounds.runtimeFor(inbound) + if servedOutsideXray(inbound.Protocol) { + if err != nil { + return err + } + next, err := inbounds.buildInboundForLocalRuntime(database.GetDB(), inbound) + if err != nil { + return err + } + return rt.UpdateInbound(ctx, previous, next) + } + + dropSessions := removalLeavesXraySessions(inbound) && restartAfterClientRemoval() + if err == nil && len(emails) <= nodeBulkPushThreshold && inbound.Protocol != model.WireGuard { + for _, email := range emails { + err = rt.RemoveUser(ctx, inbound, email) + if err != nil && !xray.IsMissingUserErr(err) { + break + } + err = nil + } + if err == nil && !dropSessions { + return nil + } + } + if !core.IsXrayRunning() { + return nil + } + // Large selections and failed live removals reconcile before the job finishes. + err = core.restartXrayFrom(false, XrayOriginConfigChange, "", dropSessions) + if err != nil && dropSessions { + pendingXraySessionDrop.Store(true) + } + return err +} + +func detachClientSettings(raw string, emails map[string]struct{}) (string, error) { + var settings map[string]json.RawMessage + if err := json.Unmarshal([]byte(raw), &settings); err != nil { + return "", err + } + var clients []json.RawMessage + if err := json.Unmarshal(settings["clients"], &clients); err != nil { + return "", fmt.Errorf("read inbound clients: %w", err) + } + kept := make([]json.RawMessage, 0, len(clients)) + for _, client := range clients { + var identity struct { + Email string + } + err := json.Unmarshal(client, &identity) + email := strings.TrimSpace(identity.Email) + if _, remove := emails[email]; err == nil && remove { + continue + } + kept = append(kept, client) + } + if len(kept) == len(clients) { + return raw, nil + } + values, err := json.Marshal(kept) + if err != nil { + return "", err + } + settings["clients"] = values + out, err := json.Marshal(settings) + return string(out), err +} diff --git a/internal/web/service/client_detach_selection_test.go b/internal/web/service/client_detach_selection_test.go new file mode 100644 index 000000000..ba8adc088 --- /dev/null +++ b/internal/web/service/client_detach_selection_test.go @@ -0,0 +1,290 @@ +package service + +import ( + "context" + "fmt" + "slices" + "testing" + + "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/xray" +) + +type scopedDetachRuntimeProbe struct { + fakeNodeRuntime + removed []string + updated *model.Inbound +} + +func (p *scopedDetachRuntimeProbe) RemoveUser(_ context.Context, _ *model.Inbound, email string) error { + p.removed = append(p.removed, email) + return nil +} + +func (p *scopedDetachRuntimeProbe) UpdateInbound(_ context.Context, _, next *model.Inbound) error { + p.updated = next + return nil +} + +func TestScopedDetachAppliesLocalRuntimeBeforeReturning(t *testing.T) { + for _, tc := range []struct { + name string + protocol model.Protocol + staleJSON bool + omit bool + }{ + {name: "vless", protocol: model.VLESS}, + {name: "tuic", protocol: model.TUIC}, + {name: "normalized-only vless", protocol: model.VLESS, staleJSON: true, omit: true}, + {name: "stale-disabled vless", protocol: model.VLESS, staleJSON: true}, + {name: "normalized-only tuic", protocol: model.TUIC, staleJSON: true, omit: true}, + } { + t.Run(tc.name, func(t *testing.T) { + cleanup, err := testpg.IsolatePackage("scoped_detach_runtime") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + setupBulkDB(t) + probe := &scopedDetachRuntimeProbe{} + useTestRuntimeManager(t).SetLocalRuntimeOverride(probe) + clients := []model.Client{ + {Email: "detach-live@test", ID: "c10b9d71-71ac-42b5-bc9d-a2697d9dbfa1", Enable: true}, + {Email: "keep-live@test", ID: "c10b9d71-71ac-42b5-bc9d-a2697d9dbfa2", Enable: true}, + } + inbound := mkInbound(t, 24004, tc.protocol, clientsSettings(t, clients)) + svc := &ClientService{} + if err := svc.SyncInbound(nil, inbound.Id, clients); err != nil { + t.Fatal(err) + } + for _, c := range clients { + traffic := xray.ClientTraffic{Email: c.Email, InboundId: inbound.Id, Enable: true} + if err := database.GetDB().Create(&traffic).Error; err != nil { + t.Fatal(err) + } + } + if tc.staleJSON { + stored := slices.Clone(clients) + if tc.omit { + stored = stored[1:] + } else { + stored[0].Enable = false + } + err := database.GetDB().Model(inbound).Update("settings", clientsSettings(t, stored)).Error + if err != nil { + t.Fatal(err) + } + } + rec, err := svc.GetRecordByEmail(nil, clients[0].Email) + if err != nil { + t.Fatal(err) + } + plan, err := NewDetachPlan(inbound.Id, DetachSelection{Mode: "explicit", ClientIDs: []int{rec.Id}}, nil) + if err != nil { + t.Fatal(err) + } + if result, err := svc.ApplyDetachPlan(t.Context(), plan, nil); err != nil || result.Detached != 1 { + t.Fatalf("detach = %+v, err %v", result, err) + } + if tc.protocol == model.VLESS { + if !slices.Equal(probe.removed, []string{clients[0].Email}) { + t.Fatalf("live core removals = %v", probe.removed) + } + } else { + if probe.updated == nil { + t.Fatal("local TUIC listener still has its old config") + } + remaining, err := (&InboundService{}).GetClients(probe.updated) + if err != nil || !slices.Equal(emailsOf(remaining), []string{clients[1].Email}) { + t.Fatalf("runtime clients = %v, err %v", emailsOf(remaining), err) + } + } + }) + } +} + +func TestScopedDetachMembershipAndPagination(t *testing.T) { + cleanup, err := testpg.IsolatePackage("scoped_detach") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + setupBulkDB(t) + db := database.GetDB() + svc := &ClientService{} + inboundSvc := &InboundService{} + ctx := t.Context() + clients := make([]model.Client, 125) + for i := range clients { + clients[i] = model.Client{Email: fmt.Sprintf("detach-%03d@test", i), ID: fmt.Sprintf("uuid-%d", i), Comment: "client", SubID: fmt.Sprintf("sub-%d", i)} + } + clients[123].Comment = "Special_% Name" + source := mkInbound(t, 24001, model.VLESS, clientsSettings(t, clients)) + other := mkInbound(t, 24002, model.VLESS, clientsSettings(t, clients[:1])) + if err := svc.SyncInbound(nil, source.Id, clients); err != nil { + t.Fatal(err) + } + if err := svc.SyncInbound(nil, other.Id, clients[:1]); err != nil { + t.Fatal(err) + } + traffic := xray.ClientTraffic{Email: clients[0].Email, InboundId: other.Id, Up: 42, Down: 19, Total: 1000, ExpiryTime: 9999999999999} + if err := db.Create(&traffic).Error; err != nil { + t.Fatal(err) + } + + p := DetachCandidateParams{InboundID: source.Id, Page: 1} + first, err := svc.ListDetachCandidates(ctx, p, nil) + if err != nil || len(first.Items) != 100 || first.Total != 125 || first.Attached != 125 { + t.Fatalf("first page: %+v, error %v", first, err) + } + p.Page = 2 + second, err := svc.ListDetachCandidates(ctx, p, nil) + if err != nil || len(second.Items) != 25 || first.Items[99].ID >= second.Items[0].ID { + t.Fatalf("second page: %+v, error %v", second, err) + } + search, err := svc.ListDetachCandidates(ctx, DetachCandidateParams{InboundID: source.Id, Search: "special_%"}, nil) + if err != nil || search.Total != 1 || search.Attached != 125 || len(search.Items) != 1 || search.Items[0].Email != clients[123].Email { + t.Fatalf("literal comment search: %+v, error %v", search, err) + } + scope, total, err := svc.FreezeDetachScope(ctx, source.Id) + if err != nil || total != 125 { + t.Fatalf("freeze count %d, error %v", total, err) + } + excluded := second.Items[0] + selection := DetachSelection{Mode: "allMatching", ScopeToken: "test-token", ExcludedClientIDs: []int{excluded.ID, excluded.ID}} + if _, err := NewDetachPlan(other.Id, selection, scope); err == nil { + t.Fatal("a frozen scope was accepted for another inbound") + } + if _, err := NewDetachPlan(source.Id, DetachSelection{Mode: "explicit"}, nil); err == nil { + t.Fatal("an empty explicit selection was accepted") + } + + // One old member is removed, one is reattached, and a new one is added. + if res, _, err := svc.BulkDetach(inboundSvc, []string{clients[1].Email, clients[1].Email}, []int{source.Id}); err != nil || + len(res.Detached) != 1 || len(res.Errors) != 0 { + t.Fatalf("legacy duplicate-email detach = %+v, error %v", res, err) + } + relinked := &model.ClientInbound{InboundId: source.Id, ClientId: first.Items[2].ID} + var oldLink model.ClientInbound + if err := db.Where(relinked).First(&oldLink).Error; err != nil { + t.Fatal(err) + } + if err := db.Where(relinked).Delete(&model.ClientInbound{}).Error; err != nil { + t.Fatal(err) + } + newClient := model.Client{Email: "late@test", ID: "late-id", SubID: "late"} + if err := db.Delete(&model.ClientRecord{}, first.Items[3].ID).Error; err != nil { + t.Fatal(err) + } + current := append(slices.Clone(clients[:1]), clients[2]) + current = append(current, clients[4:]...) + current = append(current, newClient) + if err := db.Model(source).Update("settings", clientsSettings(t, current)).Error; err != nil { + t.Fatal(err) + } + if err := svc.SyncInbound(nil, source.Id, current); err != nil { + t.Fatal(err) + } + // Force the same millisecond so a timestamp comparison cannot distinguish the reattach. + if err := db.Model(&model.ClientInbound{}).Where(relinked).Update("created_at", oldLink.CreatedAt).Error; err != nil { + t.Fatal(err) + } + replacement, err := svc.ListDetachCandidates(ctx, DetachCandidateParams{InboundID: source.Id, Search: clients[2].Email}, scope) + if err != nil || len(replacement.Items) != 1 || replacement.Items[0].InScope { + t.Fatalf("reattached membership shown as selected: %+v, error %v", replacement, err) + } + late, err := svc.ListDetachCandidates(ctx, DetachCandidateParams{InboundID: source.Id, Search: "late@test"}, scope) + if err != nil || len(late.Items) != 1 || late.Items[0].InScope { + t.Fatalf("late attachment shown as selected: %+v, error %v", late, err) + } + plan, err := NewDetachPlan(source.Id, selection, scope) + if err != nil { + t.Fatal(err) + } + var processed int + result, err := svc.ApplyDetachPlan(ctx, plan, func(n int) { processed = n }) + if err != nil || result.Detached != 121 || result.Skipped != 3 || result.Errors != 0 || processed != 124 { + t.Fatalf("scoped apply: %+v, processed %d, error %v", result, processed, err) + } + remaining, err := svc.ListForInbound(nil, source.Id) + want := []string{excluded.Email, clients[2].Email, newClient.Email} + slices.Sort(want) + if err != nil || !slices.Equal(sortedEmails(remaining), want) { + t.Fatalf("source memberships = %v, want %v, err %v", sortedEmails(remaining), want, err) + } + stored, err := inboundSvc.GetInbound(source.Id) + if err != nil { + t.Fatal(err) + } + settingsClients, err := inboundSvc.GetClients(stored) + if err != nil || !slices.Equal(sortedEmails(settingsClients), want) { + t.Fatalf("source settings clients = %v, want %v, err %v", sortedEmails(settingsClients), want, err) + } + otherClients, err := svc.ListForInbound(nil, other.Id) + if err != nil || len(otherClients) != 1 || otherClients[0].Email != clients[0].Email { + t.Fatalf("other inbound changed: %+v, error %v", otherClients, err) + } + if _, err := svc.GetRecordByEmail(nil, clients[0].Email); err != nil { + t.Fatal(err) + } + var gotTraffic xray.ClientTraffic + if err := db.First(&gotTraffic, traffic.Id).Error; err != nil || gotTraffic.Up != traffic.Up || + gotTraffic.Down != traffic.Down || gotTraffic.Total != traffic.Total || gotTraffic.ExpiryTime != traffic.ExpiryTime { + t.Fatalf("traffic changed: %+v, error %v", gotTraffic, err) + } +} + +func TestScopedDetachQueuesOfflineNodeAndRollsBackInvalidSettings(t *testing.T) { + cleanup, err := testpg.IsolatePackage("scoped_detach_node") + if err != nil { + t.Fatal(err) + } + t.Cleanup(cleanup) + setupBulkDB(t) + db := database.GetDB() + svc := &ClientService{} + client := model.Client{Email: "node-detach@test", ID: "client-id", SubID: "sub"} + source := mkInbound(t, 24003, model.VLESS, clientsSettings(t, []model.Client{client})) + node := model.Node{Name: "detached-offline-node", Status: "offline"} + if err := db.Create(&node).Error; err != nil { + t.Fatal(err) + } + if err := db.Model(source).Update("node_id", node.Id).Error; err != nil { + t.Fatal(err) + } + if err := svc.SyncInbound(nil, source.Id, []model.Client{client}); err != nil { + t.Fatal(err) + } + record, err := svc.GetRecordByEmail(nil, client.Email) + if err != nil { + t.Fatal(err) + } + plan, err := NewDetachPlan(source.Id, DetachSelection{Mode: "explicit", ClientIDs: []int{record.Id, record.Id}}, nil) + if err != nil { + t.Fatal(err) + } + validSettings := source.Settings + if err := db.Model(source).Update("settings", "{}").Error; err != nil { + t.Fatal(err) + } + failed, err := svc.ApplyDetachPlan(t.Context(), plan, nil) + if err == nil || failed.Detached != 0 || failed.Errors != 1 { + t.Fatalf("malformed settings should fail atomically: %+v, error %v", failed, err) + } + if err := db.Model(source).Update("settings", validSettings).Error; err != nil { + t.Fatal(err) + } + res, err := svc.ApplyDetachPlan(t.Context(), plan, nil) + if err != nil || res.Detached != 1 || !res.NodePending { + t.Fatalf("offline detach result: %+v, error %v", res, err) + } + if err := db.First(&node, node.Id).Error; err != nil || !node.ConfigDirty { + t.Fatalf("node was not queued for reconciliation: %+v, error %v", node, err) + } + retry, err := svc.ApplyDetachPlan(t.Context(), plan, nil) + if err != nil || retry.Detached != 0 || retry.Skipped != 1 { + t.Fatalf("retry = %+v, error %v", retry, err) + } +} diff --git a/internal/web/service/client_inbound_apply.go b/internal/web/service/client_inbound_apply.go index 84413233b..05816df51 100644 --- a/internal/web/service/client_inbound_apply.go +++ b/internal/web/service/client_inbound_apply.go @@ -25,13 +25,18 @@ import ( // endDroppedClientSessions is what restartXrayOnClientDisable asks for once the API removed a // client: it drops the credential only, so the restart is queued here, not left to a config diff. func endDroppedClientSessions(inbound *model.Inbound) bool { + on := restartAfterClientRemoval() + if on && removalLeavesXraySessions(inbound) { + pendingXraySessionDrop.Store(true) + } + return on +} + +func restartAfterClientRemoval() bool { on, err := (&SettingService{}).GetRestartXrayOnClientDisable() if err != nil { logger.Warning("get RestartXrayOnClientDisable failed:", err) } - if on && removalLeavesXraySessions(inbound) { - pendingXraySessionDrop.Store(true) - } return on } diff --git a/internal/web/translation/ar-EG.json b/internal/web/translation/ar-EG.json index ba3c8d851..3064320ad 100644 --- a/internal/web/translation/ar-EG.json +++ b/internal/web/translation/ar-EG.json @@ -381,6 +381,8 @@ "detachClientsResult": "فُصل {detached}، تم تخطي {skipped}.", "detachClientsResultMixed": "فُصل {detached}، تخطي {skipped}، أخطاء {errors}.", "detachClientsSelectLabel": "العملاء للفصل", + "detachSelectAll": "تحديد جميع العملاء المرتبطين", + "detachNodePending": "ستزامن العقدة هذه التغييرات.", "exportLinksTitle": "تصدير روابط الإدخال", "exportSubsTitle": "تصدير روابط الاشتراك", "exportAllLinksTitle": "تصدير كل روابط الإدخالات", diff --git a/internal/web/translation/en-US.json b/internal/web/translation/en-US.json index 4589de1af..37069c2a0 100644 --- a/internal/web/translation/en-US.json +++ b/internal/web/translation/en-US.json @@ -381,6 +381,8 @@ "detachClientsResult": "Detached {detached}, skipped {skipped}.", "detachClientsResultMixed": "Detached {detached}, skipped {skipped}, errors {errors}.", "detachClientsSelectLabel": "Clients to detach", + "detachSelectAll": "Select all attached clients", + "detachNodePending": "The node will sync these changes.", "exportLinksTitle": "Export inbound links", "exportSubsTitle": "Export subscription links", "exportAllLinksTitle": "Export all inbound links", diff --git a/internal/web/translation/es-ES.json b/internal/web/translation/es-ES.json index f5acc0fb9..7a30c9422 100644 --- a/internal/web/translation/es-ES.json +++ b/internal/web/translation/es-ES.json @@ -381,6 +381,8 @@ "detachClientsResult": "Desasociados {detached}, omitidos {skipped}.", "detachClientsResultMixed": "Desasociados {detached}, omitidos {skipped}, errores {errors}.", "detachClientsSelectLabel": "Clientes para desasociar", + "detachSelectAll": "Seleccionar todos los clientes vinculados", + "detachNodePending": "El nodo sincronizará estos cambios.", "exportLinksTitle": "Exportar enlaces del inbound", "exportSubsTitle": "Exportar enlaces de suscripción", "exportAllLinksTitle": "Exportar todos los enlaces de inbound", diff --git a/internal/web/translation/fa-IR.json b/internal/web/translation/fa-IR.json index ad3282605..554c8244d 100644 --- a/internal/web/translation/fa-IR.json +++ b/internal/web/translation/fa-IR.json @@ -381,6 +381,8 @@ "detachClientsResult": "جدا شد {detached}، نادیده {skipped}.", "detachClientsResultMixed": "جدا شد {detached}، نادیده {skipped}، خطا {errors}.", "detachClientsSelectLabel": "کاربران برای جداسازی", + "detachSelectAll": "انتخاب همهٔ کلاینت‌های متصل", + "detachNodePending": "نود این تغییرات را همگام‌سازی می‌کند.", "exportLinksTitle": "خروجی لینک‌های اینباند", "exportSubsTitle": "خروجی لینک‌های ساب", "exportAllLinksTitle": "خروجی لینک‌های همه اینباندها", diff --git a/internal/web/translation/id-ID.json b/internal/web/translation/id-ID.json index 3ff660bb3..ebee95042 100644 --- a/internal/web/translation/id-ID.json +++ b/internal/web/translation/id-ID.json @@ -381,6 +381,8 @@ "detachClientsResult": "Dilepas {detached}, dilewati {skipped}.", "detachClientsResultMixed": "Dilepas {detached}, dilewati {skipped}, error {errors}.", "detachClientsSelectLabel": "Klien untuk dilepas", + "detachSelectAll": "Pilih semua klien terpasang", + "detachNodePending": "Node akan menyinkronkan perubahan ini.", "exportLinksTitle": "Ekspor tautan inbound", "exportSubsTitle": "Ekspor tautan langganan", "exportAllLinksTitle": "Ekspor semua tautan inbound", diff --git a/internal/web/translation/ja-JP.json b/internal/web/translation/ja-JP.json index 465c0d65f..f5cadab6a 100644 --- a/internal/web/translation/ja-JP.json +++ b/internal/web/translation/ja-JP.json @@ -381,6 +381,8 @@ "detachClientsResult": "デタッチ {detached}、スキップ {skipped}。", "detachClientsResultMixed": "デタッチ {detached}、スキップ {skipped}、エラー {errors}。", "detachClientsSelectLabel": "デタッチするクライアント", + "detachSelectAll": "関連付けられたクライアントをすべて選択", + "detachNodePending": "ノードがこれらの変更を同期します。", "exportLinksTitle": "インバウンドリンクのエクスポート", "exportSubsTitle": "サブスクリプションリンクのエクスポート", "exportAllLinksTitle": "全インバウンドリンクのエクスポート", diff --git a/internal/web/translation/pt-BR.json b/internal/web/translation/pt-BR.json index 1f30a4831..f0f7b4fc1 100644 --- a/internal/web/translation/pt-BR.json +++ b/internal/web/translation/pt-BR.json @@ -381,6 +381,8 @@ "detachClientsResult": "Desassociados {detached}, ignorados {skipped}.", "detachClientsResultMixed": "Desassociados {detached}, ignorados {skipped}, erros {errors}.", "detachClientsSelectLabel": "Clientes para desassociar", + "detachSelectAll": "Selecionar todos os clientes vinculados", + "detachNodePending": "O nó sincronizará estas alterações.", "exportLinksTitle": "Exportar links do inbound", "exportSubsTitle": "Exportar links de assinatura", "exportAllLinksTitle": "Exportar todos os links de inbound", diff --git a/internal/web/translation/ru-RU.json b/internal/web/translation/ru-RU.json index 93b0199e2..2bb8bcc12 100644 --- a/internal/web/translation/ru-RU.json +++ b/internal/web/translation/ru-RU.json @@ -381,6 +381,8 @@ "detachClientsResult": "Отвязано {detached}, пропущено {skipped}.", "detachClientsResultMixed": "Отвязано {detached}, пропущено {skipped}, ошибок {errors}.", "detachClientsSelectLabel": "Клиенты для отвязки", + "detachSelectAll": "Выбрать всех привязанных клиентов", + "detachNodePending": "Узел синхронизирует эти изменения.", "exportLinksTitle": "Экспортировать ссылки подключения", "exportSubsTitle": "Экспортировать ссылки подписки", "exportAllLinksTitle": "Экспортировать все ссылки подключений", diff --git a/internal/web/translation/sk-SK.json b/internal/web/translation/sk-SK.json index 282d6ff57..7c8b27611 100644 --- a/internal/web/translation/sk-SK.json +++ b/internal/web/translation/sk-SK.json @@ -381,6 +381,8 @@ "detachClientsResult": "Odobraté: {detached}, preskočené: {skipped}.", "detachClientsResultMixed": "Odobraté: {detached}, preskočené: {skipped}, chyby: {errors}.", "detachClientsSelectLabel": "Klienti na odobratie", + "detachSelectAll": "Vybrať všetkých pripojených klientov", + "detachNodePending": "Uzol tieto zmeny zosynchronizuje.", "exportLinksTitle": "Exportovať odkazy vstupu", "exportSubsTitle": "Exportovať odkazy na odber", "exportAllLinksTitle": "Exportovať odkazy všetkých vstupov", diff --git a/internal/web/translation/tr-TR.json b/internal/web/translation/tr-TR.json index 9d22d6dff..f84416b5e 100644 --- a/internal/web/translation/tr-TR.json +++ b/internal/web/translation/tr-TR.json @@ -381,6 +381,8 @@ "detachClientsResult": "Çözüldü {detached}, atlandı {skipped}.", "detachClientsResultMixed": "Çözüldü {detached}, atlandı {skipped}, hatalar {errors}.", "detachClientsSelectLabel": "Çözülecek Kullanıcılar", + "detachSelectAll": "Bağlı tüm istemcileri seç", + "detachNodePending": "Düğüm bu değişiklikleri eşitleyecek.", "exportLinksTitle": "Gelen bağlantı bağlantılarını dışa aktar", "exportSubsTitle": "Abonelik bağlantılarını dışa aktar", "exportAllLinksTitle": "Tüm gelen bağlantı bağlantılarını dışa aktar", diff --git a/internal/web/translation/uk-UA.json b/internal/web/translation/uk-UA.json index 3b1b14e87..26d704168 100644 --- a/internal/web/translation/uk-UA.json +++ b/internal/web/translation/uk-UA.json @@ -381,6 +381,8 @@ "detachClientsResult": "Від'єднано {detached}, пропущено {skipped}.", "detachClientsResultMixed": "Від'єднано {detached}, пропущено {skipped}, помилок {errors}.", "detachClientsSelectLabel": "Клієнти для від'єднання", + "detachSelectAll": "Вибрати всіх прив’язаних клієнтів", + "detachNodePending": "Вузол синхронізує ці зміни.", "exportLinksTitle": "Експортувати посилання вхідних", "exportSubsTitle": "Експортувати посилання підписок", "exportAllLinksTitle": "Експортувати всі посилання вхідних", diff --git a/internal/web/translation/vi-VN.json b/internal/web/translation/vi-VN.json index 25b185e5d..5d926c696 100644 --- a/internal/web/translation/vi-VN.json +++ b/internal/web/translation/vi-VN.json @@ -381,6 +381,8 @@ "detachClientsResult": "Đã tách {detached}, bỏ qua {skipped}.", "detachClientsResultMixed": "Đã tách {detached}, bỏ qua {skipped}, lỗi {errors}.", "detachClientsSelectLabel": "Client để tách", + "detachSelectAll": "Chọn tất cả máy khách đã liên kết", + "detachNodePending": "Nút sẽ đồng bộ các thay đổi này.", "exportLinksTitle": "Xuất liên kết inbound", "exportSubsTitle": "Xuất liên kết đăng ký", "exportAllLinksTitle": "Xuất tất cả liên kết inbound", diff --git a/internal/web/translation/zh-CN.json b/internal/web/translation/zh-CN.json index ee7f0cbc4..153cd15f3 100644 --- a/internal/web/translation/zh-CN.json +++ b/internal/web/translation/zh-CN.json @@ -381,6 +381,8 @@ "detachClientsResult": "已分离 {detached},已跳过 {skipped}。", "detachClientsResultMixed": "已分离 {detached},已跳过 {skipped},错误 {errors}。", "detachClientsSelectLabel": "要分离的客户端", + "detachSelectAll": "选择所有已关联的客户端", + "detachNodePending": "节点将同步这些更改。", "exportLinksTitle": "导出入站链接", "exportSubsTitle": "导出订阅链接", "exportAllLinksTitle": "导出所有入站链接", diff --git a/internal/web/translation/zh-TW.json b/internal/web/translation/zh-TW.json index 09e1c9500..a54689fd9 100644 --- a/internal/web/translation/zh-TW.json +++ b/internal/web/translation/zh-TW.json @@ -381,6 +381,8 @@ "detachClientsResult": "已分離 {detached},已略過 {skipped}。", "detachClientsResultMixed": "已分離 {detached},已略過 {skipped},錯誤 {errors}。", "detachClientsSelectLabel": "要分離的客戶端", + "detachSelectAll": "選取所有已關聯的用戶端", + "detachNodePending": "節點將同步這些變更。", "exportLinksTitle": "匯出入站連結", "exportSubsTitle": "匯出訂閱連結", "exportAllLinksTitle": "匯出所有入站連結", diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go index c79c68983..d068d308b 100644 --- a/tools/openapigen/main.go +++ b/tools/openapigen/main.go @@ -125,6 +125,10 @@ func run(root, outDir string) error { "BulkDeleteResult", "BulkDeleteReport", "AttachSelectionResult", + "DetachCandidate", + "DetachCandidatePage", + "DetachScopeSummary", + "DetachSelectionResult", "BulkAdjustResult", "BulkAdjustReport", "BulkAttachResult", @@ -170,7 +174,7 @@ func run(root, outDir string) error { }, { Path: resolveRel(root, "internal/web/controller"), - StructAllow: setOf("TgBotCapabilities", "AttachJobStatus"), + StructAllow: setOf("TgBotCapabilities", "AttachJobStatus", "DetachJobStatus"), }, { Path: resolveRel(root, "internal/amneziawg"),