Skip to content
This repository was archived by the owner on Jul 8, 2026. It is now read-only.

Commit 949a12c

Browse files
committed
perf(core): implement efficient bulk user deletion
Revamps the entire user deletion process to resolve critical performance bottlenecks that caused the web panel and database to freeze when removing multiple users. - **Backend:** Core scripts (`kickuser.py`, `remove_user.py`) and the database layer are re-engineered to handle multiple users in a single, efficient batch operation using MongoDB's `delete_many`. - **API:** A new `POST /api/v1/users/bulk-delete` endpoint is introduced for batch removals. The existing single-user `DELETE` endpoint is fixed to align with the new bulk logic. - **Frontend:** The Users page now intelligently calls the bulk API when multiple users are selected, drastically improving UI responsiveness and reducing server load.
1 parent cb9804d commit 949a12c

7 files changed

Lines changed: 90 additions & 46 deletions

File tree

core/cli.py

Lines changed: 19 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -184,23 +184,32 @@ def reset_user(username: str):
184184

185185

186186
@cli.command('remove-user')
187-
@click.option('--username', '-u', required=True, help='Username for the user to remove', type=str)
188-
def remove_user(username: str):
187+
@click.argument('usernames', nargs=-1, required=True)
188+
def remove_user(usernames: tuple[str]):
189+
"""Removes one or more users."""
190+
if not usernames:
191+
click.echo("No usernames provided.", err=True)
192+
return
193+
189194
try:
190-
cli_api.kick_user_by_name(username)
195+
usernames_list = list(usernames)
196+
cli_api.kick_users_by_name(usernames_list)
191197
cli_api.traffic_status(display_output=False)
192-
cli_api.remove_user(username)
193-
click.echo(f"User '{username}' removed successfully.")
198+
cli_api.remove_users(usernames_list)
199+
click.echo(f"Users '{', '.join(usernames)}' removed successfully.")
194200
except Exception as e:
195201
click.echo(f'{e}', err=True)
196202

197203
@cli.command('kick-user')
198-
@click.option('--username', '-u', required=True, help='Username of the user to kick')
199-
def kick_user(username: str):
200-
"""Kicks a specific user by username."""
204+
@click.argument('usernames', nargs=-1, required=True)
205+
def kick_user(usernames: tuple[str]):
206+
"""Kicks one or more users by username."""
207+
if not usernames:
208+
click.echo("No usernames provided.", err=True)
209+
return
210+
201211
try:
202-
cli_api.kick_user_by_name(username)
203-
# click.echo(f"User '{username}' kicked successfully.")
212+
cli_api.kick_users_by_name(list(usernames))
204213
except Exception as e:
205214
click.echo(f'{e}', err=True)
206215

core/cli_api.py

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -351,24 +351,26 @@ def reset_user(username: str):
351351
run_cmd(['python3', Command.RESET_USER.value, username])
352352

353353

354-
def remove_user(username: str):
354+
def remove_users(usernames: list[str]):
355355
'''
356-
Removes a user by username.
356+
Removes one or more users by username.
357357
'''
358-
run_cmd(['python3', Command.REMOVE_USER.value, username])
358+
if not usernames:
359+
return
360+
run_cmd(['python3', Command.REMOVE_USER.value, *usernames])
359361

360-
def kick_user_by_name(username: str):
361-
'''Kicks a specific user by username.'''
362-
if not username:
363-
raise InvalidInputError('Username must be provided to kick a specific user.')
362+
def kick_users_by_name(usernames: list[str]):
363+
'''Kicks one or more users by username.'''
364+
if not usernames:
365+
raise InvalidInputError('Username(s) must be provided to kick.')
364366
script_path = Command.KICK_USER_SCRIPT.value
365367
if not os.path.exists(script_path):
366368
raise ScriptNotFoundError(f"Kick user script not found at: {script_path}")
367369
try:
368-
subprocess.run(['python3', script_path, username], check=True)
370+
subprocess.run(['python3', script_path, *usernames], check=True)
369371
except subprocess.CalledProcessError as e:
370372
raise CommandExecutionError(f"Failed to execute kick user script: {e}")
371-
373+
372374
# TODO: it's better to return json
373375
def show_user_uri(username: str, qrcode: bool, ipv: int, all: bool, singbox: bool, normalsub: bool) -> str | None:
374376
'''

core/scripts/db/database.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,9 @@ def update_user(self, username, updates):
3535
def delete_user(self, username):
3636
return self.collection.delete_one({"_id": username.lower()})
3737

38+
def delete_users(self, usernames):
39+
return self.collection.delete_many({"_id": {"$in": usernames}})
40+
3841
try:
3942
db = Database()
4043
except pymongo.errors.ConnectionFailure:

core/scripts/hysteria2/kickuser.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,15 +36,16 @@ def get_api_secret(config_path: str) -> str:
3636

3737
def main():
3838
parser = argparse.ArgumentParser(
39-
description="Kick a Hysteria2 user via the API.",
40-
usage="%(prog)s <username>"
39+
description="Kick one or more Hysteria2 users via the API.",
40+
usage="%(prog)s <username1> [username2] ..."
4141
)
4242
parser.add_argument(
43-
"username",
44-
help="The username (Auth identity) to kick."
43+
"usernames",
44+
nargs='+',
45+
help="The username(s) (Auth identity) to kick."
4546
)
4647
args = parser.parse_args()
47-
username_to_kick = args.username
48+
usernames_to_kick = args.usernames
4849

4950
try:
5051
api_secret = get_api_secret(CONFIG_FILE)
@@ -56,16 +57,14 @@ def main():
5657
secret=api_secret
5758
)
5859

59-
client.kick_clients([username_to_kick])
60-
61-
# print(f"User '{username_to_kick}' kicked successfully.")
60+
client.kick_clients(usernames_to_kick)
6261
sys.exit(0)
6362

6463
except (FileNotFoundError, KeyError, ValueError, json.JSONDecodeError) as e:
6564
print(f"Configuration Error: {e}", file=sys.stderr)
6665
sys.exit(1)
6766
except Hysteria2Error as e:
68-
print(f"API Error kicking user '{username_to_kick}': {e}", file=sys.stderr)
67+
print(f"API Error kicking users: {e}", file=sys.stderr)
6968
sys.exit(1)
7069
except ConnectionError as e:
7170
print(f"Connection Error: Could not connect to API at {API_BASE_URL}. Is it running? Details: {e}", file=sys.stderr)

core/scripts/hysteria2/remove_user.py

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,27 +5,31 @@
55
import os
66
from db.database import db
77

8-
def remove_user(username):
8+
def remove_users(usernames):
99
if db is None:
1010
return 1, "Error: Database connection failed. Please ensure MongoDB is running."
1111

12+
if not usernames:
13+
return 1, "Error: No usernames provided for removal."
14+
1215
try:
13-
result = db.delete_user(username)
16+
result = db.delete_users(usernames)
17+
1418
if result.deleted_count > 0:
15-
return 0, f"User {username} removed successfully."
19+
return 0, f"{result.deleted_count} user(s) removed successfully."
1620
else:
17-
return 1, f"Error: User {username} not found."
21+
return 1, "Error: No matching users found for removal."
1822

1923
except Exception as e:
20-
return 1, f"An error occurred while removing the user: {e}"
24+
return 1, f"An error occurred while removing users: {e}"
2125

2226
def main():
23-
if len(sys.argv) != 2:
24-
print(f"Usage: {sys.argv[0]} <username>")
27+
if len(sys.argv) < 2:
28+
print(f"Usage: {sys.argv[0]} <username1> [username2] ...")
2529
sys.exit(1)
2630

27-
username = sys.argv[1].lower()
28-
exit_code, message = remove_user(username)
31+
usernames = [username.lower() for username in sys.argv[1:]]
32+
exit_code, message = remove_users(usernames)
2933
print(message)
3034
sys.exit(exit_code)
3135

core/scripts/webpanel/routers/api/v1/user.py

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,19 @@ async def show_multiple_user_uris_api(request: UsernamesRequest):
111111
raise HTTPException(status_code=400, detail=f'Unexpected error: {str(e)}')
112112

113113

114+
@router.post('/bulk-delete', response_model=DetailResponse)
115+
async def bulk_remove_users_api(body: UsernamesRequest):
116+
if not body.usernames:
117+
raise HTTPException(status_code=400, detail="No usernames provided.")
118+
try:
119+
cli_api.kick_users_by_name(body.usernames)
120+
cli_api.traffic_status(display_output=False)
121+
cli_api.remove_users(body.usernames)
122+
return DetailResponse(detail=f'Users have been removed.')
123+
except Exception as e:
124+
raise HTTPException(status_code=400, detail=f'Error: {str(e)}')
125+
126+
114127
@router.get('/{username}', response_model=UserInfoResponse)
115128
async def get_user_api(username: str):
116129
"""
@@ -156,7 +169,7 @@ async def edit_user_api(username: str, body: EditUserInputBody):
156169
HTTPException: if an error occurs while editing the user.
157170
"""
158171
try:
159-
cli_api.kick_user_by_name(username)
172+
cli_api.kick_users_by_name([username])
160173
cli_api.traffic_status(display_output=False)
161174
cli_api.edit_user(username, body.new_username, body.new_traffic_limit, body.new_expiration_days,
162175
body.renew_password, body.renew_creation_date, body.blocked, body.unlimited_ip)
@@ -184,12 +197,11 @@ async def remove_user_api(username: str):
184197
if not user:
185198
raise HTTPException(status_code=404, detail=f'User {username} not found.')
186199

187-
cli_api.kick_user_by_name(username)
200+
cli_api.kick_users_by_name([username])
188201
cli_api.traffic_status(display_output=False)
189-
cli_api.remove_user(username)
202+
cli_api.remove_users([username])
190203
return DetailResponse(detail=f'User {username} has been removed.')
191204
except HTTPException:
192-
193205
raise
194206
except Exception as e:
195207
raise HTTPException(status_code=400, detail=f'Error: {str(e)}')

core/scripts/webpanel/templates/users.html

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -407,11 +407,26 @@ <h5 class="modal-title" id="showLinksModalLabel">Extract User Links</h5>
407407
confirmButtonText: "Yes, delete them!",
408408
}).then((result) => {
409409
if (!result.isConfirmed) return;
410-
const urlTemplate = "{{ url_for('remove_user_api', username='U') }}";
411-
const promises = selectedUsers.map(user => $.ajax({ url: urlTemplate.replace('U', user), method: "DELETE" }));
412-
Promise.all(promises)
413-
.then(() => Swal.fire("Success!", "Selected users deleted.", "success").then(() => location.reload()))
414-
.catch(() => Swal.fire("Error!", "An error occurred while deleting users.", "error"));
410+
411+
if (selectedUsers.length > 1) {
412+
const bulkUrl = "{{ url_for('bulk_remove_users_api') }}";
413+
$.ajax({
414+
url: bulkUrl,
415+
method: "POST",
416+
contentType: "application/json",
417+
data: JSON.stringify({ usernames: selectedUsers })
418+
})
419+
.done(() => Swal.fire("Success!", "Selected users have been deleted.", "success").then(() => location.reload()))
420+
.fail((err) => Swal.fire("Error!", err.responseJSON?.detail || "An error occurred while deleting users.", "error"));
421+
} else {
422+
const singleUrl = "{{ url_for('remove_user_api', username='U') }}".replace('U', selectedUsers[0]);
423+
$.ajax({
424+
url: singleUrl,
425+
method: "DELETE"
426+
})
427+
.done(() => Swal.fire("Success!", "The user has been deleted.", "success").then(() => location.reload()))
428+
.fail((err) => Swal.fire("Error!", err.responseJSON?.detail || "An error occurred while deleting the user.", "error"));
429+
}
415430
});
416431
});
417432

0 commit comments

Comments
 (0)