From 2dad23f86c73bbf2e3c2b28fa4e322920be5894c Mon Sep 17 00:00:00 2001 From: Untone Date: Sat, 30 Aug 2025 18:53:38 +0300 Subject: [PATCH] search-index-fixed --- main.py | 27 ++++++++++++++++++++++++--- resolvers/follower.py | 9 +++++++-- services/notify.py | 12 ++++++++---- 3 files changed, 39 insertions(+), 9 deletions(-) diff --git a/main.py b/main.py index 09224e1d..01a88b75 100644 --- a/main.py +++ b/main.py @@ -22,7 +22,7 @@ from auth.oauth import oauth_callback, oauth_login from cache.precache import precache_data from cache.revalidator import revalidation_manager from rbac import initialize_rbac -from services.search import check_search_service, search_service +from services.search import check_search_service, initialize_search_index, search_service from services.viewed import ViewedStorage from settings import DEV_SERVER_PID_FILE_NAME from storage.redis import redis @@ -194,6 +194,26 @@ async def dev_start() -> None: print(f"[warning] Error during DEV mode initialization: {e!s}") +async def initialize_search_index_with_data() -> None: + """Инициализация поискового индекса данными из БД""" + try: + from orm.shout import Shout + from storage.db import local_session + + # Получаем все опубликованные шауты из БД + with local_session() as session: + shouts = session.query(Shout).filter(Shout.published_at.is_not(None)).all() + + if shouts: + await initialize_search_index(shouts) + print(f"[search] Loaded {len(shouts)} published shouts into search index") + else: + print("[search] No published shouts found to index") + + except Exception as e: + logger.error(f"Failed to initialize search index with data: {e}") + + # Глобальная переменная для background tasks background_tasks: list[asyncio.Task] = [] @@ -236,8 +256,9 @@ async def lifespan(app: Starlette): await dev_start() print("[lifespan] Basic initialization complete") - # Search service is now handled by Muvera automatically - # No need for background indexing tasks + # Инициализируем поисковый индекс данными из БД + print("[lifespan] Initializing search index with existing data...") + await initialize_search_index_with_data() print("[lifespan] Search service initialized with Muvera") yield diff --git a/resolvers/follower.py b/resolvers/follower.py index eefaf41f..2a448191 100644 --- a/resolvers/follower.py +++ b/resolvers/follower.py @@ -133,8 +133,13 @@ async def follow( logger.debug("Отправка уведомления автору о подписке") if isinstance(follower_dict, dict) and isinstance(entity_id, int): # Получаем ID созданной записи подписки - subscription_id = getattr(sub, 'id', None) if 'sub' in locals() else None - await notify_follower(follower=follower_dict, author_id=entity_id, action="follow", subscription_id=subscription_id) + subscription_id = getattr(sub, "id", None) if "sub" in locals() else None + await notify_follower( + follower=follower_dict, + author_id=entity_id, + action="follow", + subscription_id=subscription_id, + ) # Инвалидируем кеш статистики авторов для обновления счетчиков подписчиков logger.debug("Инвалидируем кеш статистики авторов") diff --git a/services/notify.py b/services/notify.py index 223b751f..85ee9762 100644 --- a/services/notify.py +++ b/services/notify.py @@ -73,7 +73,9 @@ async def notify_shout(shout: dict[str, Any], action: str = "update") -> None: logger.error(f"Failed to publish to channel {channel_name}: {e}") -async def notify_follower(follower: dict[str, Any], author_id: int, action: str = "follow", subscription_id: int | None = None) -> None: +async def notify_follower( + follower: dict[str, Any], author_id: int, action: str = "follow", subscription_id: int | None = None +) -> None: channel_name = f"follower:{author_id}" try: # Simplify dictionary before publishing @@ -89,8 +91,8 @@ async def notify_follower(follower: dict[str, Any], author_id: int, action: str "id": subscription_id or 999, # ID записи подписки из БД "follower_id": simplified_follower["id"], "following_id": author_id, - "created_at": datetime.now(UTC).isoformat() - } + "created_at": datetime.now(UTC).isoformat(), + }, } # save in channel @@ -106,7 +108,9 @@ async def notify_follower(follower: dict[str, Any], author_id: int, action: str if json_data: # Use the 'await' keyword when publishing await redis.publish(channel_name, json_data) - logger.debug(f"📡 Отправлено SSE уведомление о подписке: author_id={author_id}, follower={simplified_follower.get('name')}") + logger.debug( + f"📡 Отправлено SSE уведомление о подписке: author_id={author_id}, follower={simplified_follower.get('name')}" + ) except (ConnectionError, TimeoutError, KeyError, ValueError) as e: # Log the error and re-raise it