search-index-fixed
All checks were successful
Deploy on push / deploy (push) Successful in 5m49s

This commit is contained in:
2025-08-30 18:53:38 +03:00
parent 05b5c3defd
commit 2dad23f86c
3 changed files with 39 additions and 9 deletions

27
main.py
View File

@@ -22,7 +22,7 @@ from auth.oauth import oauth_callback, oauth_login
from cache.precache import precache_data from cache.precache import precache_data
from cache.revalidator import revalidation_manager from cache.revalidator import revalidation_manager
from rbac import initialize_rbac 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 services.viewed import ViewedStorage
from settings import DEV_SERVER_PID_FILE_NAME from settings import DEV_SERVER_PID_FILE_NAME
from storage.redis import redis from storage.redis import redis
@@ -194,6 +194,26 @@ async def dev_start() -> None:
print(f"[warning] Error during DEV mode initialization: {e!s}") 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
background_tasks: list[asyncio.Task] = [] background_tasks: list[asyncio.Task] = []
@@ -236,8 +256,9 @@ async def lifespan(app: Starlette):
await dev_start() await dev_start()
print("[lifespan] Basic initialization complete") 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") print("[lifespan] Search service initialized with Muvera")
yield yield

View File

@@ -133,8 +133,13 @@ async def follow(
logger.debug("Отправка уведомления автору о подписке") logger.debug("Отправка уведомления автору о подписке")
if isinstance(follower_dict, dict) and isinstance(entity_id, int): if isinstance(follower_dict, dict) and isinstance(entity_id, int):
# Получаем ID созданной записи подписки # Получаем ID созданной записи подписки
subscription_id = getattr(sub, 'id', None) if 'sub' in locals() else None 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) await notify_follower(
follower=follower_dict,
author_id=entity_id,
action="follow",
subscription_id=subscription_id,
)
# Инвалидируем кеш статистики авторов для обновления счетчиков подписчиков # Инвалидируем кеш статистики авторов для обновления счетчиков подписчиков
logger.debug("Инвалидируем кеш статистики авторов") logger.debug("Инвалидируем кеш статистики авторов")

View File

@@ -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}") 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}" channel_name = f"follower:{author_id}"
try: try:
# Simplify dictionary before publishing # 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 записи подписки из БД "id": subscription_id or 999, # ID записи подписки из БД
"follower_id": simplified_follower["id"], "follower_id": simplified_follower["id"],
"following_id": author_id, "following_id": author_id,
"created_at": datetime.now(UTC).isoformat() "created_at": datetime.now(UTC).isoformat(),
} },
} }
# save in channel # save in channel
@@ -106,7 +108,9 @@ async def notify_follower(follower: dict[str, Any], author_id: int, action: str
if json_data: if json_data:
# Use the 'await' keyword when publishing # Use the 'await' keyword when publishing
await redis.publish(channel_name, json_data) 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: except (ConnectionError, TimeoutError, KeyError, ValueError) as e:
# Log the error and re-raise it # Log the error and re-raise it