fix(inbounds): scale bulk client attachment selection (#7243)

With around 10,000 clients both attach dialogs loaded every client, pre-selected all of them and rendered every row, which locked the browser for minutes.

Both dialogs now ask the server for 100 rows at a time and render only the visible ones. Select All freezes the eligible client IDs that match the current search and group into a small server-issued token; the browser keeps that token plus the clients the operator unticked instead of thousands of emails, and the listing marks each row against the frozen filter so rows outside it stay unselected. On submit the server re-derives the same set and rejects the job before any write when its membership changed; clients created after the freeze stay outside it. The attach runs as a background job the dialog polls for counts.

Requests that post an email list keep their synchronous response. The Postgres job now runs the selection tests, which build their predicates by hand for both dialects.

Fixes #7236
This commit is contained in:
Hamed
2026-11-28 18:00:53 +03:30
committed by GitHub
parent 9088b8a768
commit 75dc6dc61c
34 changed files with 2643 additions and 492 deletions
+10
View File
@@ -163,6 +163,16 @@ jobs:
exit 1
fi
- name: PostgreSQL attach candidate selection
run: |
set -o pipefail
go test ./internal/web/service -run '^Test(AttachCandidatesSelection|FrozenAttachSelectionFollowsFilter)Postgres$' -count=1 -v | tee /tmp/postgres-attach-selection.log
passed=$(grep -c -- '^--- PASS' /tmp/postgres-attach-selection.log || true)
if [ "$passed" -ne 2 ]; then
echo "expected 2 passing PostgreSQL attach selection tests, got $passed" >&2
exit 1
fi
- name: PostgreSQL depletion query regressions
run: |
set -o pipefail
+43 -8
View File
@@ -13,6 +13,13 @@ _openapi:
reverse field, if set, is returned as a nested JSON object (legacy
JSON-encoded-string form is still accepted on write).
url: '#list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write'
- depth: 2
title: List up to 100 clients for the inbound attachment picker. Counts
distinguish filtered rows and all eligible clients. A freeze request
returns only the eligible count, maximum ID and a scope token covering
the eligible IDs that match the given search and group for the chosen
source and targets.
url: '#list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets'
- depth: 2
title: 'Filter, sort, and paginate clients on the server. Each item is a slim
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
@@ -206,9 +213,21 @@ _openapi:
keeps its identity (email/UUID/password/subId) and a shared traffic row;
all clients are added to a target inbound in a single AddInboundClient
call. Clients already present on a target are reported under skipped.
Returns per-email attached/skipped/errors lists and triggers a single
Xray restart if any target inbound was running.
url: '#attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running'
Explicit email requests return per-email lists. Alternatively submit
selection with explicit clientIds or a frozen allMatching scopeToken
plus excludedClientIds and the search and group it was frozen under.
Scoped requests start a background job and return {jobId}. Poll GET
/bulkAttach/:id for counts or a stale-selection error. Newer IDs stay
outside the frozen scope. Changes to the frozen membership are rejected
before applying changes. Triggers a single Xray restart if any target
inbound was running.
url: '#attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-explicit-email-requests-return-per-email-lists-alternatively-submit-selection-with-explicit-clientids-or-a-frozen-allmatching-scopetoken-plus-excludedclientids-and-the-search-and-group-it-was-frozen-under-scoped-requests-start-a-background-job-and-return-jobid-poll-get-bulkattachid-for-counts-or-a-stale-selection-error-newer-ids-stay-outside-the-frozen-scope-changes-to-the-frozen-membership-are-rejected-before-applying-changes-triggers-a-single-xray-restart-if-any-target-inbound-was-running'
- depth: 2
title: 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.
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
@@ -386,6 +405,12 @@ _openapi:
reverse field, if set, is returned as a nested JSON object (legacy
JSON-encoded-string form is still accepted on write).
id: list-every-client-with-its-attached-inbound-ids-and-traffic-record-the-reverse-field-if-set-is-returned-as-a-nested-json-object-legacy-json-encoded-string-form-is-still-accepted-on-write
- content: List up to 100 clients for the inbound attachment picker. Counts
distinguish filtered rows and all eligible clients. A freeze request
returns only the eligible count, maximum ID and a scope token covering
the eligible IDs that match the given search and group for the chosen
source and targets.
id: list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets
- content: 'Filter, sort, and paginate clients on the server. Each item is a slim
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
page can ship 25-ish rows in a few KB instead of the full table. The
@@ -551,10 +576,20 @@ _openapi:
keeps its identity (email/UUID/password/subId) and a shared traffic
row; all clients are added to a target inbound in a single
AddInboundClient call. Clients already present on a target are
reported under skipped. Returns per-email attached/skipped/errors
lists and triggers a single Xray restart if any target inbound was
running.
id: attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-returns-per-email-attachedskippederrors-lists-and-triggers-a-single-xray-restart-if-any-target-inbound-was-running
reported under skipped. Explicit email requests return per-email
lists. Alternatively submit selection with explicit clientIds or a
frozen allMatching scopeToken plus excludedClientIds and the search
and group it was frozen under. Scoped requests start a background job
and return {jobId}. Poll GET /bulkAttach/:id for counts or a
stale-selection error. Newer IDs stay outside the frozen scope.
Changes to the frozen membership are rejected before applying changes.
Triggers a single Xray restart if any target inbound was running.
id: attach-many-existing-clients-to-many-inbounds-in-one-call-each-client-keeps-its-identity-emailuuidpasswordsubid-and-a-shared-traffic-row-all-clients-are-added-to-a-target-inbound-in-a-single-addinboundclient-call-clients-already-present-on-a-target-are-reported-under-skipped-explicit-email-requests-return-per-email-lists-alternatively-submit-selection-with-explicit-clientids-or-a-frozen-allmatching-scopetoken-plus-excludedclientids-and-the-search-and-group-it-was-frozen-under-scoped-requests-start-a-background-job-and-return-jobid-poll-get-bulkattachid-for-counts-or-a-stale-selection-error-newer-ids-stay-outside-the-frozen-scope-changes-to-the-frozen-membership-are-rejected-before-applying-changes-triggers-a-single-xray-restart-if-any-target-inbound-was-running
- content: 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.
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)
@@ -883,7 +918,7 @@ export default function Layout(props) {
return (
<>
{props.children}
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/update","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/del","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/wireguardDevices","method":"get"},{"path":"/panel/api/clients/wireguardDevices","method":"post"},{"path":"/panel/api/clients/wireguardDevices/limit","method":"put"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"patch"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"delete"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/hosts","method":"post"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}/block","method":"post"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/usageHistory/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
<OpenAPIPage document="./public/openapi.json" webhooks={[]} operations={[{"path":"/panel/api/clients/list","method":"get"},{"path":"/panel/api/clients/attachCandidates","method":"get"},{"path":"/panel/api/clients/list/paged","method":"get"},{"path":"/panel/api/clients/get/{email}","method":"get"},{"path":"/panel/api/clients/get","method":"get"},{"path":"/panel/api/clients/get/subId/{subId}","method":"get"},{"path":"/panel/api/clients/get/tgId/{tgId}","method":"get"},{"path":"/panel/api/clients/add","method":"post"},{"path":"/panel/api/clients/renewalPreview","method":"post"},{"path":"/panel/api/clients/update/{email}","method":"post"},{"path":"/panel/api/clients/update","method":"post"},{"path":"/panel/api/clients/del/{email}","method":"post"},{"path":"/panel/api/clients/del","method":"post"},{"path":"/panel/api/clients/{email}/attach","method":"post"},{"path":"/panel/api/clients/{email}/detach","method":"post"},{"path":"/panel/api/clients/{email}/externalLinks","method":"post"},{"path":"/panel/api/clients/wireguardDevices","method":"get"},{"path":"/panel/api/clients/wireguardDevices","method":"post"},{"path":"/panel/api/clients/wireguardDevices/limit","method":"put"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"patch"},{"path":"/panel/api/clients/wireguardDevices/{deviceId}","method":"delete"},{"path":"/panel/api/clients/resetAllTraffics","method":"post"},{"path":"/panel/api/clients/delDepleted","method":"post"},{"path":"/panel/api/clients/delOrphans","method":"post"},{"path":"/panel/api/clients/export","method":"get"},{"path":"/panel/api/clients/import","method":"post"},{"path":"/panel/api/clients/bulkAdjust","method":"post"},{"path":"/panel/api/clients/bulkEnable","method":"post"},{"path":"/panel/api/clients/bulkDisable","method":"post"},{"path":"/panel/api/clients/bulkDel","method":"post"},{"path":"/panel/api/clients/bulkCreate","method":"post"},{"path":"/panel/api/clients/groups/bulkAdd","method":"post"},{"path":"/panel/api/clients/groups/bulkRemove","method":"post"},{"path":"/panel/api/clients/bulkAttach","method":"post"},{"path":"/panel/api/clients/bulkAttach/{id}","method":"get"},{"path":"/panel/api/clients/bulkDetach","method":"post"},{"path":"/panel/api/clients/bulkResetTraffic","method":"post"},{"path":"/panel/api/clients/groups","method":"get"},{"path":"/panel/api/clients/groups/{name}/hosts","method":"post"},{"path":"/panel/api/clients/groups/{name}/emails","method":"get"},{"path":"/panel/api/clients/groups/create","method":"post"},{"path":"/panel/api/clients/groups/rename","method":"post"},{"path":"/panel/api/clients/groups/delete","method":"post"},{"path":"/panel/api/clients/groups/resetTraffic","method":"post"},{"path":"/panel/api/clients/resetTraffic/{email}","method":"post"},{"path":"/panel/api/clients/updateTraffic/{email}","method":"post"},{"path":"/panel/api/clients/ips/{email}","method":"post"},{"path":"/panel/api/clients/clearIps/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"post"},{"path":"/panel/api/clients/hwids/{email}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}","method":"delete"},{"path":"/panel/api/clients/hwids/{email}/{id}/block","method":"post"},{"path":"/panel/api/clients/onlines","method":"post"},{"path":"/panel/api/clients/onlinesByGuid","method":"post"},{"path":"/panel/api/clients/clientIpsByGuid","method":"post"},{"path":"/panel/api/clients/activeInbounds","method":"post"},{"path":"/panel/api/clients/lastOnline","method":"post"},{"path":"/panel/api/clients/traffic/{email}","method":"get"},{"path":"/panel/api/clients/usageHistory/{email}","method":"get"},{"path":"/panel/api/clients/subLinks/{subId}","method":"get"},{"path":"/panel/api/clients/happLink/{id}","method":"post"},{"path":"/panel/api/clients/links/{email}","method":"get"}]} showTitle />
</>
);
}
+321 -3
View File
@@ -1903,6 +1903,140 @@
],
"type": "object"
},
"AttachCandidate": {
"properties": {
"alreadyAttached": {
"example": false,
"type": "boolean"
},
"comment": {
"example": "Example client",
"type": "string"
},
"email": {
"example": "alice@example.test",
"type": "string"
},
"enable": {
"example": true,
"type": "boolean"
},
"group": {
"example": "staff",
"type": "string"
},
"id": {
"example": 1,
"type": "integer"
},
"inScope": {
"example": true,
"type": "boolean"
}
},
"required": [
"alreadyAttached",
"comment",
"email",
"enable",
"group",
"id",
"inScope"
],
"type": "object"
},
"AttachCandidatePage": {
"properties": {
"eligible": {
"example": 118,
"format": "int64",
"type": "integer"
},
"groups": {
"example": [
"staff"
],
"items": {
"type": "string"
},
"type": "array"
},
"items": {
"items": {
"$ref": "#/components/schemas/AttachCandidate"
},
"type": "array"
},
"maxId": {
"type": "integer"
},
"scopeToken": {
"type": "string"
},
"total": {
"example": 120,
"format": "int64",
"type": "integer"
}
},
"required": [
"eligible",
"groups",
"items",
"total"
],
"type": "object"
},
"AttachJobStatus": {
"properties": {
"ended": {
"format": "date-time",
"type": "string"
},
"error": {
"type": "string"
},
"result": {
"allOf": [
{
"$ref": "#/components/schemas/AttachSelectionResult"
}
],
"nullable": true
},
"running": {
"example": false,
"type": "boolean"
}
},
"required": [
"ended",
"running"
],
"type": "object"
},
"AttachSelectionResult": {
"properties": {
"attached": {
"example": 9997,
"type": "integer"
},
"errors": {
"example": 0,
"type": "integer"
},
"skipped": {
"example": 0,
"type": "integer"
}
},
"required": [
"attached",
"errors",
"skipped"
],
"type": "object"
},
"Blocker": {
"description": "Blocker is one unmet requirement.",
"properties": {
@@ -9479,6 +9613,135 @@
}
}
},
"/panel/api/clients/attachCandidates": {
"get": {
"tags": [
"Clients"
],
"summary": "List up to 100 clients for the inbound attachment picker. Counts distinguish filtered rows and all eligible clients. A freeze request returns only the eligible count, maximum ID and a scope token covering the eligible IDs that match the given search and group for the chosen source and targets.",
"operationId": "get_panel_api_clients_attachCandidates",
"parameters": [
{
"name": "sourceId",
"in": "query",
"required": false,
"description": "Restrict candidates to clients on this inbound.",
"schema": {
"type": "integer"
}
},
{
"name": "inboundIds",
"in": "query",
"required": false,
"description": "Comma-separated target IDs. Required for freeze and if no source ID is specified.",
"schema": {
"type": "string"
}
},
{
"name": "page",
"in": "query",
"required": false,
"description": "1-indexed page, defaults to 1.",
"schema": {
"type": "integer"
}
},
{
"name": "search",
"in": "query",
"required": false,
"description": "Match email and either comment (with a source) or group.",
"schema": {
"type": "string"
}
},
{
"name": "group",
"in": "query",
"required": false,
"description": "Filter by exact group when there is no source.",
"schema": {
"type": "string"
}
},
{
"name": "freeze",
"in": "query",
"required": false,
"description": "Freeze the eligible IDs matching search and group, independently of page.",
"schema": {
"type": "boolean"
}
},
{
"name": "scopeSearch",
"in": "query",
"required": false,
"description": "Search a frozen selection was taken under; rows outside it report inScope false.",
"schema": {
"type": "string"
}
},
{
"name": "scopeGroup",
"in": "query",
"required": false,
"description": "Group a frozen selection was taken under; rows outside it report inScope false.",
"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/AttachCandidatePage"
}
}
},
"example": {
"success": true,
"obj": {
"eligible": 118,
"groups": [
"staff"
],
"items": [
{
"alreadyAttached": false,
"comment": "Example client",
"email": "alice@example.test",
"enable": true,
"group": "staff",
"id": 1,
"inScope": true
}
],
"maxId": 0,
"scopeToken": "",
"total": 120
}
}
}
}
}
}
}
},
"/panel/api/clients/list/paged": {
"get": {
"tags": [
@@ -11719,7 +11982,7 @@
"tags": [
"Clients"
],
"summary": "Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Returns per-email attached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.",
"summary": "Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.",
"operationId": "post_panel_api_clients_bulkAttach",
"requestBody": {
"required": true,
@@ -11733,7 +11996,11 @@
"items": {
"type": "string"
},
"description": "Emails of existing clients to attach."
"description": "Emails of existing clients to attach. Omit when using selection."
},
"selection": {
"type": "object",
"description": "Either {mode: \"explicit\", clientIds, sourceId?} or {mode: \"allMatching\", scopeToken, excludedClientIds?, search?, group?, sourceId?}."
},
"inboundIds": {
"type": "array",
@@ -11744,7 +12011,6 @@
}
},
"required": [
"emails",
"inboundIds"
]
},
@@ -11797,6 +12063,58 @@
}
}
},
"/panel/api/clients/bulkAttach/{id}": {
"get": {
"tags": [
"Clients"
],
"summary": "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.",
"operationId": "get_panel_api_clients_bulkAttach_id",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"description": "Job ID returned by the scoped bulkAttach request.",
"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/AttachJobStatus"
}
}
},
"example": {
"success": true,
"obj": {
"ended": "2025-01-01T00:00:00Z",
"error": "",
"result": null,
"running": false
}
}
}
}
}
}
}
},
"/panel/api/clients/bulkDetach": {
"post": {
"tags": [
+321 -3
View File
@@ -1903,6 +1903,140 @@
],
"type": "object"
},
"AttachCandidate": {
"properties": {
"alreadyAttached": {
"example": false,
"type": "boolean"
},
"comment": {
"example": "Example client",
"type": "string"
},
"email": {
"example": "alice@example.test",
"type": "string"
},
"enable": {
"example": true,
"type": "boolean"
},
"group": {
"example": "staff",
"type": "string"
},
"id": {
"example": 1,
"type": "integer"
},
"inScope": {
"example": true,
"type": "boolean"
}
},
"required": [
"alreadyAttached",
"comment",
"email",
"enable",
"group",
"id",
"inScope"
],
"type": "object"
},
"AttachCandidatePage": {
"properties": {
"eligible": {
"example": 118,
"format": "int64",
"type": "integer"
},
"groups": {
"example": [
"staff"
],
"items": {
"type": "string"
},
"type": "array"
},
"items": {
"items": {
"$ref": "#/components/schemas/AttachCandidate"
},
"type": "array"
},
"maxId": {
"type": "integer"
},
"scopeToken": {
"type": "string"
},
"total": {
"example": 120,
"format": "int64",
"type": "integer"
}
},
"required": [
"eligible",
"groups",
"items",
"total"
],
"type": "object"
},
"AttachJobStatus": {
"properties": {
"ended": {
"format": "date-time",
"type": "string"
},
"error": {
"type": "string"
},
"result": {
"allOf": [
{
"$ref": "#/components/schemas/AttachSelectionResult"
}
],
"nullable": true
},
"running": {
"example": false,
"type": "boolean"
}
},
"required": [
"ended",
"running"
],
"type": "object"
},
"AttachSelectionResult": {
"properties": {
"attached": {
"example": 9997,
"type": "integer"
},
"errors": {
"example": 0,
"type": "integer"
},
"skipped": {
"example": 0,
"type": "integer"
}
},
"required": [
"attached",
"errors",
"skipped"
],
"type": "object"
},
"Blocker": {
"description": "Blocker is one unmet requirement.",
"properties": {
@@ -9479,6 +9613,135 @@
}
}
},
"/panel/api/clients/attachCandidates": {
"get": {
"tags": [
"Clients"
],
"summary": "List up to 100 clients for the inbound attachment picker. Counts distinguish filtered rows and all eligible clients. A freeze request returns only the eligible count, maximum ID and a scope token covering the eligible IDs that match the given search and group for the chosen source and targets.",
"operationId": "get_panel_api_clients_attachCandidates",
"parameters": [
{
"name": "sourceId",
"in": "query",
"required": false,
"description": "Restrict candidates to clients on this inbound.",
"schema": {
"type": "integer"
}
},
{
"name": "inboundIds",
"in": "query",
"required": false,
"description": "Comma-separated target IDs. Required for freeze and if no source ID is specified.",
"schema": {
"type": "string"
}
},
{
"name": "page",
"in": "query",
"required": false,
"description": "1-indexed page, defaults to 1.",
"schema": {
"type": "integer"
}
},
{
"name": "search",
"in": "query",
"required": false,
"description": "Match email and either comment (with a source) or group.",
"schema": {
"type": "string"
}
},
{
"name": "group",
"in": "query",
"required": false,
"description": "Filter by exact group when there is no source.",
"schema": {
"type": "string"
}
},
{
"name": "freeze",
"in": "query",
"required": false,
"description": "Freeze the eligible IDs matching search and group, independently of page.",
"schema": {
"type": "boolean"
}
},
{
"name": "scopeSearch",
"in": "query",
"required": false,
"description": "Search a frozen selection was taken under; rows outside it report inScope false.",
"schema": {
"type": "string"
}
},
{
"name": "scopeGroup",
"in": "query",
"required": false,
"description": "Group a frozen selection was taken under; rows outside it report inScope false.",
"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/AttachCandidatePage"
}
}
},
"example": {
"success": true,
"obj": {
"eligible": 118,
"groups": [
"staff"
],
"items": [
{
"alreadyAttached": false,
"comment": "Example client",
"email": "alice@example.test",
"enable": true,
"group": "staff",
"id": 1,
"inScope": true
}
],
"maxId": 0,
"scopeToken": "",
"total": 120
}
}
}
}
}
}
}
},
"/panel/api/clients/list/paged": {
"get": {
"tags": [
@@ -11719,7 +11982,7 @@
"tags": [
"Clients"
],
"summary": "Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Returns per-email attached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.",
"summary": "Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.",
"operationId": "post_panel_api_clients_bulkAttach",
"requestBody": {
"required": true,
@@ -11733,7 +11996,11 @@
"items": {
"type": "string"
},
"description": "Emails of existing clients to attach."
"description": "Emails of existing clients to attach. Omit when using selection."
},
"selection": {
"type": "object",
"description": "Either {mode: \"explicit\", clientIds, sourceId?} or {mode: \"allMatching\", scopeToken, excludedClientIds?, search?, group?, sourceId?}."
},
"inboundIds": {
"type": "array",
@@ -11744,7 +12011,6 @@
}
},
"required": [
"emails",
"inboundIds"
]
},
@@ -11797,6 +12063,58 @@
}
}
},
"/panel/api/clients/bulkAttach/{id}": {
"get": {
"tags": [
"Clients"
],
"summary": "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.",
"operationId": "get_panel_api_clients_bulkAttach_id",
"parameters": [
{
"name": "id",
"in": "path",
"required": true,
"description": "Job ID returned by the scoped bulkAttach request.",
"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/AttachJobStatus"
}
}
},
"example": {
"success": true,
"obj": {
"ended": "2025-01-01T00:00:00Z",
"error": "",
"result": null,
"running": false
}
}
}
}
}
}
}
},
"/panel/api/clients/bulkDetach": {
"post": {
"tags": [
+40
View File
@@ -452,6 +452,46 @@ export const EXAMPLES: Record<string, unknown> = {
"scope": "admin",
"token": "new-token-string"
},
"AttachCandidate": {
"alreadyAttached": false,
"comment": "Example client",
"email": "alice@example.test",
"enable": true,
"group": "staff",
"id": 1,
"inScope": true
},
"AttachCandidatePage": {
"eligible": 118,
"groups": [
"staff"
],
"items": [
{
"alreadyAttached": false,
"comment": "Example client",
"email": "alice@example.test",
"enable": true,
"group": "staff",
"id": 1,
"inScope": true
}
],
"maxId": 0,
"scopeToken": "",
"total": 120
},
"AttachJobStatus": {
"ended": "2025-01-01T00:00:00Z",
"error": "",
"result": null,
"running": false
},
"AttachSelectionResult": {
"attached": 9997,
"errors": 0,
"skipped": 0
},
"Blocker": {
"code": "tools",
"detail": "awg"
+134
View File
@@ -1877,6 +1877,140 @@ export const SCHEMAS: Record<string, unknown> = {
],
"type": "object"
},
"AttachCandidate": {
"properties": {
"alreadyAttached": {
"example": false,
"type": "boolean"
},
"comment": {
"example": "Example client",
"type": "string"
},
"email": {
"example": "alice@example.test",
"type": "string"
},
"enable": {
"example": true,
"type": "boolean"
},
"group": {
"example": "staff",
"type": "string"
},
"id": {
"example": 1,
"type": "integer"
},
"inScope": {
"example": true,
"type": "boolean"
}
},
"required": [
"alreadyAttached",
"comment",
"email",
"enable",
"group",
"id",
"inScope"
],
"type": "object"
},
"AttachCandidatePage": {
"properties": {
"eligible": {
"example": 118,
"format": "int64",
"type": "integer"
},
"groups": {
"example": [
"staff"
],
"items": {
"type": "string"
},
"type": "array"
},
"items": {
"items": {
"$ref": "#/components/schemas/AttachCandidate"
},
"type": "array"
},
"maxId": {
"type": "integer"
},
"scopeToken": {
"type": "string"
},
"total": {
"example": 120,
"format": "int64",
"type": "integer"
}
},
"required": [
"eligible",
"groups",
"items",
"total"
],
"type": "object"
},
"AttachJobStatus": {
"properties": {
"ended": {
"format": "date-time",
"type": "string"
},
"error": {
"type": "string"
},
"result": {
"allOf": [
{
"$ref": "#/components/schemas/AttachSelectionResult"
}
],
"nullable": true
},
"running": {
"example": false,
"type": "boolean"
}
},
"required": [
"ended",
"running"
],
"type": "object"
},
"AttachSelectionResult": {
"properties": {
"attached": {
"example": 9997,
"type": "integer"
},
"errors": {
"example": 0,
"type": "integer"
},
"skipped": {
"example": 0,
"type": "integer"
}
},
"required": [
"attached",
"errors",
"skipped"
],
"type": "object"
},
"Blocker": {
"description": "Blocker is one unmet requirement.",
"properties": {
+32
View File
@@ -447,6 +447,38 @@ export interface ApiTokenView {
token?: string;
}
export interface AttachCandidate {
alreadyAttached: boolean;
comment: string;
email: string;
enable: boolean;
group: string;
id: number;
inScope: boolean;
}
export interface AttachCandidatePage {
eligible: number;
groups: string[];
items: AttachCandidate[];
maxId?: number;
scopeToken?: string;
total: number;
}
export interface AttachJobStatus {
ended: string;
error?: string;
result?: AttachSelectionResult | null;
running: boolean;
}
export interface AttachSelectionResult {
attached: number;
errors: number;
skipped: number;
}
export interface Blocker {
code: BlockerCode;
detail?: string;
+36
View File
@@ -462,6 +462,42 @@ export const ApiTokenViewSchema = z.object({
});
export type ApiTokenView = z.infer<typeof ApiTokenViewSchema>;
export const AttachCandidateSchema = z.object({
alreadyAttached: z.boolean(),
comment: z.string(),
email: z.string(),
enable: z.boolean(),
group: z.string(),
id: z.number().int(),
inScope: z.boolean(),
});
export type AttachCandidate = z.infer<typeof AttachCandidateSchema>;
export const AttachCandidatePageSchema = z.object({
eligible: z.number().int(),
groups: z.array(z.string()),
items: z.array(z.lazy(() => AttachCandidateSchema)),
maxId: z.number().int().optional(),
scopeToken: z.string().optional(),
total: z.number().int(),
});
export type AttachCandidatePage = z.infer<typeof AttachCandidatePageSchema>;
export const AttachJobStatusSchema = z.object({
ended: z.string(),
error: z.string().optional(),
result: z.lazy(() => AttachSelectionResultSchema).nullable().optional(),
running: z.boolean(),
});
export type AttachJobStatus = z.infer<typeof AttachJobStatusSchema>;
export const AttachSelectionResultSchema = z.object({
attached: z.number().int(),
errors: z.number().int(),
skipped: z.number().int(),
});
export type AttachSelectionResult = z.infer<typeof AttachSelectionResultSchema>;
export const BlockerSchema = z.object({
code: z.lazy(() => BlockerCodeSchema),
detail: z.string().optional(),
+90 -2
View File
@@ -1020,6 +1020,71 @@ export const sections: readonly Section[] = [
response:
'{\n "success": true,\n "obj": [\n {\n "id": 1,\n "email": "alice@example.com",\n "subId": "abcd1234",\n "uuid": "...",\n "totalGB": 53687091200,\n "expiryTime": 1735689600000,\n "enable": true,\n "reverse": null,\n "inboundIds": [3, 5],\n "traffic": { "up": 1024, "down": 4096, "enable": true }\n }\n ]\n}',
},
{
method: 'GET',
path: '/panel/api/clients/attachCandidates',
summary:
'List up to 100 clients for the inbound attachment picker. Counts distinguish filtered rows and all eligible clients. A freeze request returns only the eligible count, maximum ID and a scope token covering the eligible IDs that match the given search and group for the chosen source and targets.',
params: [
{
name: 'sourceId',
in: 'query',
type: 'number',
desc: 'Restrict candidates to clients on this inbound.',
optional: true,
},
{
name: 'inboundIds',
in: 'query',
type: 'string',
desc: 'Comma-separated target IDs. Required for freeze and if no source ID is specified.',
optional: true,
},
{
name: 'page',
in: 'query',
type: 'number',
desc: '1-indexed page, defaults to 1.',
optional: true,
},
{
name: 'search',
in: 'query',
type: 'string',
desc: 'Match email and either comment (with a source) or group.',
optional: true,
},
{
name: 'group',
in: 'query',
type: 'string',
desc: 'Filter by exact group when there is no source.',
optional: true,
},
{
name: 'freeze',
in: 'query',
type: 'boolean',
desc: 'Freeze the eligible IDs matching search and group, independently of page.',
optional: true,
},
{
name: 'scopeSearch',
in: 'query',
type: 'string',
desc: 'Search a frozen selection was taken under; rows outside it report inScope false.',
optional: true,
},
{
name: 'scopeGroup',
in: 'query',
type: 'string',
desc: 'Group a frozen selection was taken under; rows outside it report inScope false.',
optional: true,
},
],
responseSchema: 'AttachCandidatePage',
},
{
method: 'GET',
path: '/panel/api/clients/list/paged',
@@ -1650,13 +1715,21 @@ export const sections: readonly Section[] = [
method: 'POST',
path: '/panel/api/clients/bulkAttach',
summary:
'Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Returns per-email attached/skipped/errors lists and triggers a single Xray restart if any target inbound was running.',
'Attach many existing clients to many inbounds in one call. Each client keeps its identity (email/UUID/password/subId) and a shared traffic row; all clients are added to a target inbound in a single AddInboundClient call. Clients already present on a target are reported under skipped. Explicit email requests return per-email lists. Alternatively submit selection with explicit clientIds or a frozen allMatching scopeToken plus excludedClientIds and the search and group it was frozen under. Scoped requests start a background job and return {jobId}. Poll GET /bulkAttach/:id for counts or a stale-selection error. Newer IDs stay outside the frozen scope. Changes to the frozen membership are rejected before applying changes. Triggers a single Xray restart if any target inbound was running.',
params: [
{
name: 'emails',
in: 'body (json)',
type: 'string[]',
desc: 'Emails of existing clients to attach.',
desc: 'Emails of existing clients to attach. Omit when using selection.',
optional: true,
},
{
name: 'selection',
in: 'body (json)',
type: 'object',
desc: 'Either {mode: "explicit", clientIds, sourceId?} or {mode: "allMatching", scopeToken, excludedClientIds?, search?, group?, sourceId?}.',
optional: true,
},
{
name: 'inboundIds',
@@ -1669,6 +1742,21 @@ export const sections: readonly Section[] = [
response:
'{\n "success": true,\n "obj": {\n "attached": ["alice", "bob"],\n "skipped": ["bob"],\n "errors": []\n }\n}',
},
{
method: 'GET',
path: '/panel/api/clients/bulkAttach/:id',
summary:
'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.',
params: [
{
name: 'id',
in: 'path',
type: 'string',
desc: 'Job ID returned by the scoped bulkAttach request.',
},
],
responseSchema: 'AttachJobStatus',
},
{
method: 'POST',
path: '/panel/api/clients/bulkDetach',
@@ -0,0 +1,497 @@
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import {
Alert,
AutoComplete,
Button,
Input,
Modal,
Pagination,
Select,
Space,
Table,
Tag,
Typography,
message,
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { selectTagRender } from '@/components/form';
import { formatInboundLabel } from '@/lib/inbounds/label';
import type { DBInbound } from '@/models/dbinbound';
import { HttpUtil, PromiseUtil } from '@/utils';
import { isInboundMultiUser } from '../list';
const PAGE_SIZE = 100;
const CANDIDATES = '/panel/api/clients/attachCandidates';
interface Candidate {
id: number;
email: string;
comment: string;
group: string;
enable: boolean;
alreadyAttached: boolean;
inScope: boolean;
}
interface CandidatePage {
items: Candidate[];
total: number;
eligible: number;
groups: string[];
scopeToken?: string;
maxId?: number;
}
interface AttachResult {
attached: number;
skipped: number;
errors: number;
}
interface FrozenSelection {
token: string;
eligible: number;
maxId: number;
search: string;
group: string;
}
function inFrozenScope(frozen: FrozenSelection, row: Candidate) {
return row.inScope && row.id <= frozen.maxId;
}
interface AttachClientPickerProps {
inbound: DBInbound;
sourceInbounds?: DBInbound[];
onClose: () => void;
onAttached?: () => void;
}
export default function AttachClientPickerModal({
inbound,
sourceInbounds,
onClose,
onAttached,
}: AttachClientPickerProps) {
const { t } = useTranslation();
const [messages, holder] = message.useMessage();
const sourceId = sourceInbounds ? inbound.id : 0;
const [targets, setTargets] = useState(sourceId ? [] : [inbound.id]);
const targetScope = targets.join(',');
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const [group, setGroup] = useState('');
const [rows, setRows] = useState<CandidatePage>();
const [loadError, setLoadError] = useState('');
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState<'freeze' | 'submit'>();
const action = useRef(false);
const [frozen, setFrozen] = useState<FrozenSelection>();
// Explicitly selected rows, or excluded rows when the scope is frozen.
const [choices, setChoices] = useState(new Map<number, string>());
const [exclusionPage, setExclusionPage] = useState(1);
const selected = frozen ? frozen.eligible - choices.size : choices.size;
const scopeSearch = frozen?.search ?? '';
const scopeGroup = frozen?.group ?? '';
useEffect(() => {
let cancelled = false;
const timer = window.setTimeout(
() => {
HttpUtil.get(
CANDIDATES,
{
sourceId,
inboundIds: targetScope,
page,
search,
group,
scopeSearch,
scopeGroup,
},
{ silent: true },
)
.then((response) => {
if (cancelled) return;
if (response?.success) {
setRows(response.obj as CandidatePage);
setLoadError('');
} else {
setRows(undefined);
setLoadError(response?.msg || t('somethingWentWrong'));
}
})
.finally(() => {
if (!cancelled) setLoading(false);
});
},
search || group ? 220 : 0,
);
return () => {
cancelled = true;
window.clearTimeout(timer);
};
}, [sourceId, targetScope, page, search, group, scopeSearch, scopeGroup, t]);
function clear() {
setFrozen(undefined);
setChoices(new Map());
setExclusionPage(1);
}
function changeTargets(ids: number[]) {
clear();
setTargets(ids);
setLoading(true);
setPage(1);
}
function selectRows(keys: React.Key[]) {
const checked = new Set(keys);
setChoices((current) => {
const next = new Map(current);
for (const row of rows?.items ?? []) {
if (row.alreadyAttached || (frozen && !inFrozenScope(frozen, row))) continue;
if (frozen ? !checked.has(row.id) : checked.has(row.id)) next.set(row.id, row.email);
else next.delete(row.id);
}
return next;
});
}
async function selectAll() {
if (action.current || !targets.length) return;
action.current = true;
setBusy('freeze');
try {
const response = await HttpUtil.get(
CANDIDATES,
{ sourceId, inboundIds: targetScope, search, group, freeze: true },
{ silent: true },
);
const scope = response?.obj as CandidatePage | undefined;
if (!response?.success || !scope?.scopeToken) {
messages.error(response?.msg || t('somethingWentWrong'));
return;
}
clear();
setFrozen({
token: scope.scopeToken,
eligible: scope.eligible,
maxId: scope.maxId ?? 0,
search,
group,
});
} finally {
action.current = false;
setBusy(undefined);
}
}
async function submit() {
if (action.current || !targets.length || selected <= 0) return;
action.current = true;
setBusy('submit');
try {
const selection = frozen
? {
mode: 'allMatching',
sourceId,
scopeToken: frozen.token,
excludedClientIds: [...choices.keys()],
search: frozen.search,
group: frozen.group,
}
: { mode: 'explicit', sourceId, clientIds: [...choices.keys()] };
const response = await HttpUtil.post<{ jobId: string }>(
'/panel/api/clients/bulkAttach',
{ inboundIds: targets, selection },
{ headers: { 'Content-Type': 'application/json' }, silent: true },
);
if (!response?.success || !response.obj?.jobId) {
messages.error(response?.msg || t('somethingWentWrong'));
return;
}
const statusURL = '/panel/api/clients/bulkAttach/' + encodeURIComponent(response.obj.jobId);
let result: AttachResult | undefined;
let failedPolls = 0;
while (!result) {
const status = await HttpUtil.get<{
running: boolean;
result?: AttachResult;
error?: string;
}>(statusURL, undefined, { silent: true });
if (!status?.success) {
if (++failedPolls < 3) {
await PromiseUtil.sleep(1000);
continue;
}
messages.error(status?.msg || t('somethingWentWrong'));
return;
}
failedPolls = 0;
if (!status.obj?.running) {
if (!status.obj?.result) {
messages.error(status.obj?.error || t('somethingWentWrong'));
return;
}
result = status.obj.result;
} else {
await PromiseUtil.sleep(1000);
}
}
const { attached, skipped, errors } = result;
if (errors > 0)
messages.warning(
t('pages.inbounds.attachClientsResultMixed', {
attached,
skipped,
errors,
}),
);
else messages.success(t('pages.inbounds.attachClientsResult', { attached, skipped }));
onAttached?.();
onClose();
} finally {
action.current = false;
setBusy(undefined);
}
}
const columns: ColumnsType<Candidate> = [
{ title: t('pages.inbounds.email'), dataIndex: 'email', ellipsis: true },
sourceId
? { title: t('comment'), dataIndex: 'comment', ellipsis: true }
: { title: t('pages.clients.group'), dataIndex: 'group', ellipsis: true },
{
title: t('enable'),
key: 'status',
render: (_, row) =>
row.alreadyAttached ? (
<Tag>{t('pages.inbounds.attachExistingStatusAttached')}</Tag>
) : row.enable ? (
<Tag color="success">{t('enable')}</Tag>
) : (
<Tag>{t('pages.inbounds.attachClientsStatusDisabled')}</Tag>
),
},
];
const label = formatInboundLabel(inbound.tag, inbound.remark);
const targetOptions = sourceInbounds
?.filter((item) => item.id !== sourceId && isInboundMultiUser(item))
.map((item) => ({
value: item.id,
label: formatInboundLabel(item.tag, item.remark),
}));
const lastExclusionPage = Math.max(1, Math.ceil(choices.size / 10));
const currentExclusionPage = Math.min(exclusionPage, lastExclusionPage);
const exclusions = frozen
? [...choices].slice((currentExclusionPage - 1) * 10, currentExclusionPage * 10)
: [];
return (
<Modal
open
title={t(
sourceId ? 'pages.inbounds.attachClientsTitle' : 'pages.inbounds.attachExistingTitle',
{ remark: label },
)}
width={720}
onCancel={() => {
if (!action.current) onClose();
}}
onOk={submit}
closable={!busy}
keyboard={!busy}
okText={t('pages.inbounds.attachClients')}
cancelText={t('cancel')}
okButtonProps={{
loading: busy === 'submit',
disabled: !!busy || loading || !!loadError || !targets.length || selected <= 0,
}}
cancelButtonProps={{ disabled: !!busy }}
>
{holder}
<Typography.Paragraph type="secondary">
{t(sourceId ? 'pages.inbounds.attachClientsDesc' : 'pages.inbounds.attachExistingDesc', {
count: rows?.eligible ?? 0,
})}
</Typography.Paragraph>
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
{targetOptions &&
(targetOptions.length ? (
<Select
mode="multiple"
maxCount={100}
tagRender={selectTagRender}
style={{ width: '100%' }}
aria-label={t('pages.inbounds.attachClientsTargets')}
placeholder={t('pages.inbounds.attachClientsTargets')}
value={targets}
onChange={changeTargets}
options={targetOptions}
disabled={!!busy}
showSearch={{ optionFilterProp: 'label' }}
/>
) : (
<Alert type="info" title={t('pages.inbounds.attachClientsNoTargets')} />
))}
<Space wrap>
<Input.Search
allowClear
aria-label={t('search')}
value={search}
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
onChange={(e) => {
setLoading(true);
setPage(1);
setSearch(e.target.value);
}}
/>
{!sourceId && (
<AutoComplete
allowClear
aria-label={t('pages.clients.group')}
value={group}
placeholder={t('pages.clients.group')}
style={{ minWidth: 150 }}
options={rows?.groups.map((value) => ({ value })) ?? []}
filterOption={(input, option) =>
option?.value.toLowerCase().includes(input.toLowerCase()) ?? false
}
onChange={(value) => {
setLoading(true);
setPage(1);
setGroup(value);
}}
/>
)}
</Space>
<Space wrap>
<Button
size="small"
onClick={() => {
selectRows(
(rows?.items ?? [])
.filter((row) => !row.alreadyAttached && (!frozen || inFrozenScope(frozen, row)))
.map((row) => row.id),
);
}}
disabled={
!!busy ||
loading ||
!targets.length ||
!rows?.items.some((row) => !row.alreadyAttached)
}
>
{t('pages.inbounds.attachSelectPage')}
</Button>
<Button
size="small"
onClick={selectAll}
disabled={!!busy || loading || !targets.length || !rows?.eligible}
loading={busy === 'freeze'}
aria-pressed={!!frozen}
>
{t('pages.inbounds.attachSelectAllEligible')}
</Button>
<Button size="small" onClick={clear} disabled={!!busy || (!choices.size && !frozen)}>
{t('pages.inbounds.attachClearSelection')}
</Button>
<Typography.Text role="status" type="secondary">
{t('pages.inbounds.attachClientsSelectedCount', {
selected,
total: frozen?.eligible ?? rows?.eligible ?? 0,
})}
</Typography.Text>
</Space>
{loadError && <Alert type="error" title={loadError} />}
{!sourceId && !loading && !search && !group && rows?.total === 0 && (
<Alert type="info" title={t('pages.inbounds.attachExistingNoClients')} />
)}
<section aria-label={t('pages.inbounds.attachClientsSelectLabel')}>
<Table<Candidate>
size="small"
rowKey="id"
columns={columns}
loading={loading}
dataSource={rows?.items ?? []}
virtual
scroll={{ x: 620, y: 280 }}
pagination={{
current: page,
total: rows?.total ?? 0,
pageSize: PAGE_SIZE,
showSizeChanger: false,
onChange: (next) => {
if (page !== next) {
setLoading(true);
setPage(next);
}
},
}}
rowSelection={{
selectedRowKeys: (rows?.items ?? [])
.filter(
(row) =>
!row.alreadyAttached &&
(frozen
? inFrozenScope(frozen, row) && !choices.has(row.id)
: choices.has(row.id)),
)
.map((row) => row.id),
onChange: selectRows,
getCheckboxProps: (row) => ({
disabled:
!!busy ||
loading ||
!targets.length ||
row.alreadyAttached ||
(!!frozen && !inFrozenScope(frozen, row)),
'aria-label': row.email,
}),
}}
/>
</section>
{exclusions.length > 0 && (
<Space orientation="vertical">
<Typography.Text>{t('pages.inbounds.attachExcludedClients')}</Typography.Text>
<Space wrap>
{exclusions.map(([id, email]) => (
<Button
key={id}
size="small"
disabled={!!busy}
onClick={() =>
setChoices((current) => {
const next = new Map(current);
next.delete(id);
return next;
})
}
>
{t('pages.inbounds.attachRestoreClient', { email })}
</Button>
))}
<Button size="small" disabled={!!busy} onClick={() => setChoices(new Map())}>
{t('pages.inbounds.attachClearExclusions')}
</Button>
</Space>
{lastExclusionPage > 1 && (
<Pagination
size="small"
current={currentExclusionPage}
pageSize={10}
total={choices.size}
showSizeChanger={false}
onChange={setExclusionPage}
/>
)}
</Space>
)}
</Space>
</Modal>
);
}
@@ -1,13 +1,5 @@
import { useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, Input, Modal, Select, Space, Table, Tag, Typography, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { selectTagRender } from '@/components/form';
import { HttpUtil } from '@/utils';
import { formatInboundLabel } from '@/lib/inbounds/label';
import { coerceInboundJsonField, type DBInbound } from '@/models/dbinbound';
import { isInboundMultiUser } from '../list';
import type { DBInbound } from '@/models/dbinbound';
import AttachClientPickerModal from './AttachClientPickerModal';
interface AttachClientsModalProps {
open: boolean;
@@ -17,32 +9,6 @@ interface AttachClientsModalProps {
onAttached?: () => void;
}
interface BulkAttachResult {
attached?: 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 AttachClientsModal({
open,
source,
@@ -50,174 +16,14 @@ export default function AttachClientsModal({
onClose,
onAttached,
}: AttachClientsModalProps) {
const { t } = useTranslation();
const [messageApi, messageContextHolder] = message.useMessage();
const [targetIds, setTargetIds] = useState<number[]>([]);
const [saving, setSaving] = useState(false);
const [clientRows, setClientRows] = useState<ClientRow[]>([]);
const [selectedEmails, setSelectedEmails] = useState<string[]>([]);
const [search, setSearch] = useState('');
// React resets this during render rather than in an effect so the modal's
// first open frame already shows cleared fields.
const openSource = open ? source : null;
const [syncedSource, setSyncedSource] = useState<DBInbound | null>(null);
if (openSource !== syncedSource) {
setSyncedSource(openSource);
if (openSource) {
const rows = readClientRows(openSource.settings);
setClientRows(rows);
setSelectedEmails(rows.map((r) => r.email));
setTargetIds([]);
setSearch('');
}
}
const targetOptions = useMemo(() => {
if (!source) return [];
return (dbInbounds || [])
.filter((ib) => ib.id !== source.id && isInboundMultiUser(ib))
.map((ib) => ({ value: ib.id, label: formatInboundLabel(ib.tag, ib.remark) }));
}, [dbInbounds, source]);
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]);
const columns: ColumnsType<ClientRow> = 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 ? (
<Tag color="success">{t('enable')}</Tag>
) : (
<Tag>{t('pages.inbounds.attachClientsStatusDisabled')}</Tag>
),
},
],
[t],
);
async function submit() {
if (!source || targetIds.length === 0 || selectedEmails.length === 0) return;
setSaving(true);
try {
const msg = await HttpUtil.post(
'/panel/api/clients/bulkAttach',
{ emails: selectedEmails, inboundIds: targetIds },
{ headers: { 'Content-Type': 'application/json' } },
);
if (!msg?.success) {
messageApi.error(msg?.msg || t('somethingWentWrong'));
return;
}
const result = (msg.obj || {}) as BulkAttachResult;
const attached = result.attached?.length ?? 0;
const skipped = result.skipped?.length ?? 0;
const errors = result.errors?.length ?? 0;
if (errors > 0) {
messageApi.warning(
t('pages.inbounds.attachClientsResultMixed', { attached, skipped, errors }),
);
} else {
messageApi.success(t('pages.inbounds.attachClientsResult', { attached, skipped }));
}
onAttached?.();
onClose();
} finally {
setSaving(false);
}
}
if (!open || !source) return null;
return (
<Modal
open={open}
onCancel={onClose}
onOk={submit}
okButtonProps={{
disabled: targetIds.length === 0 || selectedEmails.length === 0,
loading: saving,
}}
okText={t('pages.inbounds.attachClients')}
cancelText={t('cancel')}
title={t('pages.inbounds.attachClientsTitle', {
remark: formatInboundLabel(source?.tag, source?.remark),
})}
width={680}
>
{messageContextHolder}
<Typography.Paragraph type="secondary">
{t('pages.inbounds.attachClientsDesc', { count: clientRows.length })}
</Typography.Paragraph>
<Space orientation="vertical" size="small" style={{ width: '100%', marginBottom: 12 }}>
<Typography.Text strong>{t('pages.inbounds.attachClientsSelectLabel')}</Typography.Text>
<Space style={{ width: '100%', justifyContent: 'space-between' }} wrap>
<Input.Search
allowClear
aria-label={t('search')}
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
style={{ maxWidth: 320 }}
/>
<Typography.Text type="secondary">
{t('pages.inbounds.attachClientsSelectedCount', {
selected: selectedEmails.length,
total: clientRows.length,
})}
</Typography.Text>
</Space>
<Table<ClientRow>
size="small"
rowKey="email"
columns={columns}
dataSource={filteredRows}
pagination={false}
scroll={{ y: 280 }}
rowSelection={{
selectedRowKeys: selectedEmails,
onChange: (keys) => setSelectedEmails(keys as string[]),
preserveSelectedRowKeys: true,
}}
/>
</Space>
{targetOptions.length === 0 ? (
<Alert type="info" showIcon title={t('pages.inbounds.attachClientsNoTargets')} />
) : (
<Select
mode="multiple"
tagRender={selectTagRender}
aria-label={t('pages.inbounds.attachClientsTargets')}
style={{ width: '100%' }}
value={targetIds}
onChange={setTargetIds}
options={targetOptions}
placeholder={t('pages.inbounds.attachClientsTargets')}
showSearch={{ optionFilterProp: 'label' }}
/>
)}
</Modal>
<AttachClientPickerModal
key={source.id}
inbound={source}
sourceInbounds={dbInbounds}
onClose={onClose}
onAttached={onAttached}
/>
);
}
@@ -1,11 +1,5 @@
import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Alert, Input, Modal, Select, Space, Spin, Table, Tag, Typography, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import { HttpUtil } from '@/utils';
import { formatInboundLabel } from '@/lib/inbounds/label';
import type { DBInbound } from '@/models/dbinbound';
import AttachClientPickerModal from './AttachClientPickerModal';
interface AttachExistingClientsModalProps {
open: boolean;
@@ -14,241 +8,19 @@ interface AttachExistingClientsModalProps {
onAttached?: () => void;
}
interface BulkAttachResult {
attached?: string[];
skipped?: string[];
errors?: string[];
}
interface ClientRow {
email: string;
group: string;
enable: boolean;
alreadyAttached: boolean;
}
interface RawClient {
email?: string;
group?: string;
enable?: boolean;
inboundIds?: number[] | null;
}
export default function AttachExistingClientsModal({
open,
target,
onClose,
onAttached,
}: AttachExistingClientsModalProps) {
const { t } = useTranslation();
const [messageApi, messageContextHolder] = message.useMessage();
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [clientRows, setClientRows] = useState<ClientRow[]>([]);
const [selectedEmails, setSelectedEmails] = useState<string[]>([]);
const [search, setSearch] = useState('');
const [groupFilter, setGroupFilter] = useState<string | undefined>(undefined);
// Reset during render, not in an effect, so the first frame is already clean.
const openTarget = open ? target : null;
const [syncedTarget, setSyncedTarget] = useState(openTarget);
if (openTarget !== syncedTarget) {
setSyncedTarget(openTarget);
if (openTarget) {
setLoading(true);
setSearch('');
setGroupFilter(undefined);
}
}
useEffect(() => {
if (!open || !target) return;
let cancelled = false;
HttpUtil.get('/panel/api/clients/list', undefined, { silent: true })
.then((msg) => {
if (cancelled) return;
const list = Array.isArray(msg?.obj) ? (msg.obj as RawClient[]) : [];
const rows: ClientRow[] = list
.map((c) => ({
email: (c?.email || '').trim(),
group: (c?.group || '').trim(),
enable: c?.enable !== false,
alreadyAttached: Array.isArray(c?.inboundIds) && c.inboundIds.includes(target.id),
}))
.filter((r) => r.email);
setClientRows(rows);
setSelectedEmails(rows.filter((r) => !r.alreadyAttached).map((r) => r.email));
})
.finally(() => {
if (!cancelled) setLoading(false);
});
return () => {
cancelled = true;
};
}, [open, target]);
const groupOptions = useMemo(() => {
const set = new Set<string>();
for (const r of clientRows) if (r.group) set.add(r.group);
return [...set].sort((a, b) => a.localeCompare(b)).map((g) => ({ value: g, label: g }));
}, [clientRows]);
const attachableCount = useMemo(
() => clientRows.filter((r) => !r.alreadyAttached).length,
[clientRows],
);
const filteredRows = useMemo(() => {
const q = search.trim().toLowerCase();
return clientRows.filter((r) => {
if (groupFilter && r.group !== groupFilter) return false;
if (!q) return true;
return r.email.toLowerCase().includes(q) || r.group.toLowerCase().includes(q);
});
}, [clientRows, search, groupFilter]);
const columns: ColumnsType<ClientRow> = useMemo(
() => [
{
title: t('pages.inbounds.email'),
dataIndex: 'email',
key: 'email',
ellipsis: true,
},
{
title: t('pages.clients.group'),
dataIndex: 'group',
key: 'group',
width: 150,
ellipsis: true,
render: (group: string) =>
group ? (
<Tag color="geekblue">{group}</Tag>
) : (
<Typography.Text type="secondary">—</Typography.Text>
),
},
{
title: t('enable'),
key: 'status',
width: 140,
render: (_v, row) => {
if (row.alreadyAttached)
return <Tag color="default">{t('pages.inbounds.attachExistingStatusAttached')}</Tag>;
return row.enable ? (
<Tag color="success">{t('enable')}</Tag>
) : (
<Tag>{t('pages.inbounds.attachClientsStatusDisabled')}</Tag>
);
},
},
],
[t],
);
async function submit() {
if (!target || selectedEmails.length === 0) return;
setSaving(true);
try {
const msg = await HttpUtil.post(
'/panel/api/clients/bulkAttach',
{ emails: selectedEmails, inboundIds: [target.id] },
{ headers: { 'Content-Type': 'application/json' } },
);
if (!msg?.success) {
messageApi.error(msg?.msg || t('somethingWentWrong'));
return;
}
const result = (msg.obj || {}) as BulkAttachResult;
const attached = result.attached?.length ?? 0;
const skipped = result.skipped?.length ?? 0;
const errors = result.errors?.length ?? 0;
if (errors > 0) {
messageApi.warning(
t('pages.inbounds.attachClientsResultMixed', { attached, skipped, errors }),
);
} else {
messageApi.success(t('pages.inbounds.attachClientsResult', { attached, skipped }));
}
onAttached?.();
onClose();
} finally {
setSaving(false);
}
}
const noClients = !loading && clientRows.length === 0;
if (!open || !target) return null;
return (
<Modal
open={open}
onCancel={onClose}
onOk={submit}
okButtonProps={{ disabled: selectedEmails.length === 0, loading: saving }}
okText={t('pages.inbounds.attachClients')}
cancelText={t('cancel')}
title={t('pages.inbounds.attachExistingTitle', {
remark: formatInboundLabel(target?.tag, target?.remark),
})}
width={680}
>
{messageContextHolder}
<Typography.Paragraph type="secondary">
{t('pages.inbounds.attachExistingDesc', { count: attachableCount })}
</Typography.Paragraph>
{noClients ? (
<Alert type="info" showIcon title={t('pages.inbounds.attachExistingNoClients')} />
) : (
<Spin aria-live="off" spinning={loading}>
<Space orientation="vertical" size="small" style={{ width: '100%' }}>
<Space style={{ width: '100%', justifyContent: 'space-between' }} wrap>
<Space wrap>
<Input.Search
allowClear
aria-label={t('search')}
value={search}
onChange={(e) => setSearch(e.target.value)}
placeholder={t('pages.inbounds.attachClientsSearchPlaceholder')}
style={{ width: 260 }}
/>
{groupOptions.length > 0 && (
<Select
allowClear
aria-label={t('pages.clients.group')}
value={groupFilter}
onChange={(v) => setGroupFilter(v)}
options={groupOptions}
placeholder={t('pages.clients.group')}
style={{ minWidth: 160 }}
showSearch={{ optionFilterProp: 'label' }}
/>
)}
</Space>
<Typography.Text type="secondary">
{t('pages.inbounds.attachClientsSelectedCount', {
selected: selectedEmails.length,
total: attachableCount,
})}
</Typography.Text>
</Space>
<Table<ClientRow>
size="small"
rowKey="email"
columns={columns}
dataSource={filteredRows}
pagination={false}
scroll={{ y: 280 }}
rowSelection={{
selectedRowKeys: selectedEmails,
onChange: (keys) => setSelectedEmails(keys as string[]),
getCheckboxProps: (row) => ({ disabled: row.alreadyAttached }),
preserveSelectedRowKeys: true,
}}
/>
</Space>
</Spin>
)}
</Modal>
<AttachClientPickerModal
key={target.id}
inbound={target}
onClose={onClose}
onAttached={onAttached}
/>
);
}
+203 -21
View File
@@ -1,43 +1,225 @@
import { describe, expect, it } from 'vitest';
import { screen } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { fireEvent, screen, waitFor } from '@testing-library/react';
import AttachClientsModal from '@/pages/inbounds/clients/AttachClientsModal';
import AttachExistingClientsModal from '@/pages/inbounds/clients/AttachExistingClientsModal';
import { DBInbound } from '@/models/dbinbound';
import { HttpUtil } from '@/utils';
import { renderWithProviders } from './test-utils';
function sourceInbound() {
function inbound(id: number) {
return new DBInbound({
id: 7,
id,
port: 443,
listen: '',
protocol: 'vless',
remark: 'edge',
enable: true,
settings: JSON.stringify({
clients: [
{ id: 'uuid-1', email: 'alice@test' },
{ id: 'uuid-2', email: 'bob@test' },
],
decryption: 'none',
}),
streamSettings: JSON.stringify({ network: 'tcp', security: 'none' }),
settings: '{"clients":[{"email":"not-from-api"}]}',
streamSettings: '',
sniffing: '',
});
}
describe('AttachClientsModal', () => {
it('lists the source clients, selected, when first mounted already open', async () => {
function candidate(id: number, email: string, alreadyAttached = false, inScope = true) {
return {
id,
email,
alreadyAttached,
inScope,
enable: true,
group: 'fixture',
comment: '',
};
}
const alice = candidate(1, 'alice@test');
const bob = candidate(119, 'bob@test');
const attached = candidate(2, 'attached@test', true);
const page = {
items: [alice, attached],
eligible: 9999,
total: 10000,
groups: ['fixture'],
};
const url = '/panel/api/clients/attachCandidates';
afterEach(() => vi.restoreAllMocks());
describe('inbound client attachment picker', () => {
it('loads source membership from the paged API without decoding inbound settings', async () => {
const get = vi.spyOn(HttpUtil, 'get').mockResolvedValue({ success: true, obj: page } as never);
renderWithProviders(
<AttachClientsModal open source={sourceInbound()} dbInbounds={[]} onClose={() => {}} />,
<AttachClientsModal open source={inbound(7)} dbInbounds={[]} onClose={() => {}} />,
);
expect(await screen.findByText('alice@test')).toBeTruthy();
expect(screen.queryByText('not-from-api')).toBeNull();
expect(get).toHaveBeenCalledWith(
url,
expect.objectContaining({ sourceId: 7, page: 1 }),
expect.anything(),
);
});
it('submits a compact frozen selection with exclusions retained across searches', async () => {
const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (path, raw) => {
if (path.endsWith('/job-123'))
return {
success: true,
obj: {
running: false,
result: { attached: 9997, skipped: 0, errors: 0 },
},
} as never;
const p = raw as { freeze?: boolean; search?: string };
return {
success: true,
obj: p.freeze
? { ...page, items: [], scopeToken: 'frozen-token', maxId: 10000 }
: p.search
? { ...page, items: [bob], total: 1 }
: page,
} as never;
});
const post = vi.spyOn(HttpUtil, 'post').mockResolvedValue({
success: true,
obj: { jobId: 'job-123' },
} as never);
const close = vi.fn();
renderWithProviders(<AttachExistingClientsModal open target={inbound(8)} onClose={close} />);
await screen.findByText('alice@test');
const aliceBox = screen.getByRole('checkbox', {
name: 'alice@test',
}) as HTMLInputElement;
expect(aliceBox.checked).toBe(false);
expect(
(
screen.getByRole('checkbox', {
name: 'attached@test',
}) as HTMLInputElement
).disabled,
).toBe(true);
fireEvent.click(screen.getByRole('button', { name: /select all eligible clients/i }));
await waitFor(() => expect(aliceBox.checked).toBe(true));
fireEvent.click(aliceBox);
fireEvent.change(screen.getByRole('searchbox', { name: /search/i }), {
target: { value: 'bob' },
});
await screen.findByText('bob@test');
fireEvent.click(screen.getByRole('checkbox', { name: 'bob@test' }));
expect(screen.getByRole('button', { name: /restore alice@test/i })).toBeTruthy();
expect(get).toHaveBeenCalledWith(
url,
expect.objectContaining({ inboundIds: '8', freeze: true }),
expect.anything(),
);
expect(await screen.findByText('alice@test')).toBeTruthy();
expect(screen.getByText('bob@test')).toBeTruthy();
const submit = screen.getByRole('button', { name: /^attach clients to/i });
fireEvent.click(submit);
fireEvent.click(submit);
await waitFor(() => expect(close).toHaveBeenCalledOnce());
expect(post).toHaveBeenCalledExactlyOnceWith(
'/panel/api/clients/bulkAttach',
{
inboundIds: [8],
selection: {
mode: 'allMatching',
sourceId: 0,
scopeToken: 'frozen-token',
excludedClientIds: [1, 119],
search: '',
group: '',
},
},
expect.anything(),
);
});
it('freezes Select All to the active search and keeps other rows out of the selection', async () => {
const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (path, raw) => {
if (path.endsWith('/job-9'))
return {
success: true,
obj: {
running: false,
result: { attached: 1, skipped: 0, errors: 0 },
},
} as never;
const p = raw as {
freeze?: boolean;
search?: string;
scopeSearch?: string;
};
if (p.freeze)
return {
success: true,
obj: {
...page,
items: [],
eligible: 1,
scopeToken: 'bob-token',
maxId: 10000,
},
} as never;
if (p.search)
return {
success: true,
obj: { ...page, items: [bob], total: 1 },
} as never;
const outside = candidate(1, 'alice@test', false, p.scopeSearch !== 'bob');
return {
success: true,
obj: { ...page, items: [outside, bob] },
} as never;
});
const post = vi.spyOn(HttpUtil, 'post').mockResolvedValue({
success: true,
obj: { jobId: 'job-9' },
} as never);
const close = vi.fn();
renderWithProviders(<AttachExistingClientsModal open target={inbound(8)} onClose={close} />);
await screen.findByText('alice@test');
const searchBox = screen.getByRole('searchbox', { name: /search/i });
fireEvent.change(searchBox, { target: { value: 'bob' } });
await waitFor(() => expect(screen.queryByText('alice@test')).toBeNull());
fireEvent.click(screen.getByRole('button', { name: /select all eligible clients/i }));
await waitFor(() =>
expect((screen.getByRole('checkbox', { name: 'bob@test' }) as HTMLInputElement).checked).toBe(
true,
),
);
expect(get).toHaveBeenCalledWith(
url,
expect.objectContaining({ inboundIds: '8', freeze: true, search: 'bob' }),
expect.anything(),
);
const boxes = screen.getAllByRole('checkbox') as HTMLInputElement[];
const rowBoxes = boxes.slice(1);
expect(rowBoxes).toHaveLength(2);
expect(rowBoxes.every((b) => b.checked)).toBe(true);
fireEvent.change(searchBox, { target: { value: '' } });
const aliceBox = (await screen.findByRole('checkbox', {
name: 'alice@test',
})) as HTMLInputElement;
expect(aliceBox.checked).toBe(false);
expect(aliceBox.disabled).toBe(true);
expect((screen.getByRole('checkbox', { name: 'bob@test' }) as HTMLInputElement).checked).toBe(
true,
);
fireEvent.click(screen.getByRole('button', { name: /^attach clients to/i }));
await waitFor(() => expect(close).toHaveBeenCalledOnce());
expect(post).toHaveBeenCalledExactlyOnceWith(
'/panel/api/clients/bulkAttach',
{
inboundIds: [8],
selection: {
mode: 'allMatching',
sourceId: 0,
scopeToken: 'bob-token',
excludedClientIds: [],
search: 'bob',
group: '',
},
},
expect.anything(),
);
});
});
+28 -2
View File
@@ -3,6 +3,7 @@ package controller
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
@@ -53,6 +54,7 @@ func NewClientController(g *gin.RouterGroup) *ClientController {
func (a *ClientController) initRouter(g *gin.RouterGroup) {
g.GET("/list", a.list)
g.GET("/list/paged", a.listPaged)
g.GET("/attachCandidates", a.attachCandidates)
g.GET("/get", a.get)
g.GET("/get/:email", a.get)
g.GET("/get/subId/:subId", a.getBySubId)
@@ -88,6 +90,7 @@ func (a *ClientController) initRouter(g *gin.RouterGroup) {
g.POST("/bulkDel", a.bulkDelete)
g.POST("/bulkCreate", a.bulkCreate)
g.POST("/bulkAttach", a.bulkAttach)
g.GET("/bulkAttach/:id", a.attachStatus)
g.POST("/bulkDetach", a.bulkDetach)
g.POST("/bulkResetTraffic", a.bulkResetTraffic)
g.POST("/resetTraffic/:email", a.resetTrafficByEmail)
@@ -138,6 +141,20 @@ func (a *ClientController) listPaged(c *gin.Context) {
jsonObj(c, resp, nil)
}
func (a *ClientController) attachCandidates(c *gin.Context) {
var params service.AttachCandidateParams
if err := c.ShouldBindQuery(&params); err != nil {
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
return
}
result, err := a.clientService.ListAttachCandidates(c.Request.Context(), params)
if err != nil {
jsonMsg(c, I18nWeb(c, "pages.inbounds.toasts.obtain"), err)
return
}
jsonObj(c, result, nil)
}
func (a *ClientController) buildClientPayload(rec *model.ClientRecord) (gin.H, error) {
inboundIds, err := a.clientService.GetInboundIdsForRecord(rec.Id)
if err != nil {
@@ -426,8 +443,9 @@ type bulkDeleteRequest struct {
}
type bulkAttachRequest struct {
Emails []string `json:"emails"`
InboundIds []int `json:"inboundIds"`
Emails []string `json:"emails"`
InboundIds []int `json:"inboundIds"`
Selection *service.AttachSelection `json:"selection,omitempty"`
}
func (a *ClientController) bulkAttach(c *gin.Context) {
@@ -436,6 +454,14 @@ func (a *ClientController) bulkAttach(c *gin.Context) {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
if req.Selection != nil {
if len(req.Emails) > 0 {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), fmt.Errorf("use either emails or an attachment selection"))
return
}
a.beginBulkAttach(c, req.InboundIds, *req.Selection)
return
}
result, needRestart, err := a.clientService.BulkAttach(&a.inboundService, req.Emails, req.InboundIds)
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
@@ -0,0 +1,118 @@
package controller
import (
"context"
"errors"
"sync"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/mhsanaei/3x-ui/v3/internal/util/common"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
// Attachment jobs belong to the same administrator-only API as bulkAttach.
// Keep a bounded in-memory history of results and run one picker job at a time.
type attachJobStore struct {
mu sync.Mutex
running bool
jobs map[string]AttachJobStatus
}
type AttachJobStatus struct {
Running bool `json:"running" example:"false"`
Result *service.AttachSelectionResult `json:"result,omitempty"`
Error string `json:"error,omitempty"`
ended time.Time
}
var attachJobs attachJobStore
func (s *attachJobStore) start(run func() (*service.AttachSelectionResult, error)) (string, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.running {
return "", errors.New("another client attachment is running")
}
if s.jobs == nil {
s.jobs = make(map[string]AttachJobStatus)
}
cutoff := time.Now().Add(-15 * time.Minute)
var oldestID string
var oldest time.Time
for id, status := range s.jobs {
if status.ended.Before(cutoff) {
delete(s.jobs, id)
continue
}
if oldestID == "" || status.ended.Before(oldest) {
oldestID, oldest = id, status.ended
}
}
if len(s.jobs) >= 32 {
delete(s.jobs, oldestID)
}
id := uuid.NewString()
s.jobs[id] = AttachJobStatus{Running: true}
s.running = true
common.GoRecover("client-attachment", func() {
status := AttachJobStatus{Error: "client attachment interrupted"}
defer func() {
s.mu.Lock()
defer s.mu.Unlock()
status.ended = time.Now()
s.jobs[id] = status
s.running = false
}()
result, err := run()
if err != nil {
status.Error = err.Error()
return
}
status.Error = ""
status.Result = result
})
return id, nil
}
func (s *attachJobStore) get(id string) (AttachJobStatus, bool) {
s.mu.Lock()
defer s.mu.Unlock()
status, ok := s.jobs[id]
if !status.Running && time.Since(status.ended) > 15*time.Minute {
delete(s.jobs, id)
return AttachJobStatus{}, false
}
return status, ok
}
func (a *ClientController) beginBulkAttach(c *gin.Context, targets []int, selection service.AttachSelection) {
id, err := attachJobs.start(func() (*service.AttachSelectionResult, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
result, restart, err := a.clientService.BulkAttachSelection(ctx, &a.inboundService, targets, selection)
if restart {
a.xrayService.SetToNeedRestart()
}
if err == nil {
notifyClientsChanged()
}
return result, err
})
if err != nil {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), err)
return
}
jsonObj(c, gin.H{"jobId": id}, nil)
}
func (a *ClientController) attachStatus(c *gin.Context) {
status, ok := attachJobs.get(c.Param("id"))
if !ok {
jsonMsg(c, I18nWeb(c, "somethingWentWrong"), errors.New("client attachment status unavailable"))
return
}
jsonObj(c, status, nil)
}
@@ -0,0 +1,51 @@
package controller
import (
"errors"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/web/service"
)
func TestAttachJobStorePublishesStatusAndPreventsOverlap(t *testing.T) {
var store attachJobStore
block := make(chan struct{})
id, err := store.start(func() (*service.AttachSelectionResult, error) {
<-block
return &service.AttachSelectionResult{Attached: 9997, Skipped: 1, Errors: 2}, nil
})
if err != nil {
t.Fatal(err)
}
if status, ok := store.get(id); !ok || !status.Running {
t.Fatalf("accepted job status = %#v, found=%t", status, ok)
}
if _, err := store.start(nil); err == nil {
t.Fatal("overlapping job was accepted")
}
close(block)
wait := func(id string) AttachJobStatus {
t.Helper()
for deadline := time.Now().Add(time.Second); time.Now().Before(deadline); {
if status, ok := store.get(id); ok && !status.Running {
return status
}
time.Sleep(time.Millisecond)
}
t.Fatal("job did not finish")
return AttachJobStatus{}
}
result := wait(id).Result
if result == nil || result.Attached != 9997 || result.Skipped != 1 || result.Errors != 2 {
t.Fatalf("partial result lost: %#v", result)
}
id, err = store.start(func() (*service.AttachSelectionResult, error) { return nil, errors.New("stale selection") })
if err != nil {
t.Fatal(err)
}
if status := wait(id); status.Result != nil || status.Error != "stale selection" {
t.Fatalf("failed result lost: %#v", status)
}
}
@@ -0,0 +1,319 @@
package service
import (
"context"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
"fmt"
"hash"
"slices"
"strconv"
"strings"
"gorm.io/gorm"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
const attachCandidatePageSize = 100
type AttachCandidateParams struct {
SourceID int `form:"sourceId"`
Targets string `form:"inboundIds"`
Page int `form:"page"`
Search string `form:"search"`
Group string `form:"group"`
Freeze bool `form:"freeze"`
// The filter a frozen selection was taken under, which marks rows inScope.
ScopeSearch string `form:"scopeSearch"`
ScopeGroup string `form:"scopeGroup"`
}
type AttachCandidate struct {
ID int `json:"id" gorm:"column:id" example:"1"`
Email string `json:"email" example:"alice@example.test"`
Group string `json:"group" example:"staff"`
Comment string `json:"comment" example:"Example client"`
Enable bool `json:"enable" example:"true"`
AlreadyAttached bool `json:"alreadyAttached" example:"false"`
InScope bool `json:"inScope" example:"true"`
}
type AttachCandidatePage struct {
Items []AttachCandidate `json:"items"`
Total int64 `json:"total" example:"120"`
Eligible int64 `json:"eligible" example:"118"`
Groups []string `json:"groups" example:"[\"staff\"]"`
ScopeToken string `json:"scopeToken,omitempty"`
MaxID int `json:"maxId,omitempty"`
}
type AttachSelection struct {
Mode string `json:"mode"`
SourceID int `json:"sourceId"`
ClientIDs []int `json:"clientIds"`
ExcludedClientIDs []int `json:"excludedClientIds"`
ScopeToken string `json:"scopeToken"`
Search string `json:"search"`
Group string `json:"group"`
}
type AttachSelectionResult struct {
Attached int `json:"attached" example:"9997"`
Skipped int `json:"skipped" example:"0"`
Errors int `json:"errors" example:"0"`
}
func attachScope(db *gorm.DB, sourceID int, ids []int) ([]int, error) {
if len(ids) > 100 || sourceID < 0 || (sourceID == 0 && len(ids) == 0) {
return nil, fmt.Errorf("invalid client attachment scope")
}
targets := uniqueInts(ids)
slices.Sort(targets)
inbounds := slices.Clone(targets)
if sourceID > 0 {
if slices.Contains(targets, sourceID) {
return nil, fmt.Errorf("source inbound cannot be a target")
}
inbounds = append(inbounds, sourceID)
}
var rows []model.Inbound
if err := db.Select("id", "protocol").Where("id IN ?", inbounds).Find(&rows).Error; err != nil {
return nil, err
}
if len(rows) != len(inbounds) {
return nil, fmt.Errorf("an inbound in the attachment scope no longer exists")
}
for _, row := range rows {
switch row.Protocol {
case model.VMESS, model.VLESS, model.Trojan, model.Shadowsocks, model.Hysteria,
model.MTProto, model.WireGuard, model.AmneziaWG, model.TUIC, model.MASQUE:
default:
return nil, fmt.Errorf("inbound %d does not support attaching clients", row.Id)
}
}
return targets, nil
}
func attachCandidates(db *gorm.DB, sourceID int) *gorm.DB {
q := db.Table("clients AS c").Where("c.email <> ''")
if sourceID > 0 {
q = q.Where("EXISTS (SELECT 1 FROM client_inbounds AS src WHERE src.client_id = c.id AND src.inbound_id = ?)", sourceID)
}
return q
}
const attachedToTargetsSQL = "(SELECT COUNT(*) FROM client_inbounds AS dst WHERE dst.client_id = c.id AND dst.inbound_id IN ?) = ?"
func eligibleAttachCandidates(q *gorm.DB, targets []int) *gorm.DB {
if len(targets) > 0 {
return q.Where("NOT ("+attachedToTargetsSQL+")", targets, len(targets))
}
return q
}
// attachFilter is the search and group predicate of a candidate page or a frozen scope.
func attachFilter(sourceID int, search, group string) (string, []any) {
var clauses []string
var args []any
if sourceID == 0 && group != "" {
clauses = append(clauses, "c.group_name = ?")
args = append(args, group)
}
if search = strings.TrimSpace(search); search != "" {
col := "c.group_name"
if sourceID > 0 {
col = "c.comment"
}
const like = " LIKE ? ESCAPE '\\'"
predicates := []string{"LOWER(c.email)" + like, "LOWER(" + col + ")" + like}
pattern := "%" + escapeLikeLiteral(strings.ToLower(search)) + "%"
args = append(args, pattern, pattern)
for _, variant := range caseVariants(search) {
pattern := "%" + escapeLikeLiteral(variant) + "%"
predicates = append(predicates, "c.email"+like, col+like)
args = append(args, pattern, pattern)
}
clauses = append(clauses, "("+strings.Join(predicates, " OR ")+")")
}
return strings.Join(clauses, " AND "), args
}
func filteredAttachCandidates(q *gorm.DB, sourceID int, search, group string) *gorm.DB {
if filter, args := attachFilter(sourceID, search, group); filter != "" {
return q.Where(filter, args...)
}
return q
}
func writeAttachID(h hash.Hash, id int) {
var buf [8]byte
binary.BigEndian.PutUint64(buf[:], uint64(id))
_, _ = h.Write(buf[:])
}
func attachScopeHash(sourceID int, targets []int) hash.Hash {
h := sha256.New()
writeAttachID(h, sourceID)
writeAttachID(h, len(targets))
for _, id := range targets {
writeAttachID(h, id)
}
return h
}
func (s *ClientService) ListAttachCandidates(ctx context.Context, p AttachCandidateParams) (*AttachCandidatePage, error) {
if p.Page < 0 || p.Page > 1_000_000 || len(p.Search) > 256 || len(p.Group) > 256 ||
len(p.ScopeSearch) > 256 || len(p.ScopeGroup) > 256 {
return nil, fmt.Errorf("invalid client attachment page")
}
db := database.GetDB().WithContext(ctx)
var ids []int
if p.Targets != "" {
for part := range strings.SplitSeq(p.Targets, ",") {
id, err := strconv.Atoi(part)
if err != nil || id < 1 || len(ids) >= 100 {
return nil, fmt.Errorf("invalid attachment target ID")
}
ids = append(ids, id)
}
}
targets, err := attachScope(db, p.SourceID, ids)
if err != nil {
return nil, err
}
resp := &AttachCandidatePage{Items: []AttachCandidate{}, Groups: []string{}}
eligible := eligibleAttachCandidates(attachCandidates(db, p.SourceID), targets)
if p.Freeze {
if len(targets) == 0 {
return nil, fmt.Errorf("select attachment targets first")
}
h := attachScopeHash(p.SourceID, targets)
rows, err := filteredAttachCandidates(eligible, p.SourceID, p.Search, p.Group).Select("c.id").Order("c.id").Rows()
if err != nil {
return nil, err
}
defer rows.Close()
for rows.Next() {
var id int
if err := rows.Scan(&id); err != nil {
return nil, err
}
writeAttachID(h, id)
resp.Eligible++
resp.MaxID = id
}
if err := rows.Err(); err != nil {
return nil, err
}
writeAttachID(h, resp.MaxID)
resp.ScopeToken = strconv.Itoa(resp.MaxID) + "." + hex.EncodeToString(h.Sum(nil))
return resp, nil
}
if err := eligible.Count(&resp.Eligible).Error; err != nil {
return nil, err
}
if p.SourceID == 0 {
if err := attachCandidates(db, 0).Where("c.group_name <> ''").
Distinct("c.group_name").Order("c.group_name").Limit(100).Pluck("c.group_name", &resp.Groups).Error; err != nil {
return nil, err
}
}
filtered := filteredAttachCandidates(attachCandidates(db, p.SourceID), p.SourceID, p.Search, p.Group)
if err := filtered.Count(&resp.Total).Error; err != nil {
return nil, err
}
columns, args := "c.id, c.email, c.group_name AS \"group\", c.comment, c.enable, ", []any{}
if len(targets) == 0 {
columns += "false AS already_attached, "
} else {
columns += attachedToTargetsSQL + " AS already_attached, "
args = append(args, targets, len(targets))
}
if scope, scopeArgs := attachFilter(p.SourceID, p.ScopeSearch, p.ScopeGroup); scope == "" {
columns += "true AS in_scope"
} else {
columns += "(" + scope + ") AS in_scope"
args = append(args, scopeArgs...)
}
filtered = filtered.Select(columns, args...)
err = filtered.Order("c.id").Offset(max(0, p.Page-1) * attachCandidatePageSize).
Limit(attachCandidatePageSize).Scan(&resp.Items).Error
return resp, err
}
func (s *ClientService) BulkAttachSelection(ctx context.Context, inboundSvc *InboundService, targets []int, selection AttachSelection) (*AttachSelectionResult, bool, error) {
db := database.GetDB().WithContext(ctx)
targets, err := attachScope(db, selection.SourceID, targets)
if err != nil {
return nil, false, err
}
if len(targets) == 0 {
return nil, false, fmt.Errorf("select attachment targets first")
}
stale := fmt.Errorf("client attachment selection changed; clear the selection and select clients again")
q := eligibleAttachCandidates(attachCandidates(db, selection.SourceID), targets)
var records []*model.ClientRecord
switch selection.Mode {
case "explicit":
if len(selection.ClientIDs) == 0 || len(selection.ClientIDs) > 50_000 || selection.ScopeToken != "" ||
len(selection.ExcludedClientIDs) > 0 || selection.Search != "" || selection.Group != "" {
return nil, false, fmt.Errorf("invalid explicit client attachment selection")
}
ids := uniqueInts(selection.ClientIDs)
for _, chunk := range chunkInts(ids, 400) {
var part []*model.ClientRecord
if err := q.Session(&gorm.Session{}).Where("c.id IN ?", chunk).Find(&part).Error; err != nil {
return nil, false, err
}
if len(part) != len(chunk) {
return nil, false, stale
}
records = append(records, part...)
}
case "allMatching":
cutoff, digest, ok := strings.Cut(selection.ScopeToken, ".")
maxID, parseErr := strconv.Atoi(cutoff)
if !ok || parseErr != nil || maxID < 0 || len(digest) != sha256.Size*2 || len(selection.ClientIDs) > 0 ||
len(selection.ExcludedClientIDs) > 50_000 || len(selection.Search) > 256 || len(selection.Group) > 256 {
return nil, false, fmt.Errorf("invalid all-clients attachment selection")
}
excluded := make(map[int]struct{}, len(selection.ExcludedClientIDs))
for _, id := range selection.ExcludedClientIDs {
excluded[id] = struct{}{}
}
h := attachScopeHash(selection.SourceID, targets)
// Find runs the model's read hooks. The cutoff excludes newer clients.
var eligibleRecords []*model.ClientRecord
q = filteredAttachCandidates(q, selection.SourceID, selection.Search, selection.Group)
if err := q.Where("c.id <= ?", maxID).Order("c.id").Find(&eligibleRecords).Error; err != nil {
return nil, false, err
}
records = eligibleRecords[:0]
for _, record := range eligibleRecords {
writeAttachID(h, record.Id)
if _, skip := excluded[record.Id]; skip {
delete(excluded, record.Id)
continue
}
records = append(records, record)
}
writeAttachID(h, maxID)
if len(excluded) > 0 || hex.EncodeToString(h.Sum(nil)) != digest {
return nil, false, stale
}
default:
return nil, false, fmt.Errorf("invalid client attachment selection mode")
}
if err := ctx.Err(); err != nil {
return nil, false, err
}
result, restart, err := s.bulkAttachRecords(inboundSvc, records, targets, &BulkAttachResult{})
if err != nil {
return nil, restart, err
}
return &AttachSelectionResult{Attached: len(result.Attached), Skipped: len(result.Skipped), Errors: len(result.Errors)}, restart, nil
}
@@ -0,0 +1,278 @@
package service
import (
"context"
"fmt"
"slices"
"strconv"
"testing"
"time"
"github.com/mhsanaei/3x-ui/v3/internal/database"
"github.com/mhsanaei/3x-ui/v3/internal/database/model"
)
func TestAttachCandidatesSelection(t *testing.T) {
setupBulkDB(t)
testAttachCandidatesSelection(t)
}
func TestAttachCandidatesSelectionPostgres(t *testing.T) {
durablePostgresDB(t)
testAttachCandidatesSelection(t)
}
func testAttachCandidatesSelection(t *testing.T) {
t.Helper()
db := database.GetDB()
ctx := context.Background()
svc := &ClientService{}
suffix := time.Now().UnixNano()
source := durableTestInbound(nil, fmt.Sprintf("attach-source-%d", suffix), 42541)
target := durableTestInbound(nil, fmt.Sprintf("attach-target-%d", suffix), 42542)
if err := db.Create(source).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(target).Error; err != nil {
t.Fatal(err)
}
email := func(i int) string { return fmt.Sprintf("candidate-%d-%04d@x", suffix, i) }
clients := make([]model.Client, 121)
for i := range clients {
clients[i] = model.Client{
Email: email(i), SubID: fmt.Sprintf("test%d", i), Enable: i != 2, Group: "fixture",
ID: fmt.Sprintf("11111111-1111-4111-8111-%012d", i),
}
}
clients[119].Comment = "Журнал match_% only"
keepAlive := model.KeepAliveValue("19")
clients[3].KeepAlive = &keepAlive
if err := svc.SyncInbound(nil, source.Id, clients); err != nil {
t.Fatal(err)
}
if err := svc.SyncInbound(nil, target.Id, clients[:1]); err != nil {
t.Fatal(err)
}
p := AttachCandidateParams{SourceID: source.Id, Targets: strconv.Itoa(target.Id)}
first, err := svc.ListAttachCandidates(ctx, p)
if err != nil || len(first.Items) != 100 || first.Total != 121 || first.Eligible != 120 || !first.Items[0].AlreadyAttached || first.Items[2].Enable {
t.Fatalf("candidate first page = %+v, err=%v", first, err)
}
p.Page = 2
second, err := svc.ListAttachCandidates(ctx, p)
if err != nil || len(second.Items) != 21 {
t.Fatalf("second page size = %v, err=%v", second, err)
}
search, err := svc.ListAttachCandidates(ctx, AttachCandidateParams{SourceID: source.Id, Targets: p.Targets, Search: "журнал MATCH_%"})
if err != nil || len(search.Items) != 1 || search.Items[0].Email != email(119) {
t.Fatalf("literal source search = %+v, err=%v", search, err)
}
group, err := svc.ListAttachCandidates(ctx, AttachCandidateParams{Targets: p.Targets, Group: "fixture", Search: fmt.Sprintf("candidate-%d", suffix)})
if err != nil || group.Total != 121 || !slices.Contains(group.Groups, "fixture") {
t.Fatalf("group search = %+v, err=%v", group, err)
}
p.Freeze = true
scope, err := svc.ListAttachCandidates(ctx, p)
if err != nil || scope.Eligible != 120 || len(scope.Items) != 0 || scope.ScopeToken == "" {
t.Fatalf("freeze = %+v, err=%v", scope, err)
}
inboundSvc := &InboundService{}
request := AttachSelection{
Mode: "allMatching", SourceID: source.Id, ScopeToken: scope.ScopeToken,
ExcludedClientIDs: []int{first.Items[1].ID, second.Items[0].ID},
}
extra := model.Client{Email: email(121), Enable: true}
if err := svc.ApplyInboundClientDelta(nil, source.Id, []model.Client{extra}, nil); err != nil {
t.Fatal(err)
}
if err := svc.ApplyInboundClientDelta(nil, source.Id, nil, []string{clients[2].Email}); err != nil {
t.Fatal(err)
}
if _, _, err := svc.BulkAttachSelection(ctx, inboundSvc, []int{target.Id}, request); err == nil {
t.Fatal("a client that leaves the frozen scope should invalidate the selection")
}
var linked int64
if err := db.Model(&model.ClientInbound{}).Where("inbound_id = ?", target.Id).Count(&linked).Error; err != nil || linked != 1 {
t.Fatalf("stale selection mutated target: links=%d err=%v", linked, err)
}
if err := svc.ApplyInboundClientDelta(nil, source.Id, clients[2:3], nil); err != nil {
t.Fatal(err)
}
result, _, err := svc.BulkAttachSelection(ctx, inboundSvc, []int{target.Id}, request)
if err != nil || result.Attached != 118 || result.Skipped != 0 || result.Errors != 0 {
t.Fatalf("scoped attach = %+v, err=%v", result, err)
}
got, err := svc.ListForInbound(nil, target.Id)
if err != nil || len(got) != 119 {
t.Fatalf("target has %d clients, err=%v", len(got), err)
}
for _, row := range got {
if row.Email == first.Items[1].Email || row.Email == second.Items[0].Email || row.Email == extra.Email ||
(row.Email == email(2) && row.Enable) {
t.Fatalf("invalid attachment %+v", row)
}
}
reloaded, err := inboundSvc.GetInbound(target.Id)
if err != nil {
t.Fatal(err)
}
configured, err := inboundSvc.GetClients(reloaded)
if err != nil {
t.Fatal(err)
}
i := slices.IndexFunc(configured, func(c model.Client) bool { return c.Email == email(3) })
if i < 0 || configured[i].KeepAlive == nil || *configured[i].KeepAlive != keepAlive {
t.Fatal("bulk attachment discarded the stored client keepalive")
}
explicit := AttachSelection{Mode: "explicit", SourceID: source.Id, ClientIDs: []int{first.Items[1].ID}}
result, _, err = svc.BulkAttachSelection(ctx, inboundSvc, []int{target.Id}, explicit)
if err != nil || result.Attached != 1 {
t.Fatalf("explicit attachment = %+v, err=%v", result, err)
}
}
func TestFrozenAttachSelectionFollowsFilter(t *testing.T) {
setupBulkDB(t)
testFrozenAttachSelectionFollowsFilter(t)
}
func TestFrozenAttachSelectionFollowsFilterPostgres(t *testing.T) {
durablePostgresDB(t)
testFrozenAttachSelectionFollowsFilter(t)
}
func testFrozenAttachSelectionFollowsFilter(t *testing.T) {
t.Helper()
db := database.GetDB()
ctx := context.Background()
svc := &ClientService{}
suffix := time.Now().UnixNano()
source := durableTestInbound(nil, fmt.Sprintf("filter-source-%d", suffix), 42544)
target := durableTestInbound(nil, fmt.Sprintf("filter-target-%d", suffix), 42545)
if err := db.Create(source).Error; err != nil {
t.Fatal(err)
}
if err := db.Create(target).Error; err != nil {
t.Fatal(err)
}
staff := fmt.Sprintf("staff-%d", suffix)
email := func(i int) string { return fmt.Sprintf("filter-%d-%d@x", suffix, i) }
clients := make([]model.Client, 6)
for i := range clients {
clients[i] = model.Client{
Email: email(i), SubID: fmt.Sprintf("filter%d", i), Enable: true, Group: staff,
ID: fmt.Sprintf("22222222-2222-4222-8222-%012d", i),
}
}
clients[1].Group, clients[3].Group = "guests", ""
if err := svc.SyncInbound(nil, source.Id, clients); err != nil {
t.Fatal(err)
}
targets := strconv.Itoa(target.Id)
search := fmt.Sprintf("FILTER-%d", suffix)
scope, err := svc.ListAttachCandidates(ctx, AttachCandidateParams{Targets: targets, Group: staff, Search: search, Freeze: true})
if err != nil || scope.Eligible != 4 {
t.Fatalf("frozen group scope = %+v, err=%v, want the 4 staff clients", scope, err)
}
page, err := svc.ListAttachCandidates(ctx, AttachCandidateParams{Targets: targets, Search: search, ScopeGroup: staff, ScopeSearch: search})
if err != nil || len(page.Items) != 6 {
t.Fatalf("unfiltered page under a frozen scope = %+v, err=%v", page, err)
}
for i, row := range page.Items {
if row.InScope != (i != 1 && i != 3) {
t.Fatalf("row %d %s inScope = %t", i, row.Email, row.InScope)
}
}
inboundSvc := &InboundService{}
request := AttachSelection{Mode: "allMatching", ScopeToken: scope.ScopeToken, ExcludedClientIDs: []int{page.Items[0].ID}}
if _, _, err := svc.BulkAttachSelection(ctx, inboundSvc, []int{target.Id}, request); err == nil {
t.Fatal("a frozen token was accepted without the filter it was taken under")
}
request.Group, request.Search = staff, search
result, _, err := svc.BulkAttachSelection(ctx, inboundSvc, []int{target.Id}, request)
if err != nil || result.Attached != 3 || result.Errors != 0 {
t.Fatalf("filtered attach = %+v, err=%v", result, err)
}
got, err := svc.ListForInbound(nil, target.Id)
if err != nil {
t.Fatal(err)
}
var emails []string
for _, row := range got {
emails = append(emails, row.Email)
}
slices.Sort(emails)
if want := []string{email(2), email(4), email(5)}; !slices.Equal(emails, want) {
t.Fatalf("target clients = %v, want %v", emails, want)
}
}
func BenchmarkAttachCandidateScale(b *testing.B) {
for _, count := range []int{1000, 10000, 50000} {
b.Run(fmt.Sprint(count), func(b *testing.B) {
setupScaleDB(b)
ds := seedScaleDataset(b, count, 1)
db := database.GetDB()
target := durableTestInbound(nil, "attach-scale", 42543)
if err := db.Create(target).Error; err != nil {
b.Fatal(err)
}
svc := &ClientService{}
for _, mode := range []string{"page", "search", "freeze"} {
b.Run(mode, func(b *testing.B) {
p := AttachCandidateParams{SourceID: ds.inboundIds[0], Targets: strconv.Itoa(target.Id), Freeze: mode == "freeze"}
if mode == "search" {
p.Search = ds.emails[count/2]
}
b.ReportAllocs()
for b.Loop() {
result, err := svc.ListAttachCandidates(context.Background(), p)
if err != nil || len(result.Items) > attachCandidatePageSize || result.Eligible != int64(count) {
b.Fatalf("bounded candidate page or eligibility count failed: %v", err)
}
}
})
}
})
}
}
func TestAttachTenThousandClientsScale(t *testing.T) {
setupScaleDB(t)
ds := seedScaleDataset(t, 10_000, 1)
db := database.GetDB()
target := durableTestInbound(nil, "attach-ten-thousand", 42543)
if err := db.Create(target).Error; err != nil {
t.Fatal(err)
}
ctx := context.Background()
svc := &ClientService{}
scope, err := svc.ListAttachCandidates(ctx, AttachCandidateParams{
SourceID: ds.inboundIds[0], Targets: strconv.Itoa(target.Id), Freeze: true,
})
if err != nil {
t.Fatal(err)
}
var excluded []int
excludedEmails := []string{ds.emails[0], ds.emails[5000], ds.emails[9999]}
if err := db.Model(&model.ClientRecord{}).Where("email IN ?", excludedEmails).Pluck("id", &excluded).Error; err != nil {
t.Fatal(err)
}
start := time.Now()
result, _, err := svc.BulkAttachSelection(ctx, &InboundService{}, []int{target.Id}, AttachSelection{
Mode: "allMatching", SourceID: ds.inboundIds[0], ScopeToken: scope.ScopeToken, ExcludedClientIDs: excluded,
})
if err != nil || result.Attached != 9997 || result.Skipped != 0 || result.Errors != 0 {
t.Fatalf("large attachment = %+v, err=%v", result, err)
}
t.Logf("attached 9997 of 10000 clients in %v", time.Since(start))
var links, unexpected int64
query := db.Model(&model.ClientInbound{}).Where("inbound_id = ?", target.Id)
if err := query.Count(&links).Error; err != nil || links != 9997 {
t.Fatalf("target links = %d, err=%v", links, err)
}
if err := query.Where("client_id IN ?", excluded).Count(&unexpected).Error; err != nil || unexpected != 0 {
t.Fatalf("target has %d excluded clients, err=%v", unexpected, err)
}
}
+16 -12
View File
@@ -36,12 +36,6 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string,
return result, false, nil
}
recordErr := func(format string, args ...any) {
msg := fmt.Sprintf(format, args...)
result.Errors = append(result.Errors, msg)
logger.Warningf("[BulkAttach] %s", msg)
}
records := make([]*model.ClientRecord, 0, len(emails))
seenEmail := make(map[string]struct{}, len(emails))
for _, email := range emails {
@@ -55,12 +49,22 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string,
seenEmail[key] = struct{}{}
rec, err := s.GetRecordByEmail(nil, email)
if err != nil {
recordErr("%s: %v", email, err)
logAttachError(result, "%s: %v", email, err)
continue
}
records = append(records, rec)
}
return s.bulkAttachRecords(inboundSvc, records, inboundIds, result)
}
func logAttachError(result *BulkAttachResult, format string, args ...any) {
msg := fmt.Sprintf(format, args...)
result.Errors = append(result.Errors, msg)
logger.Warningf("[BulkAttach] %s", msg)
}
func (s *ClientService) bulkAttachRecords(inboundSvc *InboundService, records []*model.ClientRecord, inboundIds []int, result *BulkAttachResult) (*BulkAttachResult, bool, error) {
// Same rule as Attach (#4834): clients.flow is unreliable when a non-flow
// inbound synced last, so seed from EffectiveFlow before clientWithInboundFlow.
emailsForFlow := make([]string, 0, len(records))
@@ -89,7 +93,7 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string,
seenInbound[ibId] = struct{}{}
inbound, err := inboundSvc.GetInbound(ibId)
if err != nil {
recordErr("inbound %d: %v", ibId, err)
logAttachError(result, "inbound %d: %v", ibId, err)
continue
}
if inbound.Protocol == model.WireGuard || inbound.Protocol == model.AmneziaWG {
@@ -97,7 +101,7 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string,
}
existingClients, err := inboundSvc.GetClients(inbound)
if err != nil {
recordErr("inbound %d: %v", ibId, err)
logAttachError(result, "inbound %d: %v", ibId, err)
continue
}
have := make(map[string]struct{}, len(existingClients))
@@ -120,7 +124,7 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string,
}
client.UpdatedAt = time.Now().UnixMilli()
if err := s.fillProtocolDefaults(&client, inbound); err != nil {
recordErr("%s -> inbound %d: %v", rec.Email, ibId, err)
logAttachError(result, "%s -> inbound %d: %v", rec.Email, ibId, err)
continue
}
clientsToAdd = append(clientsToAdd, clientWithInboundFlow(client, inbound))
@@ -132,7 +136,7 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string,
payload, err := json.Marshal(map[string][]model.Client{"clients": clientsToAdd})
if err != nil {
recordErr("inbound %d: %v", ibId, err)
logAttachError(result, "inbound %d: %v", ibId, err)
continue
}
attachIds = append(attachIds, ibId)
@@ -153,7 +157,7 @@ func (s *ClientService) BulkAttach(inboundSvc *InboundService, emails []string,
err = attachPanics[i]
}
if err != nil {
recordErr("inbound %d: %v", attachIds[i], err)
logAttachError(result, "inbound %d: %v", attachIds[i], err)
continue
}
if out.needRestart {
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "العملاء للإرفاق",
"attachClientsSearchPlaceholder": "ابحث بالبريد أو التعليق",
"attachClientsStatusDisabled": "معطل",
"attachSelectPage": "تحديد عملاء هذه الصفحة",
"attachSelectAllEligible": "تحديد جميع العملاء المؤهلين",
"attachClearSelection": "مسح التحديد",
"attachExcludedClients": "العملاء المستبعدون",
"attachRestoreClient": "إعادة تحديد {email}",
"attachClearExclusions": "مسح الاستبعادات",
"attachClientsSelectedCount": "{selected} من {total} محدد",
"attachExistingClients": "إرفاق العملاء الحاليين…",
"attachExistingTitle": "إرفاق العملاء الحاليين بـ «{remark}»",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "Clients to attach",
"attachClientsSearchPlaceholder": "Search email or comment",
"attachClientsStatusDisabled": "Disabled",
"attachSelectPage": "Select this page",
"attachSelectAllEligible": "Select all eligible clients",
"attachClearSelection": "Clear selection",
"attachExcludedClients": "Excluded clients",
"attachRestoreClient": "Restore {email}",
"attachClearExclusions": "Clear exclusions",
"attachClientsSelectedCount": "{selected} of {total} selected",
"attachExistingClients": "Attach Existing Clients…",
"attachExistingTitle": "Attach existing clients to \"{remark}\"",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "Clientes para asociar",
"attachClientsSearchPlaceholder": "Buscar email o comentario",
"attachClientsStatusDisabled": "Deshabilitado",
"attachSelectPage": "Seleccionar esta página",
"attachSelectAllEligible": "Seleccionar todos los clientes elegibles",
"attachClearSelection": "Borrar selección",
"attachExcludedClients": "Clientes excluidos",
"attachRestoreClient": "Restaurar {email}",
"attachClearExclusions": "Borrar exclusiones",
"attachClientsSelectedCount": "{selected} de {total} seleccionado(s)",
"attachExistingClients": "Asociar clientes existentes…",
"attachExistingTitle": "Asociar clientes existentes a «{remark}»",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "کاربران برای الصاق",
"attachClientsSearchPlaceholder": "جستجوی ایمیل یا توضیح",
"attachClientsStatusDisabled": "غیرفعال",
"attachSelectPage": "انتخاب این صفحه",
"attachSelectAllEligible": "انتخاب همهٔ کلاینت‌های واجد شرایط",
"attachClearSelection": "پاک کردن انتخاب",
"attachExcludedClients": "کلاینت‌های مستثنا",
"attachRestoreClient": "بازگرداندن {email}",
"attachClearExclusions": "پاک کردن موارد مستثنا",
"attachClientsSelectedCount": "{selected} از {total} انتخاب‌شده",
"attachExistingClients": "الصاق کاربران موجود…",
"attachExistingTitle": "الصاق کاربران موجود به «{remark}»",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "Klien untuk dilampirkan",
"attachClientsSearchPlaceholder": "Cari email atau komentar",
"attachClientsStatusDisabled": "Dinonaktifkan",
"attachSelectPage": "Pilih halaman ini",
"attachSelectAllEligible": "Pilih semua klien yang memenuhi syarat",
"attachClearSelection": "Hapus pilihan",
"attachExcludedClients": "Klien yang dikecualikan",
"attachRestoreClient": "Sertakan kembali {email}",
"attachClearExclusions": "Hapus pengecualian",
"attachClientsSelectedCount": "{selected} dari {total} dipilih",
"attachExistingClients": "Lampirkan klien yang ada…",
"attachExistingTitle": "Lampirkan klien yang ada ke «{remark}»",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "アタッチするクライアント",
"attachClientsSearchPlaceholder": "メールまたはコメントを検索",
"attachClientsStatusDisabled": "無効",
"attachSelectPage": "このページを選択",
"attachSelectAllEligible": "対象のクライアントをすべて選択",
"attachClearSelection": "選択を解除",
"attachExcludedClients": "除外したクライアント",
"attachRestoreClient": "{email} を選択に戻す",
"attachClearExclusions": "除外を解除",
"attachClientsSelectedCount": "{total} 中 {selected} 選択中",
"attachExistingClients": "既存のクライアントをアタッチ…",
"attachExistingTitle": "「{remark}」に既存のクライアントをアタッチ",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "Clientes para associar",
"attachClientsSearchPlaceholder": "Buscar email ou comentário",
"attachClientsStatusDisabled": "Desabilitado",
"attachSelectPage": "Selecionar esta página",
"attachSelectAllEligible": "Selecionar todos os clientes elegíveis",
"attachClearSelection": "Limpar seleção",
"attachExcludedClients": "Clientes excluídos",
"attachRestoreClient": "Restaurar {email}",
"attachClearExclusions": "Limpar exclusões",
"attachClientsSelectedCount": "{selected} de {total} selecionado(s)",
"attachExistingClients": "Associar clientes existentes…",
"attachExistingTitle": "Associar clientes existentes a «{remark}»",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "Клиенты для привязки",
"attachClientsSearchPlaceholder": "Поиск email или комментария",
"attachClientsStatusDisabled": "Отключено",
"attachSelectPage": "Выбрать эту страницу",
"attachSelectAllEligible": "Выбрать всех доступных клиентов",
"attachClearSelection": "Очистить выбор",
"attachExcludedClients": "Исключённые клиенты",
"attachRestoreClient": "Вернуть {email}",
"attachClearExclusions": "Очистить исключения",
"attachClientsSelectedCount": "{selected} из {total} выбрано",
"attachExistingClients": "Привязать существующих клиентов…",
"attachExistingTitle": "Привязать существующих клиентов к «{remark}»",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "Klienti na priradenie",
"attachClientsSearchPlaceholder": "Hľadať podľa názvu klienta alebo poznámky",
"attachClientsStatusDisabled": "Vypnutý",
"attachSelectPage": "Vybrať túto stránku",
"attachSelectAllEligible": "Vybrať všetkých oprávnených klientov",
"attachClearSelection": "Zrušiť výber",
"attachExcludedClients": "Vylúčení klienti",
"attachRestoreClient": "Obnoviť {email}",
"attachClearExclusions": "Vymazať výnimky",
"attachClientsSelectedCount": "Vybrané: {selected} z {total}",
"attachExistingClients": "Priradiť existujúcich klientov…",
"attachExistingTitle": "Priradiť existujúcich klientov k vstupu „{remark}“",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "Bağlanacak Kullanıcılar",
"attachClientsSearchPlaceholder": "E-posta veya yorum ara",
"attachClientsStatusDisabled": "Devre Dışı",
"attachSelectPage": "Bu sayfayı seç",
"attachSelectAllEligible": "Uygun tüm istemcileri seç",
"attachClearSelection": "Seçimi temizle",
"attachExcludedClients": "Hariç tutulan istemciler",
"attachRestoreClient": "{email} istemcisini geri ekle",
"attachClearExclusions": "Hariç tutulanları temizle",
"attachClientsSelectedCount": "{total} içinden {selected} seçildi",
"attachExistingClients": "Mevcut Kullanıcıları Bağla…",
"attachExistingTitle": "«{remark}» gelen bağlantıya mevcut kullanıcıları bağla",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "Клієнти для прив'язки",
"attachClientsSearchPlaceholder": "Пошук email або коментаря",
"attachClientsStatusDisabled": "Вимкнено",
"attachSelectPage": "Вибрати цю сторінку",
"attachSelectAllEligible": "Вибрати всіх доступних клієнтів",
"attachClearSelection": "Очистити вибір",
"attachExcludedClients": "Виключені клієнти",
"attachRestoreClient": "Повернути {email}",
"attachClearExclusions": "Очистити виключення",
"attachClientsSelectedCount": "Обрано {selected} з {total}",
"attachExistingClients": "Прив'язати наявних клієнтів…",
"attachExistingTitle": "Прив'язати наявних клієнтів до «{remark}»",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "Client để gắn",
"attachClientsSearchPlaceholder": "Tìm email hoặc ghi chú",
"attachClientsStatusDisabled": "Đã tắt",
"attachSelectPage": "Chọn trang này",
"attachSelectAllEligible": "Chọn tất cả máy khách đủ điều kiện",
"attachClearSelection": "Xóa lựa chọn",
"attachExcludedClients": "Máy khách bị loại trừ",
"attachRestoreClient": "Khôi phục {email}",
"attachClearExclusions": "Xóa mục loại trừ",
"attachClientsSelectedCount": "Đã chọn {selected}/{total}",
"attachExistingClients": "Gắn client hiện có…",
"attachExistingTitle": "Gắn client hiện có vào «{remark}»",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "要附加的客户端",
"attachClientsSearchPlaceholder": "搜索邮箱或备注",
"attachClientsStatusDisabled": "已禁用",
"attachSelectPage": "选择此页",
"attachSelectAllEligible": "选择所有符合条件的客户端",
"attachClearSelection": "清除选择",
"attachExcludedClients": "已排除的客户端",
"attachRestoreClient": "恢复选择 {email}",
"attachClearExclusions": "清除排除项",
"attachClientsSelectedCount": "已选 {selected}/{total}",
"attachExistingClients": "附加现有客户端…",
"attachExistingTitle": "将现有客户端附加到 “{remark}”",
+6
View File
@@ -363,6 +363,12 @@
"attachClientsSelectLabel": "要附加的客戶端",
"attachClientsSearchPlaceholder": "搜尋電子郵件或備註",
"attachClientsStatusDisabled": "已停用",
"attachSelectPage": "選擇此頁",
"attachSelectAllEligible": "選擇所有符合條件的用戶端",
"attachClearSelection": "清除選擇",
"attachExcludedClients": "已排除的用戶端",
"attachRestoreClient": "恢復選擇 {email}",
"attachClearExclusions": "清除排除項",
"attachClientsSelectedCount": "已選 {selected}/{total}",
"attachExistingClients": "附加現有客戶端…",
"attachExistingTitle": "將現有客戶端附加到「{remark}」",
+4 -1
View File
@@ -108,6 +108,9 @@ func run(root, outDir string) error {
"ClientRenewalPreviewRequest",
"ClientRenewalPreview",
"ClientPageResponse",
"AttachCandidate",
"AttachCandidatePage",
"AttachSelectionResult",
"BulkAdjustResult",
"BulkAdjustReport",
"BulkExternalLinksResult",
@@ -142,7 +145,7 @@ func run(root, outDir string) error {
},
{
Path: resolveRel(root, "internal/web/controller"),
StructAllow: setOf("TgBotCapabilities"),
StructAllow: setOf("TgBotCapabilities", "AttachJobStatus"),
},
{
Path: resolveRel(root, "internal/amneziawg"),