Improve Redis key handling and spectator sync logic
Enhances Redis key type checks and cleanup in message system, adds periodic cleanup task, and improves error handling for Redis operations. Refines multiplayer and spectator hub logic to better synchronize player states and prevent invalid spectator sessions. Adds more detailed logging for channel/user join/leave events and spectator watch requests.
This commit is contained in:
@@ -76,6 +76,20 @@ class ChatServer:
|
||||
async def broadcast(self, channel_id: int, event: ChatEvent):
|
||||
users_in_channel = self.channels.get(channel_id, [])
|
||||
logger.info(f"Broadcasting to channel {channel_id}, users: {users_in_channel}")
|
||||
|
||||
# 如果频道中没有用户,检查是否是多人游戏频道
|
||||
if not users_in_channel:
|
||||
try:
|
||||
async with with_db() as session:
|
||||
from sqlmodel import select
|
||||
channel = await session.get(ChatChannel, channel_id)
|
||||
if channel and channel.type == ChannelType.MULTIPLAYER:
|
||||
logger.warning(f"No users in multiplayer channel {channel_id}, message will not be delivered to anyone")
|
||||
# 对于多人游戏房间,这可能是正常的(用户都离开了房间)
|
||||
# 但我们仍然记录这个情况以便调试
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to check channel type for {channel_id}: {e}")
|
||||
|
||||
for user_id in users_in_channel:
|
||||
await self.send_event(user_id, event)
|
||||
logger.debug(f"Sent event to user {user_id} in channel {channel_id}")
|
||||
@@ -199,12 +213,15 @@ class ChatServer:
|
||||
# 使用明确的查询避免延迟加载
|
||||
db_channel = (await session.exec(select(ChatChannel).where(ChatChannel.channel_id == channel_id))).first()
|
||||
if db_channel is None:
|
||||
logger.warning(f"Attempted to join non-existent channel {channel_id} by user {user_id}")
|
||||
return
|
||||
|
||||
user = await session.get(User, user_id)
|
||||
if user is None:
|
||||
logger.warning(f"Attempted to join channel {channel_id} by non-existent user {user_id}")
|
||||
return
|
||||
|
||||
logger.info(f"User {user_id} joining channel {channel_id} (type: {db_channel.type.value})")
|
||||
await self.join_channel(user, db_channel, session)
|
||||
|
||||
async def leave_room_channel(self, channel_id: int, user_id: int):
|
||||
@@ -212,12 +229,15 @@ class ChatServer:
|
||||
# 使用明确的查询避免延迟加载
|
||||
db_channel = (await session.exec(select(ChatChannel).where(ChatChannel.channel_id == channel_id))).first()
|
||||
if db_channel is None:
|
||||
logger.warning(f"Attempted to leave non-existent channel {channel_id} by user {user_id}")
|
||||
return
|
||||
|
||||
user = await session.get(User, user_id)
|
||||
if user is None:
|
||||
logger.warning(f"Attempted to leave channel {channel_id} by non-existent user {user_id}")
|
||||
return
|
||||
|
||||
logger.info(f"User {user_id} leaving channel {channel_id} (type: {db_channel.type.value})")
|
||||
await self.leave_channel(user, db_channel, session)
|
||||
|
||||
async def new_private_notification(self, detail: NotificationDetail):
|
||||
|
||||
Reference in New Issue
Block a user