From 1c0c665b5cc615e42b42e633d8f5166a5210100d Mon Sep 17 00:00:00 2001 From: Blank Date: Tue, 27 Oct 2026 12:31:54 +0800 Subject: [PATCH 1/2] =?UTF-8?q?fix(core):=20=E9=A1=B6=E5=8F=B7=E6=B5=81?= =?UTF-8?q?=E7=A8=8B=E6=8C=89=20playerId=20=E4=B8=B2=E8=A1=8C=E5=8C=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit UpdateSessionAsync 的读旧会话→通知→关闭→移除→绑定→路由上线关键段 此前无互斥:同玩家并发登录可双活绑定、互踢/自踢,路由版本交错重复 递增致消息路由错误(GFX-1018)。现经 PlayerLoginLocks 按 playerId 互斥 串行——锁协议为 GetOrAdd→WaitAsync→映射复核(失败让位重取)→关键段→ 持锁 TryRemove→Release,持锁回收使锁表仅驻留 in-flight 登录条目,天然 有界且规避计数/等待数探测式回收固有的 check-then-remove 竞态;另加同 会话重登守卫(同 sessionId 不再自通知/自关闭,幂等重绑)。新增 PlayerSessionManagerConcurrentLoginTests 两用例(TaskCompletionSource 确定性竞态放大,旧代码必败)。 Linear: GFX-1018 --- CHANGELOG.md | 1 + .../Session/PlayerSessionManager.cs | 108 +++++++-- ...layerSessionManagerConcurrentLoginTests.cs | 207 ++++++++++++++++++ 3 files changed, 299 insertions(+), 17 deletions(-) create mode 100644 Tests/GameFrameX.Tests/Core/Session/PlayerSessionManagerConcurrentLoginTests.cs diff --git a/CHANGELOG.md b/CHANGELOG.md index 697d4fbe5..c35be3cdb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -132,6 +132,7 @@ * 统一启动形态为「宿主持监听 + 热更持业务生命周期」(C284,Game 归一 Social 形态):缺省 `StartRoleServicesAsync` 由同步 `LoadHotfix` 改为 `await LoadHotfixModule`——全 18 Role 装载即激活热更生命周期(配置表/定时器/全局组件经桥接 `OnLoadSuccess`;此前不含 Game 的 Role 组合单起时全部不执行,Social 业务落地热更当天会踩),`--AllInOne` 重复装载由同路径幂等守卫短路;`AppStartUpGame` 不再自拟启动序列(`base` 缺省调用 + Online 双闸附加),KCP 登录流白名单(`ReqLogin/ReqPlayerList/ReqPlayerCreate/ReqPlayerLogin/ReqSessionResume`)与 `OnConnected`(MaxClientCount 拒绝 + `PlayerSession` 建立)/`OnDisconnected` 会话钩子上移宿主覆写,`PackageHandler`/`OnStartupCompletedAsync`/`OnStoppingAsync` 三覆写退役;断线业务段(房间断线标记 + 会话恢复通知)经新增共享事件 `Core.Session.PlayerDisconnectedEventArgs` + 热更 `PlayerDisconnectedEventListener` 全局监听器桥接;热更侧 `AppStartUpHotfixGame` 的 `OnLoadSuccess` 收窄纯生命周期激活(`RunServer`/`StartAsync`/`ReplyHeartBeatAsync` 退役,ByMain/ByHeart 删除)、bridge `Stop` 收窄纯业务清理(Actor/定时器/会话),监听不再活在可收集 ALC 内(消除热切换 Retire 卸载验证必然失败与 ALC 泄漏);`ServiceOnline`/`ServiceOffline` 单源化为宿主缺省分发(热更侧分发删除,避免非首装载 Role 双派发),Game 起服由两组启动序列归一为一组。 ### Bug Fixes +* 顶号流程按 playerId 串行化(C306,GFX-1018 / GitHub #647):`PlayerSessionManager.UpdateSessionAsync` 的读旧会话→通知→关闭→移除→绑定→路由上线关键段此前无互斥,同玩家并发登录可双活绑定、互踢/自踢,路由版本交错重复递增致消息路由错误;现经 `PlayerLoginLocks`(`ConcurrentDictionary`)串行——锁协议为 GetOrAdd→WaitAsync→映射复核(失败让位重取)→关键段→持锁 TryRemove(键值对)→Release,持锁回收使锁表仅驻留 in-flight 登录条目(天然有界,规避计数/等待数探测式回收固有的 check-then-remove 竞态);另加同会话重登守卫(`oldSession.SessionId == sessionId` 不再自通知/自关闭,幂等重绑)。公开接口零变化;新增确定性竞态放大并发回归测试 `PlayerSessionManagerConcurrentLoginTests`。 * 热更 Wrapper 源码生成器修复并恢复组件代理 Actor 串行化(C292):生成器引用的 Roslyn(5.6.0/5.9.0)高于 SDK 自带编译器,CS9057 下长期静默不加载,`HotfixModule.GetAgent` 回落到未串行化的原始代理。修复三件——生成类命名空间镜像代理源命名空间(`GameFrameX.Hotfix.Wrapper.Agent.<镜像段>`,同名代理 Player/Login 与 ServerRole/Login 的 `LoginComponentAgent` 分落互不冲突,此前固定单一命名空间 + 短名 hintName 在生成器真跑时即崩溃 CS8785)、hintName 由完全限定名单射净化(`.`→`_`、`+`→`__`)、分部类计数键改完全限定名;`Microsoft.CodeAnalysis.CSharp` 对齐 global.json 基线 5.0.0(与 Architecture.Analyzers 同约定)。**行为变更披露**:生成器恢复加载后,`[Service]`(非 `[ThreadSafe]`)等被包装的代理方法恢复经 `WorkerActor.EnqueueAsync` 在 Actor 队列串行化执行(并发调用可能排队),`[ThreadSafe]` 方法不受影响;新增装配护栏 `AgentWrapperAssemblyGuardTests` 防生成器再次静默停摆。全解决方案构建 0 错 0 警告(C291 遗留的 CS9057 已知例外随之关闭)。 * GameDb 门面生命周期三修(C267 / GFX-907):①`GameDb.CloseAsync()` 关停即卸载——关闭全部注册库后清空 `MultiDbRegistry` 与门面静态状态(个别库 Close 抛出也经 finally 完成卸载,异常照常传播),close→reopen 同名重注册不再被残留注册表挡在 `AlreadyRegistered`,关停后门面 CRUD 回到未初始化快速失败而非使用已关停服务;②`InitCore` 的 `IsDefault` 提名 set-once 异名冲突回滚——`MultiDbRegistry.Unregister` + 释放已打开连接后重抛原异常,废除「冲突在注册后传播、靠进程退出兜底」旧语义,Init 失败不在注册表/门面留半初始化残留(新增 `MultiDbRegistry.Unregister(string)` internal,统一入口铁律:消费方仍只经 GameDb);③删除同步 `GameDb.Close()`(`GetAwaiter().GetResult()` sync-over-async,线程饥饿/死锁面;全仓与消费仓零调用实证),异步 `CloseAsync` 为唯一关停入口。 diff --git a/GameFrameX.Core/Session/PlayerSessionManager.cs b/GameFrameX.Core/Session/PlayerSessionManager.cs index 11cf447df..60300807f 100644 --- a/GameFrameX.Core/Session/PlayerSessionManager.cs +++ b/GameFrameX.Core/Session/PlayerSessionManager.cs @@ -57,6 +57,16 @@ private PlayerSessionManager() private readonly ConcurrentDictionary SessionMap = new(); private readonly ConcurrentDictionary PlayerRouteMap = new(); + /// + /// 顶号串行锁表:playerId → in-flight 登录的互斥信号量(C306)。 + /// + /// + /// Per-player login serialization semaphores. The dictionary only holds entries for + /// in-flight logins — reclaims the entry while still + /// holding the semaphore, so the map never grows with the historical player count. + /// + private readonly ConcurrentDictionary PlayerLoginLocks = new(); + /// /// 玩家路由外发同步目标(控制库写入钩子)。 /// @@ -266,6 +276,8 @@ public void Add(IPlayerSession session) /// /// 更新会话,处理玩家ID和签名的更新。 /// 如果玩家ID已在其他设备上登录,则会通知旧会话并关闭其连接。 + /// 同一玩家的并发登录按 串行化:后进入者把先完成者判为旧会话(顶号), + /// 任一时刻至多一个绑定生效(C306)。 /// /// 会话ID,用于标识当前会话 /// 玩家ID,表示当前会话所关联的玩家 @@ -277,29 +289,91 @@ public void Add(IPlayerSession session) /// public async Task UpdateSessionAsync(string sessionId, long playerId, string sign, Func duplicateLoginNotifier) { - // 获取与玩家ID关联的旧会话 - var oldSession = GetByPlayerId(playerId); - if (oldSession != null) + // 顶号关键段按 playerId 互斥串行(C306):读旧会话→通知→关闭→移除→绑定→路由上线必须作为整体执行, + // 否则并发登录可双活绑定 / 互踢 / 路由版本重复递增(GFX-1018)。 + var loginLock = await AcquireLoginLockAsync(playerId); + try { - // 内联 await 顶号通知(须先于 Close,理由见参数注释) - await duplicateLoginNotifier(oldSession); - // 清除旧会话的连接数据并关闭连接 - oldSession.WorkChannel.ClearData(); - oldSession.WorkChannel.Close(); - // 这里先移除,等待Disconnected回调断开在移除的话有延迟 - Remove(oldSession.SessionId); + // 获取与玩家ID关联的旧会话;同一会话重登(同 sessionId)不触发顶号,幂等重绑 + var oldSession = GetByPlayerId(playerId); + if (oldSession != null && oldSession.SessionId != sessionId) + { + // 内联 await 顶号通知(须先于 Close,理由见参数注释) + await duplicateLoginNotifier(oldSession); + // 清除旧会话的连接数据并关闭连接 + oldSession.WorkChannel.ClearData(); + oldSession.WorkChannel.Close(); + // 这里先移除,等待Disconnected回调断开在移除的话有延迟 + Remove(oldSession.SessionId); + } + + // 获取当前会话并更新玩家ID和签名 + var session = Get(sessionId); + if (session.IsNull()) + { + return; + } + + session.SetPlayerId(playerId); + session.SetSign(sign); + SetPlayerRouteOnline(playerId); + } + finally + { + ReleaseLoginLock(playerId, loginLock); } + } - // 获取当前会话并更新玩家ID和签名 - var session = Get(sessionId); - if (session.IsNull()) + /// + /// 获取指定玩家的登录串行锁:等待信号量后复核字典映射仍为本实例,否则让位重取。 + /// + /// 玩家ID。 + /// 已持有的、且当前仍被 映射的信号量。 + /// + /// Mutual-exclusion invariant: a holder that passes the mapping re-check can never be + /// concurrent with another validated holder of a different instance, because the mapping + /// for a key can only be removed by a thread that holds the mapped instance (removal + /// happens inside the critical section, before Release), and a new instance is + /// only inserted while the key is absent. A waiter whose instance got retired mid-wait + /// fails the re-check, releases, and retries with the current mapping — a brief liveness + /// cost with no exclusivity loss. + /// + private async Task AcquireLoginLockAsync(long playerId) + { + while (true) { - return; + var semaphore = PlayerLoginLocks.GetOrAdd(playerId, _ => new SemaphoreSlim(1, 1)); + await semaphore.WaitAsync(); + + // 复核:等待期间本条目可能已被持锁者回收并替换,此实例不再代表该玩家的互斥权 + if (PlayerLoginLocks.TryGetValue(playerId, out var mapped) && ReferenceEquals(mapped, semaphore)) + { + return semaphore; + } + + semaphore.Release(); } + } - session.SetPlayerId(playerId); - session.SetSign(sign); - SetPlayerRouteOnline(playerId); + /// + /// 释放指定玩家的登录串行锁:先在持锁状态下回收字典条目,再释放信号量。 + /// + /// 玩家ID。 + /// 由 返回的信号量。 + /// + /// Reclaim-while-held: removing the entry before Release guarantees every removal + /// happens under the semaphore, which is exactly the invariant + /// relies on. The lock map therefore stays bounded to + /// in-flight logins without idle-detection heuristics — count/waiting-probe reclamation has + /// an inherent check-then-remove race that can let two different semaphore instances be + /// treated as authoritative concurrently. + /// + private void ReleaseLoginLock(long playerId, SemaphoreSlim semaphore) + { + // 持锁期间映射不可能被他人改写(移除只发生在持锁者手里、插入要求键缺席,见 AcquireLoginLockAsync + // 不变式),故按键移除即精确回收本实例;随后释放信号量,唤醒的等待方经映射复核让位重取 + PlayerLoginLocks.TryRemove(playerId, out _); + semaphore.Release(); } /// diff --git a/Tests/GameFrameX.Tests/Core/Session/PlayerSessionManagerConcurrentLoginTests.cs b/Tests/GameFrameX.Tests/Core/Session/PlayerSessionManagerConcurrentLoginTests.cs new file mode 100644 index 000000000..6296ad6dd --- /dev/null +++ b/Tests/GameFrameX.Tests/Core/Session/PlayerSessionManagerConcurrentLoginTests.cs @@ -0,0 +1,207 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legal rights and interests of others, as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本项目组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using GameFrameX.Core.Session; +using GameFrameX.Network.Abstractions; +using GameFrameX.SuperSocket.Server.Abstractions.Session; +using Xunit; + +namespace GameFrameX.Tests.Core.Session; + +/// +/// 顶号串行化单测(C306 / GFX-1018):同 playerId 并发登录的关键段互斥—— +/// TaskCompletionSource 把第二登录阻塞在通知器内(关键段中段)确定性放大读-判-改竞态窗口, +/// 第三登录并发进入必须等第二登录整体完成后才顶号,收敛为单一幸存绑定; +/// 同会话重登(同 sessionId)不触发顶号通知、不关闭自身通道,幂等重绑。 +/// +public sealed class PlayerSessionManagerConcurrentLoginTests +{ + [Fact] + public async Task UpdateSession_ConcurrentSamePlayerLogins_ShouldSerializeToSingleSurvivor() + { + var manager = PlayerSessionManager.Instance; + const long playerId = 930001; + + // 底座:第一会话先完成登录绑定,作为后续并发段落的"旧会话" + var firstChannel = new FakeNetworkChannel(); + var firstSession = new PlayerSession("c306-first", firstChannel); + manager.Add(firstSession); + await manager.UpdateSessionAsync("c306-first", playerId, "sign-0", _ => Task.CompletedTask); + + var secondChannel = new FakeNetworkChannel(); + var secondSession = new PlayerSession("c306-second", secondChannel); + manager.Add(secondSession); + + var thirdChannel = new FakeNetworkChannel(); + manager.Add(new PlayerSession("c306-third", thirdChannel)); + + // 第二登录进入关键段后在通知器内阻塞:notifierEntered 置位时它已持有该玩家的串行锁 + var notifierEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var releaseGate = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var secondLogin = manager.UpdateSessionAsync("c306-second", playerId, "sign-2", async old => + { + // 第二登录先进入,看到的旧会话必须是底座第一会话 + Assert.Same(firstSession, old); + notifierEntered.SetResult(true); + await releaseGate.Task; + }); + await notifierEntered.Task; + + // 第三登录并发进入:串行化下必须阻塞在锁上(通知器不可能先于放行触发); + // 无锁旧代码会立即以第一会话为旧会话完成顶号(探测到即继续,最终断言会暴露双活绑定) + IPlayerSession thirdNotifiedOld = null; + var thirdNotifierEntered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var thirdLogin = manager.UpdateSessionAsync("c306-third", playerId, "sign-3", old => + { + thirdNotifiedOld = old; + thirdNotifierEntered.TrySetResult(true); + return Task.CompletedTask; + }); + await Task.WhenAny(thirdNotifierEntered.Task, Task.Delay(TimeSpan.FromSeconds(1))); + + // 放行第二登录,等待两段登录全部完成 + releaseGate.SetResult(true); + await secondLogin; + await thirdLogin; + + // 串行化收敛:同 playerId 恰一个绑定存活(无锁旧代码此处为 2——第二/第三双活绑定) + var bound = manager.GetList(m => m.PlayerId == playerId); + Assert.Single(bound); + var survivor = manager.GetByPlayerId(playerId); + Assert.NotNull(survivor); + Assert.Equal("c306-third", survivor.SessionId); + Assert.Equal(playerId, survivor.PlayerId); + Assert.Equal("sign-3", survivor.Sign); + Assert.False(thirdChannel.IsClosed()); + + // 第三登录顶掉的旧会话 = 第二会话(而非底座第一会话),证明它等待了第二登录整体完成 + Assert.Same(secondSession, thirdNotifiedOld); + Assert.True(secondChannel.IsClosed()); + Assert.Null(manager.Get("c306-second")); + + // 底座第一会话被第二登录顶掉:通知后关闭并移除 + Assert.True(firstChannel.IsClosed()); + Assert.Null(manager.Get("c306-first")); + } + + [Fact] + public async Task UpdateSession_SameSessionRebind_ShouldNotKickSelf() + { + var manager = PlayerSessionManager.Instance; + const long playerId = 930002; + + var channel = new FakeNetworkChannel(); + var session = new PlayerSession("c306-rebind", channel); + manager.Add(session); + await manager.UpdateSessionAsync("c306-rebind", playerId, "sign-a", _ => Task.CompletedTask); + + var notified = false; + await manager.UpdateSessionAsync("c306-rebind", playerId, "sign-b", _ => + { + notified = true; + return Task.CompletedTask; + }); + + // 同会话重登不触发顶号通知(无守卫旧代码会把自己判为旧会话:自通知 + 自关闭 + 自移除) + Assert.False(notified); + var current = manager.Get("c306-rebind"); + Assert.NotNull(current); + Assert.Same(session, current); + Assert.Equal(playerId, current.PlayerId); + Assert.Equal("sign-b", current.Sign); + Assert.False(channel.IsClosed()); + } + + /// + /// 最小网络通道假件:仅实现 SetData / ClearData / Close / IsClosed 的状态语义,其余成员为空实现。 + /// + private sealed class FakeNetworkChannel : INetworkChannel + { + private readonly Dictionary _data = new(); + private bool _closed; + + public ulong SendBytesLength => 0; + + public ulong SendPacketLength => 0; + + public ulong ReceiveBytesLength => 0; + + public ulong ReceivePacketLength => 0; + + public IGameAppSession GameAppSession => null; + + public Task WriteAsync(INetworkMessage msg, int errorCode = 0) + { + return Task.CompletedTask; + } + + public void Close() + { + _closed = true; + } + + public T GetData(string key) + { + return _data.TryGetValue(key, out var value) ? (T)value : default; + } + + public void ClearData() + { + _data.Clear(); + } + + public void RemoveData(string key) + { + _data.Remove(key); + } + + public void SetData(string key, object value) + { + _data[key] = value; + } + + public void UpdateReceivePacketBytesLength(ulong bufferLength) + { + } + + public void UpdateReceiveMessageTime(long offsetTicks = 0) + { + } + + public long GetLastMessageTimeSecond(in DateTime utcTime) + { + return 0; + } + + public bool IsClosed() + { + return _closed; + } + } +} From 4424c75303e92325005c509097765e81567adca6 Mon Sep 17 00:00:00 2001 From: Blank Date: Wed, 28 Oct 2026 11:38:19 +0800 Subject: [PATCH 2/2] =?UTF-8?q?fix(session):=20=E9=98=B2=E6=AD=A2=E6=96=AD?= =?UTF-8?q?=E5=BC=80=E7=9A=84=E7=99=BB=E5=BD=95=E4=BC=9A=E8=AF=9D=E8=B8=A2?= =?UTF-8?q?=E6=8E=89=E6=9C=89=E6=95=88=E8=BF=9E=E6=8E=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- CHANGELOG.md | 1 + .../Session/PlayerSessionManager.cs | 13 +++++- ...layerSessionManagerConcurrentLoginTests.cs | 43 ++++++++++++++++++- 3 files changed, 55 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c35be3cdb..9138fd2b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -132,6 +132,7 @@ * 统一启动形态为「宿主持监听 + 热更持业务生命周期」(C284,Game 归一 Social 形态):缺省 `StartRoleServicesAsync` 由同步 `LoadHotfix` 改为 `await LoadHotfixModule`——全 18 Role 装载即激活热更生命周期(配置表/定时器/全局组件经桥接 `OnLoadSuccess`;此前不含 Game 的 Role 组合单起时全部不执行,Social 业务落地热更当天会踩),`--AllInOne` 重复装载由同路径幂等守卫短路;`AppStartUpGame` 不再自拟启动序列(`base` 缺省调用 + Online 双闸附加),KCP 登录流白名单(`ReqLogin/ReqPlayerList/ReqPlayerCreate/ReqPlayerLogin/ReqSessionResume`)与 `OnConnected`(MaxClientCount 拒绝 + `PlayerSession` 建立)/`OnDisconnected` 会话钩子上移宿主覆写,`PackageHandler`/`OnStartupCompletedAsync`/`OnStoppingAsync` 三覆写退役;断线业务段(房间断线标记 + 会话恢复通知)经新增共享事件 `Core.Session.PlayerDisconnectedEventArgs` + 热更 `PlayerDisconnectedEventListener` 全局监听器桥接;热更侧 `AppStartUpHotfixGame` 的 `OnLoadSuccess` 收窄纯生命周期激活(`RunServer`/`StartAsync`/`ReplyHeartBeatAsync` 退役,ByMain/ByHeart 删除)、bridge `Stop` 收窄纯业务清理(Actor/定时器/会话),监听不再活在可收集 ALC 内(消除热切换 Retire 卸载验证必然失败与 ALC 泄漏);`ServiceOnline`/`ServiceOffline` 单源化为宿主缺省分发(热更侧分发删除,避免非首装载 Role 双派发),Game 起服由两组启动序列归一为一组。 ### Bug Fixes +* 顶号时在获取登录锁后及异步通知返回后复核新会话;新会话已断开或被替换时保留原会话,避免无效登录踢掉有效连接。并发登录测试的同步等待增加超时并观察登录任务失败,避免断言失败后永久等待。 * 顶号流程按 playerId 串行化(C306,GFX-1018 / GitHub #647):`PlayerSessionManager.UpdateSessionAsync` 的读旧会话→通知→关闭→移除→绑定→路由上线关键段此前无互斥,同玩家并发登录可双活绑定、互踢/自踢,路由版本交错重复递增致消息路由错误;现经 `PlayerLoginLocks`(`ConcurrentDictionary`)串行——锁协议为 GetOrAdd→WaitAsync→映射复核(失败让位重取)→关键段→持锁 TryRemove(键值对)→Release,持锁回收使锁表仅驻留 in-flight 登录条目(天然有界,规避计数/等待数探测式回收固有的 check-then-remove 竞态);另加同会话重登守卫(`oldSession.SessionId == sessionId` 不再自通知/自关闭,幂等重绑)。公开接口零变化;新增确定性竞态放大并发回归测试 `PlayerSessionManagerConcurrentLoginTests`。 * 热更 Wrapper 源码生成器修复并恢复组件代理 Actor 串行化(C292):生成器引用的 Roslyn(5.6.0/5.9.0)高于 SDK 自带编译器,CS9057 下长期静默不加载,`HotfixModule.GetAgent` 回落到未串行化的原始代理。修复三件——生成类命名空间镜像代理源命名空间(`GameFrameX.Hotfix.Wrapper.Agent.<镜像段>`,同名代理 Player/Login 与 ServerRole/Login 的 `LoginComponentAgent` 分落互不冲突,此前固定单一命名空间 + 短名 hintName 在生成器真跑时即崩溃 CS8785)、hintName 由完全限定名单射净化(`.`→`_`、`+`→`__`)、分部类计数键改完全限定名;`Microsoft.CodeAnalysis.CSharp` 对齐 global.json 基线 5.0.0(与 Architecture.Analyzers 同约定)。**行为变更披露**:生成器恢复加载后,`[Service]`(非 `[ThreadSafe]`)等被包装的代理方法恢复经 `WorkerActor.EnqueueAsync` 在 Actor 队列串行化执行(并发调用可能排队),`[ThreadSafe]` 方法不受影响;新增装配护栏 `AgentWrapperAssemblyGuardTests` 防生成器再次静默停摆。全解决方案构建 0 错 0 警告(C291 遗留的 CS9057 已知例外随之关闭)。 * GameDb 门面生命周期三修(C267 / GFX-907):①`GameDb.CloseAsync()` 关停即卸载——关闭全部注册库后清空 `MultiDbRegistry` 与门面静态状态(个别库 Close 抛出也经 finally 完成卸载,异常照常传播),close→reopen 同名重注册不再被残留注册表挡在 `AlreadyRegistered`,关停后门面 CRUD 回到未初始化快速失败而非使用已关停服务;②`InitCore` 的 `IsDefault` 提名 set-once 异名冲突回滚——`MultiDbRegistry.Unregister` + 释放已打开连接后重抛原异常,废除「冲突在注册后传播、靠进程退出兜底」旧语义,Init 失败不在注册表/门面留半初始化残留(新增 `MultiDbRegistry.Unregister(string)` internal,统一入口铁律:消费方仍只经 GameDb);③删除同步 `GameDb.Close()`(`GetAwaiter().GetResult()` sync-over-async,线程饥饿/死锁面;全仓与消费仓零调用实证),异步 `CloseAsync` 为唯一关停入口。 diff --git a/GameFrameX.Core/Session/PlayerSessionManager.cs b/GameFrameX.Core/Session/PlayerSessionManager.cs index 60300807f..ae15dc33c 100644 --- a/GameFrameX.Core/Session/PlayerSessionManager.cs +++ b/GameFrameX.Core/Session/PlayerSessionManager.cs @@ -294,12 +294,23 @@ public async Task UpdateSessionAsync(string sessionId, long playerId, string sig var loginLock = await AcquireLoginLockAsync(playerId); try { + var session = Get(sessionId); + if (session.IsNull()) + { + return; + } + // 获取与玩家ID关联的旧会话;同一会话重登(同 sessionId)不触发顶号,幂等重绑 var oldSession = GetByPlayerId(playerId); if (oldSession != null && oldSession.SessionId != sessionId) { // 内联 await 顶号通知(须先于 Close,理由见参数注释) await duplicateLoginNotifier(oldSession); + if (!ReferenceEquals(Get(sessionId), session)) + { + return; + } + // 清除旧会话的连接数据并关闭连接 oldSession.WorkChannel.ClearData(); oldSession.WorkChannel.Close(); @@ -308,7 +319,7 @@ public async Task UpdateSessionAsync(string sessionId, long playerId, string sig } // 获取当前会话并更新玩家ID和签名 - var session = Get(sessionId); + session = Get(sessionId); if (session.IsNull()) { return; diff --git a/Tests/GameFrameX.Tests/Core/Session/PlayerSessionManagerConcurrentLoginTests.cs b/Tests/GameFrameX.Tests/Core/Session/PlayerSessionManagerConcurrentLoginTests.cs index 6296ad6dd..c7b02da70 100644 --- a/Tests/GameFrameX.Tests/Core/Session/PlayerSessionManagerConcurrentLoginTests.cs +++ b/Tests/GameFrameX.Tests/Core/Session/PlayerSessionManagerConcurrentLoginTests.cs @@ -71,7 +71,12 @@ public async Task UpdateSession_ConcurrentSamePlayerLogins_ShouldSerializeToSing notifierEntered.SetResult(true); await releaseGate.Task; }); - await notifierEntered.Task; + var synchronization = await Task.WhenAny(notifierEntered.Task, secondLogin).WaitAsync(TimeSpan.FromSeconds(10)); + if (synchronization == secondLogin) + { + await secondLogin; + } + await notifierEntered.Task.WaitAsync(TimeSpan.FromSeconds(10)); // 第三登录并发进入:串行化下必须阻塞在锁上(通知器不可能先于放行触发); // 无锁旧代码会立即以第一会话为旧会话完成顶号(探测到即继续,最终断言会暴露双活绑定) @@ -110,6 +115,42 @@ public async Task UpdateSession_ConcurrentSamePlayerLogins_ShouldSerializeToSing Assert.Null(manager.Get("c306-first")); } + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task UpdateSession_DisconnectedReplacement_ShouldPreserveExistingSession(bool disconnectDuringNotification) + { + var manager = PlayerSessionManager.Instance; + var playerId = disconnectDuringNotification ? 930004L : 930003L; + var existingIdentifier = "existing-" + playerId; + var replacementIdentifier = "replacement-" + playerId; + var existingChannel = new FakeNetworkChannel(); + var replacementChannel = new FakeNetworkChannel(); + manager.Add(new PlayerSession(existingIdentifier, existingChannel)); + await manager.UpdateSessionAsync(existingIdentifier, playerId, "original", session => Task.CompletedTask); + manager.Add(new PlayerSession(replacementIdentifier, replacementChannel)); + if (!disconnectDuringNotification) + { + manager.Remove(replacementIdentifier); + } + try + { + await manager.UpdateSessionAsync(replacementIdentifier, playerId, "replacement", session => + { + manager.Remove(replacementIdentifier); + return Task.CompletedTask; + }).WaitAsync(TimeSpan.FromSeconds(10)); + Assert.False(existingChannel.IsClosed()); + Assert.Equal(existingIdentifier, manager.GetByPlayerId(playerId).SessionId); + Assert.Equal("original", manager.Get(existingIdentifier).Sign); + } + finally + { + manager.Remove(existingIdentifier); + manager.Remove(replacementIdentifier); + } + } + [Fact] public async Task UpdateSession_SameSessionRebind_ShouldNotKickSelf() {