Skip to content
This repository was archived by the owner on Nov 13, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 45 additions & 19 deletions cogs/mod/cases.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,10 @@

from __future__ import annotations

import asyncio
import datetime
import logging
from collections.abc import Awaitable, Callable
from collections.abc import Awaitable, Callable, Sequence
from enum import Enum
from typing import TYPE_CHECKING, Any, Literal, Protocol

Expand Down Expand Up @@ -383,7 +384,7 @@ async def active(
user.id,
case_type.value,
)
return [await self._from_row(row, guild, user) for row in rows]
return await self._from_rows(rows, guild, user)

async def for_user(
self, guild: discord.Guild, user: discord.Member | discord.User, status: CaseStatus = "all"
Expand All @@ -404,7 +405,7 @@ async def for_user(
query += " AND (active = false OR (expires IS NOT NULL AND expires <= $3))"
params.append(datetime.datetime.now(tz=datetime.UTC))
rows = await self._db.fetch(query + " ORDER BY created DESC", *params)
return [await self._from_row(row, guild, user) for row in rows]
return await self._from_rows(rows, guild, user)

async def open(self, case: Case) -> Case | None:
"""Record a new case and perform its side effects.
Expand Down Expand Up @@ -524,23 +525,48 @@ async def expire(self, case_id: int) -> None:
async def _from_row(
self, row: asyncpg.Record, guild: discord.Guild, user: discord.Member | discord.User | None = None
) -> Case:
"""Build the `Case` subclass matching the row's type, resolving users from cache or the API."""
active = row["active"]
return CASE_CLASSES[CaseType(row["type"])](
_id=int(row["case_id"]),
bot=self._bot,
guild=guild,
user=user or await self._resolve_user(int(row["user_id"])),
moderator=await self._resolve_user(int(row["moderator_id"])),
reason=row["reason"],
expires=row["expires"],
message=row["message"],
created=row["created"],
active=True if active is None else active,
)
(case,) = await self._from_rows([row], guild, user)
return case

async def _resolve_user(self, user_id: int) -> discord.User:
return self._bot.get_user(user_id) or await self._bot.fetch_user(user_id)
async def _from_rows(
self, rows: Sequence[asyncpg.Record], guild: discord.Guild, user: discord.Member | discord.User | None = None
) -> list[Case]:
"""Build the `Case` subclass for each row, resolving every distinct user once (cache, then the API)."""
ids = {int(row["moderator_id"]) for row in rows}
if user is None:
ids |= {int(row["user_id"]) for row in rows}
users = await self._resolve_users(ids)
cases = []
for row in rows:
active = row["active"]
cases.append(
CASE_CLASSES[CaseType(row["type"])](
_id=int(row["case_id"]),
bot=self._bot,
guild=guild,
user=user or users[int(row["user_id"])],
moderator=users[int(row["moderator_id"])],
reason=row["reason"],
expires=row["expires"],
message=row["message"],
created=row["created"],
active=True if active is None else active,
)
)
return cases

async def _resolve_users(self, user_ids: set[int]) -> dict[int, discord.User]:
resolved = {uid: cached for uid in user_ids if (cached := self._bot.get_user(uid)) is not None}
missing = [uid for uid in user_ids if uid not in resolved]
if missing:
limit = asyncio.Semaphore(5)

async def fetch(uid: int) -> discord.User:
async with limit:
return await self._bot.fetch_user(uid)

resolved.update(zip(missing, await asyncio.gather(*(fetch(uid) for uid in missing)), strict=True))
return resolved


class CaseExpirationManager(ExpiryScheduler[int]):
Expand Down
15 changes: 15 additions & 0 deletions tests/test_cases_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,3 +235,18 @@ async def test_expire_closes_due_case_and_drops_cases_of_left_guilds(store, worl

assert await db.fetchval("SELECT active FROM cases WHERE case_id = 110") is False
assert await db.fetchval("SELECT count(*) FROM cases WHERE case_id = 111") == 0


async def test_listing_fetches_each_uncached_user_once(store, world):
"""Cases whose moderator isn't cached cost one API call per distinct moderator, not one per case."""
absent_mod = make_user(77)
for case_id in range(200, 206):
await store.open(Warn(case_id, world["bot"], world["guild"], world["target"], absent_mod))
world["bot"].get_user = MagicMock(side_effect=lambda uid: world["target"] if uid == world["target"].id else None)
world["bot"].fetch_user = AsyncMock(return_value=absent_mod)

cases = await store.for_user(world["guild"], world["target"])

assert len(cases) == 6
assert all(case._moderator is absent_mod for case in cases)
world["bot"].fetch_user.assert_awaited_once_with(77)
Loading