Forward the lab 5 foundation while preserving lab 6 telemetry

Source: immutable lab5 snapshot f88e9ba43cdfd7eb6a5a7ae5feb4247b4e820071; forward the allowed diff from 64d5c67. Carry SQLAlchemy, Alembic, reliability fixes, versioned jobs, infrastructure and student tests without changing protected coursework files.

Validation: make check, validate, lint; 515 student tests passed with one Linux-only skip; public smoke with telemetry enabled and repeat migration passed. Stop the owned stack and retain volumes. Preserve the existing OTel work in progress; grade implementation remains a separate phase.
This commit is contained in:
Artyom
2026-11-06 12:29:35 +03:00
parent dc9256baf9
commit 12db77133f
161 changed files with 11160 additions and 1467 deletions
+13 -9
View File
@@ -4,7 +4,7 @@ from messenger.identity.application.commands import CloseSession, OpenSession, R
from messenger.identity.application.ports import (
IdentityUnitOfWork,
PasswordHasher,
SessionDirectory,
SessionRevocations,
)
from messenger.identity.domain.events import SessionClosed, SessionOpened
from messenger.identity.domain.models import Session, User
@@ -62,15 +62,19 @@ class OpenSessionHandler:
class CloseSessionHandler:
__slots__ = ("_sessions", "_uow")
__slots__ = ("_revocations", "_uow")
def __init__(self, uow: IdentityUnitOfWork, sessions: SessionDirectory) -> None:
def __init__(self, uow: IdentityUnitOfWork, revocations: SessionRevocations) -> None:
self._uow = uow
self._sessions = sessions
self._revocations = revocations
async def __call__(self, command: CloseSession) -> None:
await self._sessions.invalidate(command.session)
async with self._uow.transaction():
await self._uow.sessions.remove(command.session.token_hash)
self._uow.record(SessionClosed(user_id=command.session.user_id))
await self._uow.commit()
await self._revocations.revoke(command.session)
try:
async with self._uow.transaction():
await self._uow.sessions.remove(command.session.token_hash)
self._uow.record(SessionClosed(user_id=command.session.user_id))
await self._uow.commit()
except BaseException:
await self._revocations.restore(command.session)
raise
+6 -1
View File
@@ -38,7 +38,12 @@ class UserDirectory(Protocol):
class SessionDirectory(Protocol):
async def find(self, token_hash: bytes, now: datetime) -> Session | None: ...
async def invalidate(self, session: Session) -> None: ...
@runtime_checkable
class SessionRevocations(Protocol):
async def revoke(self, session: Session) -> None: ...
async def restore(self, session: Session) -> None: ...
@runtime_checkable
+8 -3
View File
@@ -17,6 +17,7 @@ from messenger.identity.application.ports import (
IdentityUnitOfWork,
PasswordHasher,
SessionDirectory,
SessionRevocations,
UserDirectory,
)
from messenger.identity.application.queries import Authenticate, GetCurrentUser, VerifyCredentials
@@ -27,7 +28,7 @@ from messenger.identity.infrastructure.postgres import (
PostgresSessionDirectory,
PostgresUserDirectory,
)
from messenger.identity.infrastructure.valkey import CachedSessionDirectory
from messenger.identity.infrastructure.valkey import CachedSessionDirectory, NoRevocations
from messenger.shared.application.commands import Command
from messenger.shared.application.messagebus import CommandHandler
from messenger.shared.application.ports import Clock, EventPublisher, IdGenerator, Logger
@@ -76,6 +77,10 @@ class IdentityProvider(Provider):
finally:
await client.aclose()
@provide(scope=Scope.APP)
def revocations(self, sessions: SessionDirectory) -> SessionRevocations:
return sessions if isinstance(sessions, CachedSessionDirectory) else NoRevocations()
@provide(scope=Scope.APP)
def verify(self, users: UserDirectory, hasher: PasswordHasher) -> VerifyCredentials:
return VerifyCredentials(users, hasher)
@@ -100,13 +105,13 @@ class IdentityProvider(Provider):
clock: Clock,
ids: IdGenerator,
hasher: PasswordHasher,
sessions: SessionDirectory,
revocations: SessionRevocations,
settings: IdentitySettings,
) -> IdentityCommandBus:
ttl = timedelta(seconds=settings.session_ttl_seconds)
handlers: dict[type[Command], CommandHandler] = {
RegisterUser: RegisterUserHandler(uow, clock, ids, hasher),
OpenSession: OpenSessionHandler(uow, clock, ttl),
CloseSession: CloseSessionHandler(uow, sessions),
CloseSession: CloseSessionHandler(uow, revocations),
}
return IdentityCommandBus(handlers, uow, publisher)
+121 -63
View File
@@ -1,85 +1,126 @@
from datetime import datetime
from uuid import UUID
from asyncpg import Record
from sqlalchemy import (
CheckConstraint,
DateTime,
ForeignKey,
Index,
LargeBinary,
UniqueConstraint,
delete,
literal,
select,
)
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.orm import Mapped, mapped_column
from messenger.identity.domain.errors import UsernameAlreadyTaken
from messenger.identity.domain.models import Session, User
from messenger.identity.domain.values import DisplayName, Username
from messenger.shared.infrastructure.postgres import Connection, Database, PostgresUnitOfWork
INSERT_USER = """
INSERT INTO users (id, username, display_name, password_hash, created_at)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (username) DO NOTHING
RETURNING true
"""
USER_BY_ID = """
SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1
"""
USER_BY_USERNAME = """
SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1
"""
INSERT_SESSION = """
WITH expired AS (DELETE FROM sessions WHERE user_id = $2 AND expires_at <= $3)
INSERT INTO sessions (token_hash, user_id, created_at, expires_at) VALUES ($1, $2, $3, $4)
"""
DELETE_SESSION = "DELETE FROM sessions WHERE token_hash = $1"
ACTIVE_SESSION = """
SELECT token_hash, user_id, created_at, expires_at
FROM sessions
WHERE token_hash = $1 AND expires_at > $2
"""
from messenger.shared.infrastructure.postgres import (
Base,
Database,
DatabaseSession,
PostgresUnitOfWork,
)
def user_of(row: Record | None) -> User | None:
class UserRow(Base):
__tablename__ = "users"
__table_args__ = (
UniqueConstraint("username", name="users_username_key"),
CheckConstraint("username ~ '^[a-z0-9_]{3,32}$'", name="users_username_format"),
CheckConstraint(
"char_length(display_name) BETWEEN 1 AND 100", name="users_display_name_check"
),
CheckConstraint("password_hash LIKE '$argon2id$%'", name="users_password_hash_check"),
)
id: Mapped[UUID] = mapped_column(primary_key=True)
username: Mapped[str]
display_name: Mapped[str]
password_hash: Mapped[str]
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
class SessionRow(Base):
__tablename__ = "sessions"
__table_args__ = (
CheckConstraint("octet_length(token_hash) = 32", name="sessions_token_hash_check"),
CheckConstraint("expires_at > created_at", name="sessions_check"),
Index("sessions_user_idx", "user_id"),
)
token_hash: Mapped[bytes] = mapped_column(LargeBinary, primary_key=True)
user_id: Mapped[UUID] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
def user_of(row: UserRow | None) -> User | None:
if row is None:
return None
return User(
id=row["id"],
username=Username(row["username"]),
display_name=DisplayName(row["display_name"]),
created_at=row["created_at"],
password_hash=row["password_hash"],
id=row.id,
username=Username(row.username),
display_name=DisplayName(row.display_name),
created_at=row.created_at,
password_hash=row.password_hash,
)
class PostgresUserRepository:
__slots__ = ("_connection",)
__slots__ = ("_session",)
def __init__(self, connection: Connection) -> None:
self._connection = connection
def __init__(self, session: DatabaseSession) -> None:
self._session = session
async def add(self, user: User) -> None:
inserted = await self._connection.fetchval(
INSERT_USER,
user.id,
user.username.value,
user.display_name.value,
user.password_hash,
user.created_at,
statement = (
insert(UserRow)
.values(
id=user.id,
username=user.username.value,
display_name=user.display_name.value,
password_hash=user.password_hash,
created_at=user.created_at,
)
.on_conflict_do_nothing(index_elements=["username"])
.returning(literal(True))
)
inserted = (await self._session.execute(statement)).scalar_one_or_none()
if inserted is None:
raise UsernameAlreadyTaken("username уже занят")
class PostgresSessionRepository:
__slots__ = ("_connection",)
__slots__ = ("_session",)
def __init__(self, connection: Connection) -> None:
self._connection = connection
def __init__(self, session: DatabaseSession) -> None:
self._session = session
async def add(self, session: Session) -> None:
await self._connection.execute(
INSERT_SESSION,
session.token_hash,
session.user_id,
session.created_at,
session.expires_at,
expired = (
delete(SessionRow)
.where(
SessionRow.user_id == session.user_id, SessionRow.expires_at <= session.created_at
)
.cte("expired")
)
await self._session.execute(
insert(SessionRow)
.values(
token_hash=session.token_hash,
user_id=session.user_id,
created_at=session.created_at,
expires_at=session.expires_at,
)
.add_cte(expired)
)
async def remove(self, token_hash: bytes) -> None:
await self._connection.execute(DELETE_SESSION, token_hash)
await self._session.execute(delete(SessionRow).where(SessionRow.token_hash == token_hash))
class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
@@ -87,11 +128,11 @@ class PostgresIdentityUnitOfWork(PostgresUnitOfWork):
@property
def users(self) -> PostgresUserRepository:
return PostgresUserRepository(self.connection)
return PostgresUserRepository(self.session)
@property
def sessions(self) -> PostgresSessionRepository:
return PostgresSessionRepository(self.connection)
return PostgresSessionRepository(self.session)
class PostgresUserDirectory:
@@ -101,12 +142,18 @@ class PostgresUserDirectory:
self._database = database
async def find(self, user_id: UUID) -> User | None:
async with self._database.connection() as connection:
return user_of(await connection.fetchrow(USER_BY_ID, user_id))
async with self._database.session() as session:
row = (
await session.execute(select(UserRow).where(UserRow.id == user_id))
).scalar_one_or_none()
return user_of(row)
async def find_by_username(self, username: str) -> User | None:
async with self._database.connection() as connection:
return user_of(await connection.fetchrow(USER_BY_USERNAME, username))
async with self._database.session() as session:
row = (
await session.execute(select(UserRow).where(UserRow.username == username))
).scalar_one_or_none()
return user_of(row)
class PostgresSessionDirectory:
@@ -116,9 +163,20 @@ class PostgresSessionDirectory:
self._database = database
async def find(self, token_hash: bytes, now: datetime) -> Session | None:
async with self._database.connection() as connection:
row = await connection.fetchrow(ACTIVE_SESSION, token_hash, now)
return None if row is None else Session(**dict(row))
async def invalidate(self, session: Session) -> None:
return None
async with self._database.session() as session:
row = (
await session.execute(
select(SessionRow).where(
SessionRow.token_hash == token_hash,
SessionRow.expires_at > now,
)
)
).scalar_one_or_none()
if row is None:
return None
return Session(
token_hash=row.token_hash,
user_id=row.user_id,
created_at=row.created_at,
expires_at=row.expires_at,
)
@@ -37,6 +37,14 @@ def decode(token_hash: bytes, value: str) -> Session:
)
class NoRevocations:
async def revoke(self, session: Session) -> None:
return None
async def restore(self, session: Session) -> None:
return None
class CachedSessionDirectory:
__slots__ = ("_client", "_cooldown", "_limit", "_logger", "_origin", "_resume_at")
@@ -70,7 +78,7 @@ class CachedSessionDirectory:
await self._quietly(self._client.set(key, encode(session), pxat=until, nx=True))
return session
async def invalidate(self, session: Session) -> None:
async def revoke(self, session: Session) -> None:
if not self._closed():
raise Unavailable("кэш сессий недоступен")
try:
@@ -81,6 +89,9 @@ class CachedSessionDirectory:
self._trip(error)
raise Unavailable("кэш сессий недоступен") from error
async def restore(self, session: Session) -> None:
await self._quietly(self._client.delete(key_of(session.token_hash)))
async def _read(self, key: str) -> str | None:
if not self._closed():
return None