|
| 1 | +import dataclasses |
| 2 | +import datetime as dt |
| 3 | + |
| 4 | +from db_retry import Transaction, postgres_retry |
| 5 | +from sqlalchemy import func, insert, select |
| 6 | +from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker |
| 7 | + |
| 8 | +from sqlalchemy_inbox import Inbox |
| 9 | +from tests.conftest import Tables |
| 10 | + |
| 11 | + |
| 12 | +@dataclasses.dataclass(kw_only=True, frozen=True, slots=True) |
| 13 | +class CleanupInboxUseCase: |
| 14 | + transaction: Transaction |
| 15 | + inbox: Inbox |
| 16 | + |
| 17 | + async def __call__(self, *, retention: dt.timedelta, batch_size: int) -> None: |
| 18 | + async with self.transaction: |
| 19 | + cutoff = await self.inbox.cleanup_cutoff(retention=retention) |
| 20 | + while await self._delete_batch(cutoff=cutoff, limit=batch_size): |
| 21 | + pass |
| 22 | + |
| 23 | + @postgres_retry |
| 24 | + async def _delete_batch(self, *, cutoff: dt.datetime, limit: int) -> int: |
| 25 | + async with self.transaction: |
| 26 | + deleted = await self.inbox.delete_expired_batch(cutoff=cutoff, limit=limit) |
| 27 | + await self.transaction.commit() |
| 28 | + return deleted |
| 29 | + |
| 30 | + |
| 31 | +async def test_readme_cleanup_use_case_deletes_every_expired_marker( |
| 32 | + pg_engine: AsyncEngine, tables: Tables, session_maker: async_sessionmaker[AsyncSession] |
| 33 | +) -> None: |
| 34 | + async with pg_engine.begin() as conn: |
| 35 | + for index in range(5): |
| 36 | + await conn.execute( |
| 37 | + insert(tables.inbox).values( |
| 38 | + scope="s", message_id=f"old-{index}", processed_at=func.now() - dt.timedelta(hours=2) |
| 39 | + ) |
| 40 | + ) |
| 41 | + await conn.execute(insert(tables.inbox).values(scope="s", message_id="recent")) |
| 42 | + |
| 43 | + session = session_maker() |
| 44 | + use_case = CleanupInboxUseCase(transaction=Transaction(session=session), inbox=Inbox(session, tables.inbox)) |
| 45 | + await use_case(retention=dt.timedelta(hours=1), batch_size=2) |
| 46 | + |
| 47 | + async with pg_engine.connect() as conn: |
| 48 | + remaining = list((await conn.execute(select(tables.inbox.c.message_id))).scalars()) |
| 49 | + assert remaining == ["recent"] |
0 commit comments