Files
romm/backend/handler/database/notifications_handler.py
zurdi 00373cee5b refactor: apply the second simplify pass
- A persisted snackbar toasts at once with the caller's options; what this
  tab sends is marked with its tab id, so the socket echo of it adds the row
  without a second toast. The toast no longer depends on which of the
  request and the push arrives first.
- v2 logout disconnects the socket, which otherwise stays in the user's rooms
  until the next login.
- notify_scan_end takes one required outcome, the stats or the error.
- Inboxes are trimmed only for users over the cap, found in one query, and
  pushes go out one after another on one Redis connection.
- The log forwarder and the sync emitters use the shared write manager.
- One makeNotification fixture for the frontend tests; small dead code gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-23 13:42:12 +02:00

107 lines
3.7 KiB
Python

from collections.abc import Sequence
from datetime import datetime, timezone
from sqlalchemy import delete, func, select, update
from sqlalchemy.orm import Session, joinedload
from decorators.database import begin_session
from models.notification import MAX_NOTIFICATIONS_PER_USER, Notification
from models.user import User
from .base_handler import DBBaseHandler, affected_rows
def _with_actor():
# Name and avatar only, the rest of a user row is large JSON. Built per query,
# as touching `User` columns at import configures the mappers too early.
return joinedload(Notification.actor).load_only(
User.id, User.username, User.avatar_path, User.updated_at
)
class DBNotificationsHandler(DBBaseHandler):
@begin_session
def add_notifications(
self,
notifications: Sequence[Notification],
session: Session = None, # type: ignore
) -> Sequence[Notification]:
"""Store notifications and trim their users' inboxes; returns the rows kept."""
session.add_all(notifications)
session.flush()
over_cap = session.scalars(
select(Notification.user_id)
.where(Notification.user_id.in_({n.user_id for n in notifications}))
.group_by(Notification.user_id)
.having(func.count() > MAX_NOTIFICATIONS_PER_USER)
).all()
for user_id in over_cap:
stale_ids = session.scalars(
select(Notification.id)
.where(Notification.user_id == user_id)
.order_by(Notification.created_at.desc(), Notification.id.desc())
.offset(MAX_NOTIFICATIONS_PER_USER)
).all()
if stale_ids:
session.execute(
delete(Notification)
.where(Notification.id.in_(stale_ids))
.execution_options(synchronize_session=False)
)
return session.scalars(
select(Notification)
.options(_with_actor())
.where(Notification.id.in_([n.id for n in notifications]))
.order_by(Notification.id)
).all()
@begin_session
def get_notifications(
self,
user_id: int,
session: Session = None, # type: ignore
) -> Sequence[Notification]:
return session.scalars(
select(Notification)
.options(_with_actor())
.where(Notification.user_id == user_id)
.order_by(Notification.created_at.desc(), Notification.id.desc())
).all()
@begin_session
def mark_read(
self,
user_id: int,
ids: list[int] | None = None,
session: Session = None, # type: ignore
) -> None:
"""Mark the user's unread notifications read, all of them when `ids` is None."""
stmt = update(Notification).where(
Notification.user_id == user_id, Notification.read_at.is_(None)
)
if ids is not None:
stmt = stmt.where(Notification.id.in_(ids))
session.execute(
stmt.values(read_at=datetime.now(timezone.utc)).execution_options(
synchronize_session=False
)
)
@begin_session
def delete_notifications(
self,
user_id: int,
ids: list[int] | None = None,
session: Session = None, # type: ignore
) -> int:
"""Delete the user's notifications, all of them when `ids` is None."""
stmt = delete(Notification).where(Notification.user_id == user_id)
if ids is not None:
stmt = stmt.where(Notification.id.in_(ids))
result = session.execute(stmt.execution_options(synchronize_session=False))
return affected_rows(result)