"""心跳保活服务:扫描 Agent 池,剔除超时未心跳节点。""" import logging import redis.asyncio as aioredis from app.config import settings from app.constants import AgentStatus from app.repository.agent_repo import AgentRepo logger = logging.getLogger(__name__) class HeartbeatService: def __init__(self, redis: aioredis.Redis, agent_repo: AgentRepo | None = None): self.redis = redis self.agent_repo = agent_repo or AgentRepo(redis) async def scan(self) -> int: """扫描并剔除超时 Agent,返回剔除数量。""" stale = await self.agent_repo.stale_agents(settings.agent_heartbeat_timeout) for aid in stale: await self.agent_repo.update_status(aid, AgentStatus.OFFLINE) logger.info("heartbeat: agent offline (stale) agent_id=%s", aid) return len(stale)