本次提交完成了一系列核心功能迭代与优化: 1. 新增并完善了多个领域模型与端口定义,补充了`__all__`导出规范 2. 优化了会话、绑定、出箱等模块的数据模型,修复了时间字段类型不一致问题 3. 新增了代理ID解析、缓存发布等接口,扩展了系统能力 4. 重构了去重中间件逻辑,优化了空内容校验规则 5. 新增了认证中间件的匿名访问支持,完善了鉴权流程 6. 优化了SSE连接管理,增加了单会话连接上限限制 7. 重构了消息日志与仓储相关代码,将数据类迁移至对应模型目录 8. 新增了重复绑定校验、绑定更新接口,完善了绑定服务逻辑 9. 优化了健康检查逻辑,新增了环境变量控制启动时间线展示 10. 重构了出箱重试工作线程,使用缓存端口替代直接redis操作,新增了消息处理标记逻辑 11. 完善了飞书、Web、钩子等通道的翻译器逻辑,补充了账户ID传递 12. 新增了多种自定义异常类型,优化了异常映射与错误处理流程 13. 完善了配置热重载逻辑,同步认证凭证与校验器配置 14. 重构了Redis缓存实现,增加了异常捕获与包装
140 lines
4.8 KiB
Python
140 lines
4.8 KiB
Python
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import logging
|
|
import os
|
|
|
|
from fastapi import APIRouter, Depends
|
|
from fastapi.responses import JSONResponse
|
|
from pydantic import BaseModel
|
|
from sqlalchemy import select
|
|
|
|
from yuxi.channel.container import ChannelContainer, get_channel
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
router = APIRouter()
|
|
|
|
|
|
class HealthzResponse(BaseModel):
|
|
status: str = "ok"
|
|
startup_timeline: list[dict] | None = None
|
|
|
|
|
|
class ReadyzComponentStatus(BaseModel):
|
|
status: str
|
|
detail: str | None = None
|
|
|
|
|
|
class ReadyzResponse(BaseModel):
|
|
status: str
|
|
redis: ReadyzComponentStatus | None = None
|
|
postgres: ReadyzComponentStatus | None = None
|
|
workers: ReadyzComponentStatus | None = None
|
|
channels: ReadyzComponentStatus | None = None
|
|
ws_connections: ReadyzComponentStatus | None = None
|
|
|
|
|
|
@router.get("/healthz", response_model=HealthzResponse)
|
|
async def liveness_check(channel: ChannelContainer = Depends(get_channel)):
|
|
show_timeline = os.getenv("CHANNEL_SHOW_STARTUP_TIMELINE", "false").lower() == "true"
|
|
return HealthzResponse(
|
|
status="ok",
|
|
startup_timeline=channel.startup_tracer.to_dict() if show_timeline else None,
|
|
)
|
|
|
|
|
|
@router.get("/readyz")
|
|
async def readiness_check(channel: ChannelContainer = Depends(get_channel)):
|
|
keys = ["redis", "postgres", "workers", "channels", "ws_connections"]
|
|
results = await asyncio.gather(
|
|
_check_redis(channel),
|
|
_check_postgres(),
|
|
_check_workers(channel),
|
|
_check_channels(channel),
|
|
_check_ws_connections(channel),
|
|
)
|
|
checks = dict(zip(keys, results))
|
|
|
|
has_error = any(v.status == "error" for v in checks.values())
|
|
has_degraded = any(v.status == "degraded" for v in checks.values())
|
|
|
|
if has_error:
|
|
overall, status_code = "not_ready", 503
|
|
elif has_degraded:
|
|
overall, status_code = "degraded", 200
|
|
else:
|
|
overall, status_code = "ready", 200
|
|
|
|
return JSONResponse(
|
|
status_code=status_code,
|
|
content=ReadyzResponse(status=overall, **checks).model_dump(),
|
|
)
|
|
|
|
|
|
async def _check_redis(container: ChannelContainer) -> ReadyzComponentStatus:
|
|
try:
|
|
if container and container.redis:
|
|
await container.redis.ping()
|
|
return ReadyzComponentStatus(status="ok")
|
|
except Exception as exc:
|
|
logger.warning("redis check failed: %s", exc)
|
|
return ReadyzComponentStatus(status="error", detail="connection refused")
|
|
|
|
|
|
async def _check_postgres() -> ReadyzComponentStatus:
|
|
try:
|
|
from yuxi.storage.postgres.manager import pg_manager
|
|
|
|
if not pg_manager.is_initialized:
|
|
return ReadyzComponentStatus(status="error", detail="not initialized")
|
|
async with pg_manager.get_async_session_context() as session:
|
|
await session.execute(select(1))
|
|
return ReadyzComponentStatus(status="ok")
|
|
except Exception as exc:
|
|
logger.warning("postgres check failed: %s", exc)
|
|
return ReadyzComponentStatus(status="error", detail="connection refused")
|
|
|
|
|
|
async def _check_workers(container: ChannelContainer) -> ReadyzComponentStatus:
|
|
try:
|
|
if container and container.worker_pool and container.worker_pool.is_running:
|
|
return ReadyzComponentStatus(status="ok")
|
|
except Exception as exc:
|
|
logger.warning("workers check failed: %s", exc)
|
|
return ReadyzComponentStatus(status="error", detail="no active consumers")
|
|
|
|
|
|
async def _check_channels(container: ChannelContainer) -> ReadyzComponentStatus:
|
|
try:
|
|
if container and container.adapters:
|
|
results = await asyncio.gather(
|
|
*[a.is_healthy() for a in container.adapters.values()],
|
|
return_exceptions=True,
|
|
)
|
|
unhealthy = [name for name, r in zip(container.adapters, results) if r is not True]
|
|
if not unhealthy:
|
|
return ReadyzComponentStatus(status="ok")
|
|
return ReadyzComponentStatus(
|
|
status="degraded",
|
|
detail=f"unhealthy channels: {', '.join(unhealthy)}",
|
|
)
|
|
except Exception as exc:
|
|
logger.warning("channels check failed: %s", exc)
|
|
return ReadyzComponentStatus(status="error", detail="no adapters")
|
|
|
|
|
|
async def _check_ws_connections(container: ChannelContainer) -> ReadyzComponentStatus:
|
|
if not container or not container.ws_manager:
|
|
return ReadyzComponentStatus(status="ok", detail="no ws connections")
|
|
status_map = container.ws_manager.connections_status
|
|
if not status_map:
|
|
return ReadyzComponentStatus(status="ok", detail="no ws connections registered")
|
|
disconnected = [ct for ct, ok in status_map.items() if not ok]
|
|
if not disconnected:
|
|
return ReadyzComponentStatus(status="ok")
|
|
return ReadyzComponentStatus(
|
|
status="degraded",
|
|
detail=f"disconnected: {', '.join(disconnected)}",
|
|
)
|