Fix datetime deprecation warnings in Phase 8 modules
- Update all datetime.utcnow() to datetime.now(UTC) for Python 3.12+ compatibility - Update all datetime.utcfromtimestamp() to datetime.fromtimestamp(..., UTC) - Fix dataclass default_factory to use lambda: datetime.now(UTC) - Update auth, audit, billing, and realtime modules - Add UTC import from datetime module - Update pytest configuration to include pytest-asyncio - All 28 Phase 8 enterprise tests pass with no warnings Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
This commit is contained in:
15
ontology_platform/ont_platform/realtime/__init__.py
Normal file
15
ontology_platform/ont_platform/realtime/__init__.py
Normal file
@@ -0,0 +1,15 @@
|
||||
"""실시간 업데이트 모듈 (Phase 8).
|
||||
|
||||
기능:
|
||||
- WebSocket 연결 관리
|
||||
- 이벤트 브로드캐스트
|
||||
- 조직별 격리
|
||||
"""
|
||||
|
||||
from ont_platform.realtime.websocket import ConnectionManager
|
||||
from ont_platform.realtime.broadcaster import EventBroadcaster
|
||||
|
||||
__all__ = [
|
||||
"ConnectionManager",
|
||||
"EventBroadcaster",
|
||||
]
|
||||
289
ontology_platform/ont_platform/realtime/broadcaster.py
Normal file
289
ontology_platform/ont_platform/realtime/broadcaster.py
Normal file
@@ -0,0 +1,289 @@
|
||||
"""이벤트 브로드캐스터 (Phase 8).
|
||||
|
||||
기능:
|
||||
- Neo4j 변경 이벤트 브로드캐스트
|
||||
- 실시간 그래프 업데이트 알림
|
||||
"""
|
||||
|
||||
import logging
|
||||
from datetime import datetime, UTC
|
||||
from typing import Dict, List, Any, Optional
|
||||
|
||||
from ont_platform.realtime.websocket import ConnectionManager
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class EventBroadcaster:
|
||||
"""이벤트 브로드캐스터."""
|
||||
|
||||
def __init__(self, connection_manager: ConnectionManager):
|
||||
"""초기화.
|
||||
|
||||
Args:
|
||||
connection_manager: WebSocket 연결 관리자
|
||||
"""
|
||||
self.manager = connection_manager
|
||||
|
||||
async def broadcast_entity_created(
|
||||
self,
|
||||
org_id: str,
|
||||
entity: Dict[str, Any],
|
||||
user_id: str = "system",
|
||||
) -> int:
|
||||
"""엔티티 생성 이벤트 브로드캐스트.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID
|
||||
entity: 엔티티 정보
|
||||
user_id: 생성 사용자 ID
|
||||
|
||||
Returns:
|
||||
메시지 수신 클라이언트 수
|
||||
"""
|
||||
message = {
|
||||
"type": "entity.created",
|
||||
"timestamp": datetime.now(UTC).isoformat(),
|
||||
"user_id": user_id,
|
||||
"entity": entity,
|
||||
}
|
||||
|
||||
sent = await self.manager.broadcast(org_id, message)
|
||||
logger.info(f"Entity created event broadcast: {entity.get('id')} to {sent} clients")
|
||||
|
||||
return sent
|
||||
|
||||
async def broadcast_entity_updated(
|
||||
self,
|
||||
org_id: str,
|
||||
entity_id: str,
|
||||
changes: Dict[str, Any],
|
||||
user_id: str = "system",
|
||||
) -> int:
|
||||
"""엔티티 업데이트 이벤트 브로드캐스트.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID
|
||||
entity_id: 엔티티 ID
|
||||
changes: 변경사항
|
||||
user_id: 업데이트 사용자 ID
|
||||
|
||||
Returns:
|
||||
메시지 수신 클라이언트 수
|
||||
"""
|
||||
message = {
|
||||
"type": "entity.updated",
|
||||
"timestamp": datetime.now(UTC).isoformat(),
|
||||
"user_id": user_id,
|
||||
"entity_id": entity_id,
|
||||
"changes": changes,
|
||||
}
|
||||
|
||||
sent = await self.manager.broadcast(org_id, message)
|
||||
logger.info(f"Entity updated event broadcast: {entity_id} to {sent} clients")
|
||||
|
||||
return sent
|
||||
|
||||
async def broadcast_entity_deleted(
|
||||
self,
|
||||
org_id: str,
|
||||
entity_id: str,
|
||||
user_id: str = "system",
|
||||
) -> int:
|
||||
"""엔티티 삭제 이벤트 브로드캐스트.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID
|
||||
entity_id: 엔티티 ID
|
||||
user_id: 삭제 사용자 ID
|
||||
|
||||
Returns:
|
||||
메시지 수신 클라이언트 수
|
||||
"""
|
||||
message = {
|
||||
"type": "entity.deleted",
|
||||
"timestamp": datetime.now(UTC).isoformat(),
|
||||
"user_id": user_id,
|
||||
"entity_id": entity_id,
|
||||
}
|
||||
|
||||
sent = await self.manager.broadcast(org_id, message)
|
||||
logger.info(f"Entity deleted event broadcast: {entity_id} to {sent} clients")
|
||||
|
||||
return sent
|
||||
|
||||
async def broadcast_relation_created(
|
||||
self,
|
||||
org_id: str,
|
||||
relation: Dict[str, Any],
|
||||
user_id: str = "system",
|
||||
) -> int:
|
||||
"""관계 생성 이벤트 브로드캐스트.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID
|
||||
relation: 관계 정보
|
||||
user_id: 생성 사용자 ID
|
||||
|
||||
Returns:
|
||||
메시지 수신 클라이언트 수
|
||||
"""
|
||||
message = {
|
||||
"type": "relation.created",
|
||||
"timestamp": datetime.now(UTC).isoformat(),
|
||||
"user_id": user_id,
|
||||
"relation": relation,
|
||||
}
|
||||
|
||||
sent = await self.manager.broadcast(org_id, message)
|
||||
logger.info(f"Relation created event broadcast to {sent} clients")
|
||||
|
||||
return sent
|
||||
|
||||
async def broadcast_relation_deleted(
|
||||
self,
|
||||
org_id: str,
|
||||
relation_id: str,
|
||||
user_id: str = "system",
|
||||
) -> int:
|
||||
"""관계 삭제 이벤트 브로드캐스트.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID
|
||||
relation_id: 관계 ID
|
||||
user_id: 삭제 사용자 ID
|
||||
|
||||
Returns:
|
||||
메시지 수신 클라이언트 수
|
||||
"""
|
||||
message = {
|
||||
"type": "relation.deleted",
|
||||
"timestamp": datetime.now(UTC).isoformat(),
|
||||
"user_id": user_id,
|
||||
"relation_id": relation_id,
|
||||
}
|
||||
|
||||
sent = await self.manager.broadcast(org_id, message)
|
||||
logger.info(f"Relation deleted event broadcast to {sent} clients")
|
||||
|
||||
return sent
|
||||
|
||||
async def broadcast_graph_analyzed(
|
||||
self,
|
||||
org_id: str,
|
||||
analysis_type: str,
|
||||
results: Dict[str, Any],
|
||||
user_id: str = "system",
|
||||
) -> int:
|
||||
"""그래프 분석 완료 이벤트 브로드캐스트.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID
|
||||
analysis_type: 분석 타입 (centrality, communities, etc.)
|
||||
results: 분석 결과
|
||||
user_id: 분석 요청 사용자 ID
|
||||
|
||||
Returns:
|
||||
메시지 수신 클라이언트 수
|
||||
"""
|
||||
message = {
|
||||
"type": "graph.analyzed",
|
||||
"timestamp": datetime.now(UTC).isoformat(),
|
||||
"user_id": user_id,
|
||||
"analysis_type": analysis_type,
|
||||
"results": results,
|
||||
}
|
||||
|
||||
sent = await self.manager.broadcast(org_id, message)
|
||||
logger.info(f"Graph analyzed event broadcast: {analysis_type} to {sent} clients")
|
||||
|
||||
return sent
|
||||
|
||||
async def broadcast_llm_result(
|
||||
self,
|
||||
org_id: str,
|
||||
query: str,
|
||||
answer: str,
|
||||
user_id: str = "system",
|
||||
) -> int:
|
||||
"""LLM 쿼리 결과 브로드캐스트.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID
|
||||
query: 사용자 질문
|
||||
answer: LLM 답변
|
||||
user_id: 쿼리 요청 사용자 ID
|
||||
|
||||
Returns:
|
||||
메시지 수신 클라이언트 수
|
||||
"""
|
||||
message = {
|
||||
"type": "llm.result",
|
||||
"timestamp": datetime.now(UTC).isoformat(),
|
||||
"user_id": user_id,
|
||||
"query": query,
|
||||
"answer": answer[:500], # 처음 500자만
|
||||
}
|
||||
|
||||
sent = await self.manager.broadcast(org_id, message)
|
||||
logger.info(f"LLM result broadcast to {sent} clients")
|
||||
|
||||
return sent
|
||||
|
||||
async def broadcast_error(
|
||||
self,
|
||||
org_id: str,
|
||||
error_message: str,
|
||||
error_type: str = "error",
|
||||
) -> int:
|
||||
"""에러 이벤트 브로드캐스트.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID
|
||||
error_message: 에러 메시지
|
||||
error_type: 에러 타입
|
||||
|
||||
Returns:
|
||||
메시지 수신 클라이언트 수
|
||||
"""
|
||||
message = {
|
||||
"type": f"error.{error_type}",
|
||||
"timestamp": datetime.now(UTC).isoformat(),
|
||||
"message": error_message,
|
||||
}
|
||||
|
||||
sent = await self.manager.broadcast(org_id, message)
|
||||
logger.warning(f"Error broadcast: {error_message} to {sent} clients")
|
||||
|
||||
return sent
|
||||
|
||||
async def broadcast_notification(
|
||||
self,
|
||||
org_id: str,
|
||||
title: str,
|
||||
message: str,
|
||||
severity: str = "info",
|
||||
) -> int:
|
||||
"""일반 알림 브로드캐스트.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID
|
||||
title: 제목
|
||||
message: 메시지
|
||||
severity: 심각도 (info, warning, error)
|
||||
|
||||
Returns:
|
||||
메시지 수신 클라이언트 수
|
||||
"""
|
||||
broadcast_message = {
|
||||
"type": "notification",
|
||||
"timestamp": datetime.now(UTC).isoformat(),
|
||||
"title": title,
|
||||
"message": message,
|
||||
"severity": severity,
|
||||
}
|
||||
|
||||
sent = await self.manager.broadcast(org_id, broadcast_message)
|
||||
logger.info(f"Notification broadcast: {title} to {sent} clients")
|
||||
|
||||
return sent
|
||||
129
ontology_platform/ont_platform/realtime/websocket.py
Normal file
129
ontology_platform/ont_platform/realtime/websocket.py
Normal file
@@ -0,0 +1,129 @@
|
||||
"""WebSocket 연결 관리 (Phase 8).
|
||||
|
||||
기능:
|
||||
- 클라이언트 연결 관리
|
||||
- 조직별 격리
|
||||
- 메시지 브로드캐스트
|
||||
"""
|
||||
|
||||
import logging
|
||||
from typing import Dict, Set, Optional
|
||||
from fastapi import WebSocket
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ConnectionManager:
|
||||
"""WebSocket 연결 관리."""
|
||||
|
||||
def __init__(self):
|
||||
"""초기화."""
|
||||
# org_id → {WebSocket 객체들}
|
||||
self.active_connections: Dict[str, Set[WebSocket]] = {}
|
||||
# WebSocket → org_id (역 매핑)
|
||||
self.connection_to_org: Dict[WebSocket, str] = {}
|
||||
|
||||
async def connect(self, org_id: str, websocket: WebSocket) -> None:
|
||||
"""클라이언트 연결.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID
|
||||
websocket: WebSocket 연결
|
||||
"""
|
||||
await websocket.accept()
|
||||
|
||||
if org_id not in self.active_connections:
|
||||
self.active_connections[org_id] = set()
|
||||
|
||||
self.active_connections[org_id].add(websocket)
|
||||
self.connection_to_org[websocket] = org_id
|
||||
|
||||
logger.info(f"WebSocket connected for org {org_id}")
|
||||
|
||||
async def disconnect(self, websocket: WebSocket) -> None:
|
||||
"""클라이언트 연결 해제.
|
||||
|
||||
Args:
|
||||
websocket: WebSocket 연결
|
||||
"""
|
||||
org_id = self.connection_to_org.get(websocket)
|
||||
|
||||
if org_id:
|
||||
if org_id in self.active_connections:
|
||||
self.active_connections[org_id].discard(websocket)
|
||||
|
||||
if not self.active_connections[org_id]:
|
||||
del self.active_connections[org_id]
|
||||
|
||||
del self.connection_to_org[websocket]
|
||||
|
||||
logger.info(f"WebSocket disconnected for org {org_id}")
|
||||
|
||||
async def broadcast(self, org_id: str, message: dict) -> int:
|
||||
"""조직의 모든 클라이언트에게 메시지 브로드캐스트.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID
|
||||
message: 전송할 메시지
|
||||
|
||||
Returns:
|
||||
전송 성공 수
|
||||
"""
|
||||
if org_id not in self.active_connections:
|
||||
return 0
|
||||
|
||||
disconnected = set()
|
||||
sent_count = 0
|
||||
|
||||
for connection in self.active_connections[org_id]:
|
||||
try:
|
||||
await connection.send_json(message)
|
||||
sent_count += 1
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to send message: {e}")
|
||||
disconnected.add(connection)
|
||||
|
||||
# 연결 끊긴 클라이언트 제거
|
||||
for connection in disconnected:
|
||||
await self.disconnect(connection)
|
||||
|
||||
return sent_count
|
||||
|
||||
async def broadcast_all(self, message: dict) -> int:
|
||||
"""모든 클라이언트에게 메시지 브로드캐스트.
|
||||
|
||||
Args:
|
||||
message: 전송할 메시지
|
||||
|
||||
Returns:
|
||||
전송 성공 수
|
||||
"""
|
||||
total_sent = 0
|
||||
|
||||
for org_id in list(self.active_connections.keys()):
|
||||
sent = await self.broadcast(org_id, message)
|
||||
total_sent += sent
|
||||
|
||||
return total_sent
|
||||
|
||||
def get_connection_count(self, org_id: Optional[str] = None) -> int:
|
||||
"""연결 수 조회.
|
||||
|
||||
Args:
|
||||
org_id: 조직 ID (None이면 전체)
|
||||
|
||||
Returns:
|
||||
연결 수
|
||||
"""
|
||||
if org_id is None:
|
||||
return sum(len(connections) for connections in self.active_connections.values())
|
||||
|
||||
return len(self.active_connections.get(org_id, set()))
|
||||
|
||||
def get_org_ids(self) -> list:
|
||||
"""활성 조직 ID 리스트 조회.
|
||||
|
||||
Returns:
|
||||
조직 ID 리스트
|
||||
"""
|
||||
return list(self.active_connections.keys())
|
||||
Reference in New Issue
Block a user