File size: 2,486 Bytes
0b2210a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | from __future__ import annotations
import json
import time
import threading
from pathlib import Path
import os
import logging
from typing import Optional, Dict, Any, Any as AnyType # Any imported twice to be safe if some tools prefer it
logger = logging.getLogger(__name__)
class MultiProcessSync:
"""Легковесная синхронизация между процессами Uvicorn"""
def __init__(self, sync_dir=".sync"):
self.sync_dir = Path(sync_dir)
self.sync_dir.mkdir(exist_ok=True)
self.state_file = self.sync_dir / "workers.json"
self._local_version = self._load_version()
def _load_version(self):
"""Загружает текущую версию"""
if self.state_file.exists():
try:
with open(self.state_file, 'r') as f:
data = json.load(f)
return data.get('version', 0)
except Exception as e:
logger.warning(f"Error loading sync file: {e}")
return 0
return 0
def notify_state_change(self, change_type: str, data: Optional[Dict[str, Any]] = None):
"""
Уведомляет о изменении состояния.
Args:
change_type: Тип изменения (например, "project_open", "session_mode_change")
data: Дополнительные данные об изменении.
"""
self._local_version += 1
notification = {
'version': self._local_version,
'timestamp': time.time(),
'type': change_type,
'data': data or {},
'pid': os.getpid()
}
try:
with open(self.state_file, 'w') as f:
json.dump(notification, f, indent=2)
logger.info(f"Notified workers about {change_type} (v{self._local_version})")
except Exception as e:
logger.error(f"Failed to write sync file: {e}")
def check_for_notifications(self) -> bool:
"""Проверяет новые уведомления."""
current_version = self._load_version()
if current_version > self._local_version:
self._local_version = current_version
return True
return False
# Глобальный экземпляр для импорта
multi_process_sync = MultiProcessSync()
|