forked from mtusi2026/mtusi2026lab2
выполнение лр2 на 4
This commit is contained in:
+1
-25
@@ -1,4 +1,3 @@
|
||||
"""PostgreSQL repository. Every query is parameterised; PostgreSQL is the source of truth."""
|
||||
from __future__ import annotations
|
||||
|
||||
import base64
|
||||
@@ -14,7 +13,6 @@ from app.errors import ApiError
|
||||
|
||||
|
||||
def fmt_ts(value: datetime) -> str:
|
||||
# Always 6 fractional digits: exact round trip with PostgreSQL microseconds.
|
||||
return value.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
|
||||
@@ -46,10 +44,6 @@ def message_row(row: asyncpg.Record) -> dict:
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Opaque keyset cursor bound to one resource
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def encode_cursor(resource: str, created_at: str, item_id: str) -> str:
|
||||
payload = json.dumps({"r": resource, "t": created_at, "i": item_id}, separators=(",", ":"))
|
||||
return base64.urlsafe_b64encode(payload.encode("utf-8")).decode("ascii").rstrip("=")
|
||||
@@ -65,12 +59,11 @@ def decode_cursor(resource: str, cursor: str) -> Tuple[datetime, uuid.UUID]:
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError("cursor time has no timezone")
|
||||
return created_at, uuid.UUID(payload["i"])
|
||||
except Exception as exc: # noqa: BLE001 - any malformed cursor is a 400
|
||||
except Exception as exc:
|
||||
raise ApiError(400, "invalid_request", "invalid cursor") from exc
|
||||
|
||||
|
||||
def page_of(items: List[dict], resource: str, limit: int) -> dict:
|
||||
"""Queries fetch limit+1 rows: the extra row only tells whether a next page exists."""
|
||||
page = items[:limit]
|
||||
next_cursor = None
|
||||
if len(items) > limit:
|
||||
@@ -79,17 +72,11 @@ def page_of(items: List[dict], resource: str, limit: int) -> dict:
|
||||
return {"items": page, "next_cursor": next_cursor}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Repository
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class Store:
|
||||
def __init__(self):
|
||||
self.pool: Optional[asyncpg.Pool] = None
|
||||
|
||||
async def open(self) -> None:
|
||||
# min_size=0: connections open on demand, so the API starts even while
|
||||
# PostgreSQL is down and readiness reports 503 until it is back.
|
||||
self.pool = await asyncpg.create_pool(
|
||||
config.DATABASE_URL,
|
||||
min_size=0,
|
||||
@@ -110,7 +97,6 @@ class Store:
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchval("SELECT 1") == 1
|
||||
|
||||
# -- users --------------------------------------------------------------
|
||||
|
||||
async def create_user(self, username: str, display_name: str, password_hash: str) -> dict:
|
||||
async with self.acquire() as conn:
|
||||
@@ -124,7 +110,6 @@ class Store:
|
||||
uuid.uuid4(), username, display_name, password_hash,
|
||||
)
|
||||
except asyncpg.UniqueViolationError:
|
||||
# The UNIQUE constraint, not a prior SELECT, decides concurrent registrations.
|
||||
raise ApiError(409, "conflict", "username already taken") from None
|
||||
return user_row(row)
|
||||
|
||||
@@ -135,7 +120,6 @@ class Store:
|
||||
username,
|
||||
)
|
||||
|
||||
# -- sessions -----------------------------------------------------------
|
||||
|
||||
async def create_session(self, token_hash: bytes, user_id: uuid.UUID, ttl_seconds: int) -> datetime:
|
||||
async with self.acquire() as conn:
|
||||
@@ -149,7 +133,6 @@ class Store:
|
||||
)
|
||||
|
||||
async def find_session(self, token_hash: bytes) -> Optional[asyncpg.Record]:
|
||||
"""Only a live session: not revoked and not expired by the database clock."""
|
||||
async with self.acquire() as conn:
|
||||
return await conn.fetchrow(
|
||||
"""
|
||||
@@ -171,13 +154,8 @@ class Store:
|
||||
token_hash,
|
||||
)
|
||||
|
||||
# -- chats --------------------------------------------------------------
|
||||
|
||||
async def create_chat(self, title: str, member_ids: List[uuid.UUID]) -> dict:
|
||||
"""Chat and all memberships commit together or not at all.
|
||||
|
||||
Unknown members are detected by the foreign key inside the transaction, so a
|
||||
failure after the chat row was inserted really exercises the rollback."""
|
||||
chat_id = uuid.uuid4()
|
||||
async with self.acquire() as conn:
|
||||
try:
|
||||
@@ -245,10 +223,8 @@ class Store:
|
||||
chat_id, user_id,
|
||||
))
|
||||
|
||||
# -- messages -----------------------------------------------------------
|
||||
|
||||
async def create_message(self, chat_id: uuid.UUID, sender_id: uuid.UUID, text: str) -> Optional[dict]:
|
||||
"""Membership check and insert in one statement; None means "no such chat for you"."""
|
||||
async with self.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"""
|
||||
|
||||
Reference in New Issue
Block a user