Skip to content

Commit 6f062fe

Browse files
fix: try to make get usages faster
1 parent b77f766 commit 6f062fe

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

app/db/crud/user.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -888,7 +888,7 @@ async def autodelete_expired_users(
888888

889889
async def get_all_users_usages(
890890
db: AsyncSession,
891-
admin: str,
891+
admins: Sequence[str] | None,
892892
start: datetime,
893893
end: datetime,
894894
period: Period = Period.hour,
@@ -901,7 +901,7 @@ async def get_all_users_usages(
901901
902902
Args:
903903
db (AsyncSession): Database session for querying.
904-
admin (Admin): The admin user for which to retrieve user usage data.
904+
admins (Sequence[str] | None): Admin usernames to filter users by. If None/empty, include all admins.
905905
start (datetime): Start of the period.
906906
end (datetime): End of the period.
907907
period (Period): Time period to group by ('minute', 'hour', 'day', 'month').
@@ -910,15 +910,20 @@ async def get_all_users_usages(
910910
Returns:
911911
UserUsageStatsList: Aggregated usage data for each period.
912912
"""
913-
admin_users = {user.id for user in await get_users(db=db, admins=admin)}
913+
admins_filter = admins or None
914+
915+
users_subquery = select(User.id)
916+
if admins_filter:
917+
users_subquery = users_subquery.join(Admin).where(Admin.username.in_(admins_filter))
918+
users_subquery = users_subquery.subquery()
914919

915920
# Build the appropriate truncation expression
916921
trunc_expr = _build_trunc_expression(db, period, NodeUserUsage.created_at)
917922

918923
conditions = [
919924
NodeUserUsage.created_at >= start,
920925
NodeUserUsage.created_at <= end,
921-
NodeUserUsage.user_id.in_(admin_users),
926+
NodeUserUsage.user_id.in_(select(users_subquery.c.id)),
922927
]
923928

924929
if node_id is not None:

app/operation/user.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -336,7 +336,7 @@ async def get_users_usage(
336336
end=end,
337337
period=period,
338338
node_id=node_id,
339-
admin=owner if admin.is_sudo else [admin.username],
339+
admins=owner if admin.is_sudo else [admin.username],
340340
group_by_node=group_by_node,
341341
)
342342

0 commit comments

Comments
 (0)