"""命台席位控制:同一人物同一时刻只有一条前台意识流。 M0 为进程内实现(单人物粒度 asyncio 锁 + 等待计数);多副本部署在标准档 切换 Redis 租约(lingtai-runtime.md §8),接口保持不变。 """ from __future__ import annotations from collections import defaultdict from contextlib import asynccontextmanager from collections.abc import AsyncIterator import asyncio class SeatManager: """人物粒度的前台席位。后台受托 Run(kind=background_task)不占席位。""" def __init__(self) -> None: self._locks: dict[str, asyncio.Lock] = {} self._waiting: dict[str, int] = defaultdict(int) def _lock(self, character_id: str) -> asyncio.Lock: if character_id not in self._locks: self._locks[character_id] = asyncio.Lock() return self._locks[character_id] @asynccontextmanager async def foreground(self, character_id: str) -> AsyncIterator[None]: """占用前台席位;同人物并发请求在此排队(Kernel 不变量 2)。""" lock = self._lock(character_id) if lock.locked(): self._waiting[character_id] += 1 try: async with lock: yield finally: self._waiting[character_id] -= 1 else: async with lock: yield def queue_depth(self, character_id: str) -> int: """该人物当前排队等待前台席位的请求数(HJ-1101 附带信息)。""" return self._waiting.get(character_id, 0)