From b3246baf317fbbf60ca6e1392292d4dea8712fa3 Mon Sep 17 00:00:00 2001 From: itqop Date: Sat, 12 Jul 2025 00:03:06 +0300 Subject: [PATCH] Fix heath check (database + theads error) --- src/dependency_injection.py | 2 +- src/models/article_dto.py | 4 ---- src/services/database.py | 9 ++------- src/services/simplify_service.py | 11 +++++------ src/services/write_queue.py | 1 - tests/test_adapters.py | 2 -- tests/test_services.py | 2 -- 7 files changed, 8 insertions(+), 23 deletions(-) diff --git a/src/dependency_injection.py b/src/dependency_injection.py index 3a3125c..68cbc04 100644 --- a/src/dependency_injection.py +++ b/src/dependency_injection.py @@ -114,7 +114,7 @@ class DependencyContainer: checks["database"] = await db_service.health_check() except Exception: checks["database"] = False - return checks + try: write_queue = self.get_write_queue() checks["write_queue"] = ( diff --git a/src/models/article_dto.py b/src/models/article_dto.py index 9f837d1..cb795fd 100644 --- a/src/models/article_dto.py +++ b/src/models/article_dto.py @@ -12,10 +12,6 @@ class ArticleStatus(Enum): @dataclass class ArticleDTO: - """ - DTO для Article без зависимостей от SQLModel. - Используется в runtime коде для передачи данных между слоями. - """ url: str title: str raw_text: str diff --git a/src/services/database.py b/src/services/database.py index 3c10db4..3b6241e 100644 --- a/src/services/database.py +++ b/src/services/database.py @@ -19,7 +19,6 @@ class DatabaseService: self.logger.info("Создание схемы базы данных", db_path=self.config.db_path) - # Создаём таблицы напрямую через DDL без SQLAlchemy async with aiosqlite.connect(self.config.db_path) as conn: await conn.execute(""" CREATE TABLE IF NOT EXISTS articles ( @@ -67,18 +66,14 @@ class DatabaseService: async def get_connection(self) -> aiosqlite.Connection: self.logger.info("Открытие соединения с базой данных") - return await aiosqlite.connect( + return aiosqlite.connect( self.config.db_path, timeout=30.0, ) async def health_check(self) -> bool: try: - self.logger.info("Начинаем health_check...") - self.logger.info("Создаём соединение напрямую...") - - # Создаём соединение напрямую, не переиспользуя объект - async with aiosqlite.connect(self.config.db_path, timeout=30.0) as connection: + async with await self.get_connection() as connection: self.logger.info("Вошли в async context manager") self.logger.info("Выполняем SELECT 1...") await connection.execute("SELECT 1") diff --git a/src/services/simplify_service.py b/src/services/simplify_service.py index 370f32e..4c64b8d 100644 --- a/src/services/simplify_service.py +++ b/src/services/simplify_service.py @@ -70,9 +70,8 @@ class SimplifyService: page_info = await self.ruwiki_adapter.fetch_page_cleaned(command.url) article = await self._create_or_update_article(command, page_info) - # Отмечаем статью как обрабатываемую from src.models.article_dto import ArticleStatus - article.status = ArticleStatus.PENDING # В новой схеме используем PENDING для обработки + article.status = ArticleStatus.PENDING await self.repository.update_article(article) simplified_text, input_tokens, output_tokens = await self._simplify_article_text( @@ -113,9 +112,9 @@ class SimplifyService: title=existing_article.title, raw_text=existing_article.raw_text, simplified_text=existing_article.simplified_text, - token_count_raw=0, # ArticleDTO не хранит token counts - token_count_simplified=0, # ArticleDTO не хранит token counts - processing_time_seconds=0, # ArticleDTO не хранит processing time + token_count_raw=0, + token_count_simplified=0, + processing_time_seconds=0, ) return None @@ -136,7 +135,7 @@ class SimplifyService: from src.models.article_dto import ArticleStatus article.title = page_info.title article.raw_text = page_info.content - article.status = ArticleStatus.PENDING # Эквивалент mark_processing + article.status = ArticleStatus.PENDING await self.repository.update_article(article) return article diff --git a/src/services/write_queue.py b/src/services/write_queue.py index 361bf56..008ae44 100644 --- a/src/services/write_queue.py +++ b/src/services/write_queue.py @@ -155,7 +155,6 @@ class AsyncWriteQueue: msg = "Неполные данные в успешном результате" raise ValueError(msg) - # Обновляем поля напрямую, так как у ArticleDTO нет методов mark_* from src.models.article_dto import ArticleStatus article.simplified_text = result.simplified_text article.status = ArticleStatus.SIMPLIFIED diff --git a/tests/test_adapters.py b/tests/test_adapters.py index a7de050..ebd7498 100644 --- a/tests/test_adapters.py +++ b/tests/test_adapters.py @@ -121,7 +121,6 @@ class TestRuWikiAdapter: adapter.extract_title_from_url("https://ru.wikipedia.org/invalid") def test_clean_wikitext(self, test_config, sample_wikitext): - """Тест очистки wiki-текста.""" adapter = RuWikiAdapter(test_config) cleaned = adapter._clean_wikitext(sample_wikitext) @@ -160,7 +159,6 @@ class TestRuWikiAdapter: class TestLLMProviderAdapter: def test_count_tokens(self, test_config): - """Тест подсчёта токенов.""" adapter = LLMProviderAdapter(test_config) count = adapter.count_tokens("Hello world") diff --git a/tests/test_services.py b/tests/test_services.py index 30563a7..5cf34fb 100644 --- a/tests/test_services.py +++ b/tests/test_services.py @@ -1,5 +1,3 @@ -"""Тесты для сервисов.""" - import tempfile from pathlib import Path from unittest.mock import AsyncMock, MagicMock