diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index b99a8ba..e023d5b 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -1,36 +1,37 @@ -# XPack 开源版本 - Copilot 编程指导 +# XPack Open Source Edition - Copilot Programming Guidelines -## 项目架构 +## Project Architecture -### 服务依赖 -- `admin_service` 和 `api_service` 相互独立,都依赖 `common` -- 遵循分层架构:Controller → Service → Repository +### Service Dependencies +- `admin_service` and `api_service` are independent of each other, both depend on `common` +- Follow layered architecture: Controller → Service → Repository -### 目录结构 +### Directory Structure ``` services/ -├── admin_service/ # 管理端服务 -├── api_service/ # API服务 -└── common/ # 公共模块 +├── admin_service/ # Admin service +├── api_service/ # API service +└── common/ # Common modules ``` -## 编码规范 +## Coding Standards -### 代码风格 -- 遵循 PEP 8,使用类型注解和 docstring -- 命名:函数/变量用 `snake_case`,类用 `PascalCase` -- 导入:优先使用 `services/common`,避免跨服务导入 +### Code Style +- Follow PEP 8, use type annotations and docstrings +- Naming: use `snake_case` for functions/variables, `PascalCase` for classes +- Imports: prioritize `services/common`, avoid cross-service imports -### 日志要求 -- **必须使用英文**,使用 `services/common/logging_config.py` -- 格式:`logger.info("Action completed: {context}")` -- 避免敏感信息,包含必要上下文 +### Logging Requirements +- **Must use English**, use `services/common/logging_config.py` +- Format: `logger.info("Action completed: {context}")` +- Avoid sensitive information, include necessary context -### 错误处理 -- 使用 `services/common/error_msg.py` 定义的错误消息 -- 统一异常处理和日志记录 +### Error Handling +- Use error messages defined in `services/common/error_msg.py` +- Unified exception handling and logging -## 开发建议 -- 有适当的日志记录(英文格式,统一格式) -- 添加方法级别英文注释,需要简洁 -- 添加的注释一律使用英文 \ No newline at end of file +## Development Guidelines +- Think and analyze requirements first, wait for user confirmation before writing code +- Include appropriate logging (English format, consistent style) +- Add method-level English comments, keep them concise +- All comments must be written in English \ No newline at end of file diff --git a/services/admin_service/controllers/sys_config.py b/services/admin_service/controllers/sys_config.py index 6072d1a..d95c60a 100644 --- a/services/admin_service/controllers/sys_config.py +++ b/services/admin_service/controllers/sys_config.py @@ -7,7 +7,11 @@ from services.common.utils.response_utils import ResponseUtils from services.common.utils.email_utils import EmailUtils from services.admin_service.services.sys_config_service import SysConfigService from services.admin_service.services.user_service import UserService +from services.admin_service.services.platform_report_service import PlatformReportService from services.admin_service.constants import sys_config_key +from services.common.logging_config import get_logger + +logger = get_logger(__name__) router = APIRouter() @@ -266,6 +270,33 @@ def set_sysconfig( is_large = True sysconfig_service.set_value_by_key(key, value, desc,is_large) + # Report platform information asynchronously to avoid impacting main operations + try: + platform_report_service = PlatformReportService() + + # Prepare platform data for reporting + platform_report_data = { + "name": platform_name, + "logo": platform_logo, + "url": platform_url, + "website_title": website_title, + "headline": headline, + "subheadline": subheadline, + "language": language, + "theme": theme, + "domain": domain, + "is_showcased": is_showcased, + "mcp_server_prefix": mcp_server_prefix, + } + + # Use background reporting to avoid blocking the main configuration update + platform_report_service.report_platform_info_background(platform_report_data) + logger.debug("Platform information reporting initiated in background") + + except Exception as e: + # Log error but continue with main operation - reporting failure should not affect configuration update + logger.warning(f"Failed to initiate platform reporting: {e}") + return get_sysconfig(sysconfig_service, user_service) except Exception as e: diff --git a/services/admin_service/services/platform_report_service.py b/services/admin_service/services/platform_report_service.py new file mode 100644 index 0000000..d3753c1 --- /dev/null +++ b/services/admin_service/services/platform_report_service.py @@ -0,0 +1,165 @@ +""" +Platform Report Service + +This service handles reporting platform information to the official XPack platform +when is_showcased is enabled. +""" + +import asyncio +from typing import Optional, Dict, Any +from services.common.logging_config import get_logger +from services.common.utils.http_utils import HttpUtils +from services.common.exceptions import ServiceUnavailableException, InternalServerException + +logger = get_logger(__name__) + + +class PlatformReportService: + """Service for reporting platform information to XPack official platform""" + + # Official XPack platform reporting endpoint + XPACK_REPORT_URL = "https://platform.xpack.ai/v1/cases/report" + + def __init__(self): + """Initialize platform report service""" + self.http_utils = HttpUtils() + + async def report_platform_info(self, platform_data: Dict[str, Any]) -> bool: + """ + Report platform information to XPack official platform + + Args: + platform_data: Platform configuration data containing: + - name: Platform name + - logo: Platform logo URL + - url: Platform URL + - website_title: Website title + - headline: Homepage headline + - subheadline: Homepage subheadline + - language: Platform language + - theme: Platform theme + - domain: Platform domain + - is_showcased: Whether to showcase on XPack website + - mcp_server_prefix: MCP server prefix + + Returns: + bool: True if report was successful, False otherwise + """ + try: + # Validate required fields + if not self._validate_platform_data(platform_data): + logger.warning("Platform data validation failed, skipping report") + return False + + # Check if showcasing is enabled + if not platform_data.get("is_showcased", False): + logger.info("Platform showcasing is disabled, skipping report") + return True + + # Prepare report payload + report_payload = { + "platform": { + "name": platform_data.get("name", ""), + "logo": platform_data.get("logo", ""), + "url": platform_data.get("url", ""), + "website_title": platform_data.get("website_title", ""), + "domain": platform_data.get("domain", ""), + "headline": platform_data.get("headline", ""), + "subheadline": platform_data.get("subheadline", ""), + "language": platform_data.get("language", ""), + "is_showcased": platform_data.get("is_showcased", False), + "mcp_server_prefix": platform_data.get("mcp_server_prefix", ""), + } + } + + logger.info(f"Reporting platform information to XPack platform: {platform_data.get('name', 'Unknown')}") + + # Send report to XPack platform + response = await self.http_utils.post_json( + url=self.XPACK_REPORT_URL, data=report_payload, timeout=15 # Reduced timeout to avoid blocking main operations + ) + + logger.info(f"Platform report successful: {response}") + return True + + except ServiceUnavailableException as e: + logger.error(f"Failed to report platform info due to network issue: {e}") + return False + except InternalServerException as e: + logger.error(f"Failed to report platform info due to internal error: {e}") + return False + except Exception as e: + logger.error(f"Unexpected error during platform reporting: {e}") + return False + + def _validate_platform_data(self, platform_data: Dict[str, Any]) -> bool: + """ + Validate platform data before reporting + + Args: + platform_data: Platform data to validate + + Returns: + bool: True if data is valid, False otherwise + """ + required_fields = ["name"] + + for field in required_fields: + if not platform_data.get(field): + logger.warning(f"Missing required field for platform report: {field}") + return False + + return True + + def report_platform_info_sync(self, platform_data: Dict[str, Any]) -> bool: + """ + Synchronous wrapper for reporting platform information + This method is designed to be non-blocking and fail-safe to avoid impacting main business logic. + + Args: + platform_data: Platform configuration data + + Returns: + bool: True if report was successful, False otherwise + """ + try: + # Try to get the current event loop + try: + loop = asyncio.get_running_loop() + # If we're already in an event loop, use asyncio.create_task + import concurrent.futures + + with concurrent.futures.ThreadPoolExecutor() as executor: + future = executor.submit(asyncio.run, self.report_platform_info(platform_data)) + # Reduced timeout to avoid blocking main operations + return future.result(timeout=30) + except RuntimeError: + # No event loop running, create a new one + return asyncio.run(self.report_platform_info(platform_data)) + except Exception as e: + # Log error but don't propagate to avoid affecting main business logic + logger.warning(f"Platform reporting failed but continuing with main operation: {e}") + return False + + def report_platform_info_background(self, platform_data: Dict[str, Any]) -> None: + """ + Background reporting method that runs asynchronously without blocking main operations. + This method is fire-and-forget style to ensure zero impact on main business logic. + + Args: + platform_data: Platform configuration data + """ + import threading + + def _background_report(): + try: + # Use a shorter timeout for background operations + self.report_platform_info_sync(platform_data) + except Exception as e: + # Silently handle any exceptions to avoid affecting main operations + logger.debug(f"Background platform reporting completed with issues: {e}") + + # Start reporting in background thread + thread = threading.Thread(target=_background_report, daemon=True) + thread.start() + logger.debug("Platform reporting started in background thread")