This commit is contained in:
user committed 2025-07-11 06:46:33 +03:00
1 parent 373c832e71
commit 1b0dfdafbc
48 files changed
+3114 -396

No files matched your search

+54 -3
View File
@@ -7,7 +7,7 @@ from datetime import datetime, timedelta
from typing import Dict, List, Optional, Set, Any
from pathlib import Path
from app.core.database_compatible import get_async_session
from app.core.database import db_manager
from app.core.models.content_compatible import Content
from app.core.cache import cache
from .bootstrap_manager import BootstrapManager
@@ -297,8 +297,11 @@ class MyNetworkNodeService:
logger.info(f"Starting replication of content: {content_hash}")
# Найти контент в локальной БД
async with get_async_session() as session:
content = await session.get(Content, {"hash": content_hash})
async with db_manager.get_session() as session:
from sqlalchemy import select
stmt = select(Content).where(Content.hash == content_hash)
result = await session.execute(stmt)
content = result.scalar_one_or_none()
if not content:
raise ValueError(f"Content not found: {content_hash}")
@@ -358,6 +361,54 @@ class MyNetworkNodeService:
async def get_content_sync_status(self, content_hash: str) -> Dict[str, Any]:
"""Получить статус синхронизации конкретного контента."""
return await self.sync_manager.get_content_sync_status(content_hash)
async def get_node_info(self) -> Dict[str, Any]:
"""Получить информацию о текущей ноде."""
try:
uptime_seconds = self._get_uptime_hours() * 3600 if self.start_time else 0
return {
"node_id": self.node_id,
"status": "running" if self.is_running else "stopped",
"version": "2.0",
"uptime": uptime_seconds,
"start_time": self.start_time.isoformat() if self.start_time else None,
"metrics": self.node_metrics.copy(),
"storage_path": str(self.storage_path),
"last_sync": self.last_sync_time.isoformat() if self.last_sync_time else None
}
except Exception as e:
logger.error(f"Error getting node info: {e}")
return {
"node_id": self.node_id,
"status": "error",
"error": str(e)
}
async def get_peers_info(self) -> Dict[str, Any]:
"""Получить информацию о пирах."""
try:
connected_peers = self.peer_manager.get_connected_peers()
all_peers_info = self.peer_manager.get_all_peers_info()
connection_stats = self.peer_manager.get_connection_stats()
return {
"peer_count": len(connected_peers),
"connected_peers": list(connected_peers),
"peers": list(all_peers_info.values()),
"connection_stats": connection_stats,
"healthy_connections": connection_stats.get("healthy_connections", 0),
"total_connections": connection_stats.get("total_connections", 0),
"average_latency_ms": connection_stats.get("average_latency_ms")
}
except Exception as e:
logger.error(f"Error getting peers info: {e}")
return {
"peer_count": 0,
"connected_peers": [],
"peers": [],
"error": str(e)
}
# Глобальный экземпляр сервиса ноды
+12 -10
View File
@@ -9,7 +9,7 @@ from pathlib import Path
from typing import Dict, List, Optional, Any, Set
from sqlalchemy import select, and_
from app.core.database_compatible import get_async_session
from app.core.database import db_manager
from app.core.models.content_compatible import Content, ContentMetadata
from app.core.cache import cache
@@ -328,9 +328,11 @@ class ContentSyncManager:
async def _get_local_content_info(self, content_hash: str) -> Optional[Dict[str, Any]]:
"""Получить информацию о локальном контенте."""
try:
async with get_async_session() as session:
async with db_manager.get_session() as session:
# Найти контент по хешу
stmt = select(Content).where(Content.md5_hash == content_hash or Content.sha256_hash == content_hash)
stmt = select(Content).where(
(Content.md5_hash == content_hash) | (Content.sha256_hash == content_hash)
)
result = await session.execute(stmt)
content = result.scalar_one_or_none()
@@ -352,7 +354,7 @@ class ContentSyncManager:
"file_type": content.file_type,
"mime_type": content.mime_type,
"encrypted": content.encrypted if hasattr(content, 'encrypted') else False,
"metadata": metadata.to_dict() if metadata else {}
"metadata": metadata.to_dict() if metadata and hasattr(metadata, 'to_dict') else {}
}
except Exception as e:
@@ -484,7 +486,7 @@ class ContentSyncManager:
async def _save_content_to_db(self, content_hash: str, file_path: Path, metadata: Dict[str, Any]) -> None:
"""Сохранить информацию о контенте в базу данных."""
try:
async with get_async_session() as session:
async with db_manager.get_session() as session:
# Создать запись контента
content = Content(
filename=metadata.get("filename", file_path.name),
@@ -647,16 +649,16 @@ class ContentSyncManager:
async def _get_local_content_hashes(self) -> Set[str]:
"""Получить множество хешей локального контента."""
try:
async with get_async_session() as session:
async with db_manager.get_session() as session:
stmt = select(Content.md5_hash, Content.sha256_hash).where(Content.is_active == True)
result = await session.execute(stmt)
hashes = set()
for row in result:
if row.md5_hash:
hashes.add(row.md5_hash)
if row.sha256_hash:
hashes.add(row.sha256_hash)
if row[0]: # md5_hash
hashes.add(row[0])
if row[1]: # sha256_hash
hashes.add(row[1])
return hashes