diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fbc57fe5..229e335d9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -36,6 +36,7 @@ * Wrapper 生成器崩溃止血与不可编译产物清理(C431,GFX-1171,GitHub #917):`[TimeOut]` 实参防御式解析(仅数值字面量可静态求值——常量名/缺参/空参/表达式/下划线开头的常量名输出 Error 诊断并降级为框架默认超时,不再令生成器整体崩溃丢失全部 wrapper);`GetFullName` 重写为向上收集命名空间与嵌套类型段(无命名空间代理返回类型链短名,顺带覆盖 struct/enum 容器形态);`Tools.GetNameSpace` 取真命名空间(首个 `+` 前最后一个 `.`,无命名空间返回空串且不发射空 using),嵌套代理基类改容器限定名 `Outer.Inner`、wrapper 类名携带容器链(同命名空间同名代理不再碰撞);partial 合并键升为完全限定名(跨命名空间同名无关类不再产生幽灵 Wrapper);async 被包装方法统一 `return await`(修复非泛型 `async Task`/`async ValueTask` 生成体不可编译);含 `ref/out/in` 参数与 `[Discard]` 返回类型非 Task/ValueTask(按类型名最后一段比较,全限定名不误报)的方法报 Error 且不进入生成面(校验先行);`[Discard]` 非 ThreadSafe 入队 lambda 改 `async ()=> await` 统一绑定 `EnqueueAsync(Func)` 重载(ValueTask 一次性消费契约不再被违反)。新增 16 例生成器测试(含独立审查 R1/R2/R3 修复钉住),既有 3 例 Discard lambda 断言随契约更新。 ### Added +* 黄金路径默认开箱即通(C460,GFX-1195,GitHub #959):`OnlineLeaderboardProjectionOptions.MatchSettledBoardId` 默认值由空白(不投影)改为默认榜常量 `match-settled`(`OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId`)——零 Online JSON 配置起服即装配 Match.Settled 投影、激活期预建默认榜,RPS 对局→结算→Grant 发奖→上榜全链默认贯通;显式置空白 / null 或配置段覆盖为空白仍可关闭投影(不装配、不预建、不报错)。`OnlineCompetitionOptions.Validate` 补投影组合校验:`LeaderboardProjection` 须为非 null 对象,榜单标识非空白(投影开启)时长度 ≤128 且不得含空白字符(装配期 fail-fast,全部问题一次报全)。端到端验收以可重跑 xunit 钉住(GameFrameX.Tests 零 Settings 组合全链 + Hotfix.Tests 桥断言:好友桥→撮合桥→对局桥→默认榜条目),`Configs/app_config.json` Game 角色移除 `Online.Settings` 空节依赖。 * 行版本条件写内存管线收口共享助手(C409,GFX-1117):新增 `GameFrameX.DataBase/Abstractions/RowVersionCasWriteHelper` 与 `RowVersionBackfillWriteHelper`——`UpdateIfRowVersionAsync`(CAS)与 `UpdateIfRowVersionIsNullAsync`(回填)两原语在 Mongo/PostgreSQL/SQLite 三 Provider 重复的内存侧样板(Id 一致性校验、版本对齐 + checked 递增、写库前 `ToBytes()` 快照、失败回滚 / 成功精确提交)收敛为单一事实源,Provider 仅保留谓词 / 语句 / 重试外壳等写库差异;语义零变化(失败回滚、异常不回滚、`long.MaxValue` 溢出写库前抛出、SQLite null 守卫现状均冻结),回归依托 `DatabaseConditionalWritePrimitivesTests` 既有套件。 * 服务器间 RPC 端点改由心跳注册表解析并退役静态引导(C304,GitHub #643):`RemoteServiceTarget`(ServerType + 可选 InstanceId)结构化拨号取代 `{Role}_{InstanceId}` 字符串拼接;`DiscoveryServiceEndpointResolver` 成为唯一端点解析器(指定实例走 Instance 视图含 Draining 并校验 Role 一致,ServerType 级取 Active 中 InstanceId 序数最小者,端点集合 = TCP 主端点 + 附加端点,偏好 kcp > ws > wss > tcp);`RemoteMessagingBuilder.WithRouteTable(IRoleRouteTableProvider)` 绑定路由表、生产注册 KCP 拨号适配器(`IsEnableInnerKcp` 时,服务器间 KCP 首次生产可用);心跳新增附加广播端点(`InstanceDescriptor.AdditionalAdvertiseEndpoints`,监听器装配成功的实例级闸门后才广播,多 ServerType 进程非首选类型披露 Warning);`UnifiedMessageSender` 实例列表改读路由表 Active 视图且仅 InstanceId 集合变化才重建哈希环;玩家路由实例直达——`player_route.InstanceId` 写真实发现层实例 Id(`PlayerRouteResolverBootstrap` 同源注入),`ForwardToRemoteServerAsync` 按 `TargetInstanceId` 投递(Instance 视图含 Draining)、`IsCurrentServer` 改 InstanceId 比较;Mongo 心跳 class map 显式忽略未知字段(含继承传递)、写路径空集合归一化为 null(默认配置文档与旧版本逐字节同形);PostgreSQL 幂等补列 `additional_advertise_endpoints text[]`(命名经 `DiscoveryStorageNaming` 推导);删除 `services__*` 环境变量契约、`EnvironmentVariableEndpointResolver`、`EnvironmentServiceInstanceDiscovery`、`docker-compose.multi.legacy.yml` 与生成器静态引导映射。 diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs index 241945c3f..3084bc100 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs @@ -31,13 +31,19 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// /// 排行榜投影选项( 的子对象; -/// 非空白才装配 Match.Settled 投影与激活期榜单预建, -/// 空白 / 缺省 = 不投影,不报错)。 +/// 默认投影到默认榜(C460:默认值服务黄金路径开箱即通—— +/// 零 JSON 配置起服即装配 Match.Settled 投影并在激活期预建默认榜);显式置空白 / null +/// 或经配置段覆盖为空白 = 关闭投影(不装配、不预建,不报错)。 /// public sealed class OnlineLeaderboardProjectionOptions { /// - /// 获取或设置 Match.Settled 事件的目标榜单标识(空白 = 不投影)。 + /// 默认投影目标榜单标识(Match.Settled 投影的默认榜;装配期由 Leaderboard 能力预建)。 /// - public string MatchSettledBoardId { get; set; } + public const string DefaultMatchSettledBoardId = "match-settled"; + + /// + /// 获取或设置 Match.Settled 事件的目标榜单标识(默认 = ;空白 = 不投影)。 + /// + public string MatchSettledBoardId { get; set; } = DefaultMatchSettledBoardId; } diff --git a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs index 54587807c..e68b61919 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs @@ -52,9 +52,10 @@ namespace GameFrameX.Capability.Online.Competition; /// 锦标赛三个 store 以懒默认描述符注册(族 / 宿主覆盖恒胜出,模块不感知);赛季 / 锦标赛对发放服务 /// (,assets 域产物)的依赖经 manifest 可选声明 + GetOptionalService, /// 缺席(assets 能力被过滤)时不装配两者;对外产物(榜单 / 赛季 / 锦标赛服务与 LiveOps 注册表)注册回 -/// 共享面。 为唯一参数面(含榜单组件参数与 Match.Settled 投影配置, -/// 后者收编族级键 MatchBridgeLeaderboardId):投影榜 id 非空白且对局结果存储(online-match 可选产物) -/// 在场时装配 Match.Settled 排行榜投影(机制总线订阅 + 失败重投 tick); +/// 为唯一参数面(含榜单组件参数与 Match.Settled 投影配置, +/// 后者收编族级键 MatchBridgeLeaderboardId):投影榜 id 非空白(C460 起默认投影到默认榜 +/// ,显式空白可关闭)且对局结果存储 +/// (online-match 可选产物)在场时装配 Match.Settled 排行榜投影(机制总线订阅 + 失败重投 tick); /// ActivateAsync 在投影榜 id 非空白时经榜单服务预建目标榜(查询-创建,见方法注释)。 /// /// diff --git a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs b/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs index f548b97a9..e015d44fd 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs @@ -45,17 +45,19 @@ public sealed class OnlineCompetitionOptions : ICapabilityOptions public OnlineLeaderboardOptions Leaderboard { get; set; } = new OnlineLeaderboardOptions(); /// - /// 获取或设置 Match.Settled 写榜投影配置(MatchSettledBoardId 空白 = 不投影不预建)。 + /// 获取或设置 Match.Settled 写榜投影配置(默认投影到默认榜;显式置空白或配置段覆盖可关闭)。 /// public OnlineLeaderboardProjectionOptions LeaderboardProjection { get; set; } = new OnlineLeaderboardProjectionOptions(); /// - /// 校验排行榜组件选项:单次提交最大分数、限流最大提交次数、限流窗口秒数、缓存有效期秒数与最大分页大小均须为正数;投影配置不做校验(空白榜单标识表示不投影)。 + /// 校验排行榜组件与投影组合选项:单次提交最大分数、限流最大提交次数、限流窗口秒数、缓存有效期秒数与最大分页大小均须为正数; + /// 投影配置须为非 null 对象,目标榜单标识非空白(投影开启)时长度不得超过上限且不得包含空白字符(装配期 fail-fast,全部问题一次报全)。 /// /// /// Validates the leaderboard options: default maximum score per submission, rate-limit maximum submissions, rate-limit window - /// seconds, cache time-to-live seconds and maximum page size must all be positive. The projection settings are not validated because - /// a blank board id simply disables the projection. Failures are recorded on the validation collector. + /// seconds, cache time-to-live seconds and maximum page size must all be positive. The projection settings must be a non-null + /// object, and when the target board id is not blank (projection enabled) it must not exceed the maximum length or contain any + /// whitespace characters. All problems are collected and reported together on the validation collector. /// /// 选项校验结果收集器 / Options validation collector public void Validate(CapabilityOptionsValidation validation) @@ -65,5 +67,38 @@ public void Validate(CapabilityOptionsValidation validation) validation.RequirePositive("Leaderboard.RateLimitWindowSeconds", Leaderboard.RateLimitWindowSeconds); validation.RequirePositive("Leaderboard.CacheTtlSeconds", Leaderboard.CacheTtlSeconds); validation.RequirePositive("Leaderboard.MaxPageSize", Leaderboard.MaxPageSize); + + // 投影组合校验(C460):子对象缺席 = 代码 Configure 写坏,fail-fast;榜单 id 非空白(投影开启)时 + // 校验长度与空白字符——该 id 会拼进事件幂等键与读缓存键,超长 / 含空白属于配置错误而非运行期输入。 + if (LeaderboardProjection == null) + { + validation.AddError("LeaderboardProjection", "must be a non-null options object"); + return; + } + + var boardId = LeaderboardProjection.MatchSettledBoardId; + if (string.IsNullOrWhiteSpace(boardId)) + { + return; + } + + if (boardId.Length > MaxMatchSettledBoardIdLength) + { + validation.AddError("LeaderboardProjection.MatchSettledBoardId", "must be at most " + MaxMatchSettledBoardIdLength + " characters (actual: " + boardId.Length + ")"); + } + + for (var index = 0; index < boardId.Length; index++) + { + if (char.IsWhiteSpace(boardId[index])) + { + validation.AddError("LeaderboardProjection.MatchSettledBoardId", "must not contain whitespace characters"); + break; + } + } } + + /// + /// 投影目标榜单标识的最大长度( 非空白时的上限)。 + /// + public const int MaxMatchSettledBoardIdLength = 128; } diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs index e1b0216be..60a0fe242 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs @@ -167,8 +167,11 @@ public void Register(CapabilityRegistrationContext context) var eventPublisher = context.GetService(); context.AddService(static _ => new InMemoryOnlineMatchActorStore()); var matchActorStore = context.GetService(); - context.AddService(static _ => new InMemoryOnlineMatchSettlementStore()); - context.AddService(static _ => new InMemoryOnlineMatchSettlementStore()); + // 同一实例注册两接口键(C460):结算写入与投影读取必须看到同一份事实——分别 new 会造成 + // 「结算落库 / 投影读空」的分裂脑(默认内存形态下黄金路径静默断链);族 / 宿主覆盖仍逐键恒胜出。 + var settlementStoreInstance = new InMemoryOnlineMatchSettlementStore(); + context.AddService(_ => settlementStoreInstance); + context.AddService(_ => settlementStoreInstance); var matchSettlementStore = context.GetService(); var rpsGame = new OnlineRockPaperScissorsGame(); diff --git a/Configs/app_config.json b/Configs/app_config.json index 162bffa4d..077b4258a 100644 --- a/Configs/app_config.json +++ b/Configs/app_config.json @@ -17,8 +17,7 @@ "EnableRuntime": true, "EnableAdminApi": true, "EnableRoles": ["Game"], - "UseGameDbStores": true, - "Settings": {} + "UseGameDbStores": true }, "MinModuleId": 10, "MaxModuleId": 9999, diff --git a/README.md b/README.md index f030caa4c..5a6f8f271 100644 --- a/README.md +++ b/README.md @@ -161,6 +161,12 @@ GameFrameX Server is a high-performance, cross-platform game server framework bu - Health check: `http://localhost:28080/health` (liveness probe: `/alive`) - Check console logs to confirm successful startup + **Zero-JSON golden path**: start the server without writing any `Online.Settings` and the sample + RPS chain (matchmaking → match → settlement → reward grant → leaderboard) works out of the box — + `MatchSettledBoardId` projects onto the default board `match-settled` (pre-created during + assembly). To turn the projection off, explicitly blank + `online-competition.LeaderboardProjection.MatchSettledBoardId` under `Online.Settings`. + ### SQLite Provider Boundaries SQLite (`--DatabaseProvider=Sqlite`) is positioned for quick starts, development evaluation, and diff --git a/README.zh-CN.md b/README.zh-CN.md index 413c027cc..e2954197e 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -157,6 +157,8 @@ GameFrameX Server 是基于 C# .NET 10.0 开发的高性能、跨平台游戏服 - 健康检查:`http://localhost:28080/health`(存活探针:`/alive`) - 查看控制台日志确认启动成功 + **零 JSON 默认通(黄金路径)**:不写任何 `Online.Settings` 配置直接起服,RPS 样例对局全链(撮合 → 对局 → 结算 → 发奖 → 上榜)默认贯通——`MatchSettledBoardId` 默认投影到默认榜 `match-settled`(装配期自动预建);如需关闭投影,在 `Online.Settings` 中将 `online-competition.LeaderboardProjection.MatchSettledBoardId` 显式置空即可。 + --- ## 使用示例 diff --git a/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj b/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj index a9ce58c55..19a8f5f12 100644 --- a/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj +++ b/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj @@ -21,6 +21,15 @@ runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/Tests/GameFrameX.Hotfix.Tests/GoldenPathBridgeChainTests.cs b/Tests/GameFrameX.Hotfix.Tests/GoldenPathBridgeChainTests.cs new file mode 100644 index 000000000..aa9ea6a2d --- /dev/null +++ b/Tests/GameFrameX.Hotfix.Tests/GoldenPathBridgeChainTests.cs @@ -0,0 +1,204 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the PRC and related international regulations. +// 使用本项目须严格遵守相关法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with relevant 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 at the root 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://www.cnb.cool/GameFrameX +// CNB Repository: https://www.cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using System; +using System.Collections.Generic; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Hosting.Abstractions; +using GameFrameX.Capability.Hosting.Core; +using GameFrameX.Capability.Online.Abstractions; +using GameFrameX.Capability.Online.Operations.HotfixRollback; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Competition.Leaderboard; +using GameFrameX.Hotfix.Logic.Game.RockPaperScissors; +using GameFrameX.Hotfix.Logic.Player.Friend; +using GameFrameX.Hotfix.Logic.ServerRole.Match; +using GameFrameX.Proto.Proto; +using Xunit; + +namespace GameFrameX.Hotfix.Tests; + +/// +/// 黄金路径桥断言(C460:好友(C244)→撮合(C246)→对局→上榜 全链经 Hotfix 桥薄适配器走通): +/// 真实 Online 能力族组合(零 Settings JSON——默认投影开箱即通),好友桥建立关系 → 撮合桥双玩家入队 → +/// 对局桥开局 / 出拳决胜 → 结算发奖投影 → 默认榜出现条目。桥契约槽位是进程级静态状态,入 +/// 与其余域桥用例串行。 +/// +[Collection(HotfixBridgeTestCollection.Name)] +public sealed class GoldenPathBridgeChainTests +{ + /// 测试租户标识(族配置段一致)。 + private const long TenantId = 1; + + /// 测试 App 标识(族配置段一致)。 + private const long AppId = 1; + + /// 测试区服标识(族配置段一致)。 + private const long ServerId = 1001; + + /// 玩家一(好友请求方 / 胜方,连出石头两轮)。 + private const long PlayerOne = 1001; + + /// 玩家二(好友接受方 / 负方,连出剪刀两轮)。 + private const long PlayerTwo = 1002; + + /// 房间标识(确定性对局标识派生入参)。 + private const long RoomId = 5001; + + /// 局号(同房同局幂等)。 + private const int Round = 1; + + /// 驱动的最大 tick 轮数(每轮覆盖撮合 / 对局 / 结算 / 投影重投 job)。 + private const int MaxTickRounds = 10; + + /// + /// 验证零 JSON 默认配置下桥全链:好友桥 → 撮合桥 → 对局桥 → 结算发奖 → 默认榜条目出现。 + /// + [Fact] + public async Task GoldenPath_ZeroSettings_FriendBridge_MatchBridge_RpsMatch_ProjectsOntoDefaultBoard() + { + CapabilityRuntime runtime = null; + try + { + var section = JsonDocument.Parse("{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}").RootElement.Clone(); + var options = new CapabilityCompositionOptions(section, new HotfixBridgeAssemblyLog()) + { + HostOptions = new CapabilityHostOptions { TenantId = TenantId, AppId = AppId, ServerId = ServerId, SchedulerIntervalMilliseconds = 3600000, }, + Filter = new CapabilityAssemblyFilter(new[] { "online-foundation", "online-social", "online-matchmaking", "online-match", "online-assets", "online-competition" }), + }; + options.Override(new EmptyPlayerDirectoryStub()); + options.Override(new NoopHotfixRollbackExecutorStub()); + + runtime = CapabilityComposition.Compose(new OnlineCapabilityFamily(), options); + await runtime.Host.StartAsync(); + + // —— 好友桥(C244):请求 → 接受 → 双方好友列表可见。 + var sendRequest = new RespFriendSendRequest(); + await FriendDomainBridge.SendRequestAsync(PlayerOne, PlayerTwo, sendRequest); + Assert.Equal(0, sendRequest.ErrorCode); + + var accept = new RespFriendAccept(); + await FriendDomainBridge.AcceptAsync(PlayerTwo, PlayerOne, accept); + Assert.Equal(0, accept.ErrorCode); + + var friendList = new RespFriendList(); + await FriendDomainBridge.QueryFriendListAsync(PlayerOne, friendList); + Assert.Equal(0, friendList.ErrorCode); + Assert.Contains(friendList.Friends, friend => friend.PlayerId == PlayerTwo); + + // —— 撮合桥(C246):双玩家入队 1v1 匹配池。 + foreach (var player in new[] { PlayerOne, PlayerTwo }) + { + var enqueueResponse = new RespMatchEnqueue(); + await MatchDomainBridge.EnqueueAsync(player, new ReqMatchEnqueue { Mode = MatchMode.OneVsOne, Rating = 1000, }, enqueueResponse); + Assert.Equal(0, enqueueResponse.ErrorCode); + } + + // —— 对局桥:开局(确定性对局标识)+ 双方各两轮出拳(石头胜剪刀两轮 = 决胜)。 + Assert.True(RockPaperScissorsMatchBridge.IsBridgeEnabled, "online-match 装配后对局桥应在场接管"); + + var startResponse = new RespStartRoomGame(); + var handled = await RockPaperScissorsMatchBridge.TryStartRoomGameAsync(PlayerOne, RoomId, Round, new List { PlayerOne, PlayerTwo }, startResponse); + Assert.True(handled); + Assert.Equal(0, startResponse.ErrorCode); + + for (var roundIndex = 0; roundIndex < 2; roundIndex++) + { + foreach (var player in new[] { PlayerOne, PlayerTwo }) + { + var gesture = player == PlayerOne ? (int)RockPaperScissorsGesture.Rock : (int)RockPaperScissorsGesture.Scissors; + var submitResponse = new RespSubmitRockPaperScissorsGesture(); + var (gestureHandled, _) = await RockPaperScissorsMatchBridge.TrySubmitGestureAsync(player, RoomId, Round, gesture, submitResponse); + Assert.True(gestureHandled); + Assert.Equal(0, submitResponse.ErrorCode); + } + + // 本轮双方已提交:驱动一轮 tick 裁决本轮,开启下一轮。 + await runtime.Host.Scheduler.TickAsync(); + } + + // —— 结算 → 发奖 → 投影:显式驱动调度轮直至默认榜出现条目。 + var leaderboardStore = runtime.Host.Services.GetService(); + OnlineLeaderboardEntry winnerEntry = null; + for (var tickRound = 0; tickRound < MaxTickRounds; tickRound++) + { + await runtime.Host.Scheduler.TickAsync(); + winnerEntry = await leaderboardStore.FindEntryAsync(TenantId, AppId, OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId, PlayerOne); + if (winnerEntry != null) + { + break; + } + } + + Assert.NotNull(winnerEntry); + var loserEntry = await leaderboardStore.FindEntryAsync(TenantId, AppId, OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId, PlayerTwo); + Assert.NotNull(loserEntry); + Assert.True(winnerEntry.Score >= loserEntry.Score, "winner score (" + winnerEntry.Score + ") should rank above loser score (" + loserEntry.Score + ")"); + } + finally + { + if (runtime != null) + { + await runtime.StopAsync(); + } + } + } + + /// + /// 空玩家目录桩(社交能力的展示名检索宿主扩展点:黄金路径不消费搜索结果)。 + /// + private sealed class EmptyPlayerDirectoryStub : IOnlinePlayerDirectory + { + /// 按名检索恒返回空(黄金路径不消费)。 + public Task> SearchByNameAsync(long tenantId, long appId, string keyword, int limit, CancellationToken cancellationToken = default) + { + return Task.FromResult>(Array.Empty()); + } + + /// 按标识批量解析恒返回空(好友列表展示名回退标识字面量)。 + public Task> FindAsync(long tenantId, long appId, IReadOnlyList playerIds, CancellationToken cancellationToken = default) + { + return Task.FromResult>(Array.Empty()); + } + } + + /// + /// 空操作热更回滚执行器桩(Online 运营能力的宿主扩展点:黄金路径不触发回滚)。 + /// + private sealed class NoopHotfixRollbackExecutorStub : IOnlineHotfixRollbackExecutor + { + /// 恒完成(黄金路径不触发回滚)。 + public Task RollbackAsync(string targetVersion, CancellationToken cancellationToken = default) + { + return Task.CompletedTask; + } + } +} diff --git a/Tests/GameFrameX.Tests/Online/GoldenPathDefaultOnTests.cs b/Tests/GameFrameX.Tests/Online/GoldenPathDefaultOnTests.cs new file mode 100644 index 000000000..b90e45ddd --- /dev/null +++ b/Tests/GameFrameX.Tests/Online/GoldenPathDefaultOnTests.cs @@ -0,0 +1,134 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the PRC and related international regulations. +// 使用本项目须严格遵守相关法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with relevant 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 at the root 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://www.cnb.cool/GameFrameX +// CNB Repository: https://www.cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using GameFrameX.Capability.Hosting.Abstractions; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Scope; +using GameFrameX.Capability.Online.Assets; +using GameFrameX.Capability.Online.Competition.Leaderboard; +using GameFrameX.Capability.Online.Match; +using Xunit; + +namespace GameFrameX.Tests.Online +{ + /// + /// 黄金路径端到端验收(C460:Options 默认值开箱即通): + /// 零 Online JSON(不写 Settings 键)的真实族组合——RPS 对局(桥服务开局 / 出拳)→ + /// 结算管线(match-settlement-tick)→ Grant 幂等发奖 → Match.Settled 投影写默认榜, + /// 断言钱包余额与默认榜条目同时出现;显式空白覆盖关闭投影的反例见投影器组合测试。 + /// + [Collection(CapabilityRuntimeCollection.Name)] + public class GoldenPathDefaultOnTests + { + /// 玩家一(胜方,连出石头两轮)。 + private const long PlayerOne = 1001; + + /// 玩家二(负方,连出剪刀两轮)。 + private const long PlayerTwo = 1002; + + /// 房间标识(确定性对局标识派生入参)。 + private const long RoomId = 5001; + + /// 局号(同房同局幂等)。 + private const int Round = 1; + + /// 驱动的最大 tick 轮数(每轮覆盖 match-tick / match-settlement-tick / 投影重投 job)。 + private const int MaxTickRounds = 10; + + /// + /// 验证零 JSON 默认配置即通黄金路径:默认榜随装配预建,RPS 两轮决胜 → 结算 → 发奖 → 默认榜条目出现。 + /// + [Fact] + public async Task ZeroSettings_RpsMatch_Settles_Grants_And_ProjectsOntoDefaultBoard() + { + await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => + { + await runtime.Host.StartAsync(); + var services = runtime.Host.Services; + var scope = new OnlineScope(OnlineCapabilityTestHarness.TenantId, OnlineCapabilityTestHarness.AppId, OnlineCapabilityTestHarness.ServerId); + + // 默认榜已随装配预建(ActivateAsync 查询-创建):Top 探针即成功。 + var probe = await services.GetService().GetTopAsync(scope, new OnlineLeaderboardTopQuery { LeaderboardId = OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId, Count = 1, }); + Assert.True(probe.IsSuccess, probe.Message); + + // 对局:开局幂等 + 双方各两轮出拳(石头胜剪刀两轮 = 达到 WinTarget 决胜)。 + var bridge = services.GetService(); + var started = await bridge.StartRoomGameAsync(new OnlineScope(scope.TenantId, scope.AppId, scope.ServerId, PlayerOne), RoomId, Round, new List { PlayerOne, PlayerTwo }); + Assert.True(started.IsSuccess, started.Message); + + for (var roundIndex = 0; roundIndex < 2; roundIndex++) + { + foreach (var player in new[] { PlayerOne, PlayerTwo }) + { + var gesture = player == PlayerOne ? (int)OnlineRockPaperScissorsMove.Rock : (int)OnlineRockPaperScissorsMove.Scissors; + var submitted = await bridge.SubmitGestureAsync(new OnlineScope(scope.TenantId, scope.AppId, scope.ServerId, player), RoomId, Round, gesture); + Assert.True(submitted.IsSuccess, submitted.Message); + } + + // 本轮双方已提交:驱动一轮 tick 裁决本轮,开启下一轮。 + await runtime.Host.Scheduler.TickAsync(); + } + + // 结算 → 发奖 → 投影:显式驱动调度轮直至默认榜出现条目(事件订阅链同步投影,重投 job 兜底)。 + OnlineLeaderboardEntry winnerEntry = null; + for (var tickRound = 0; tickRound < MaxTickRounds; tickRound++) + { + await runtime.Host.Scheduler.TickAsync(); + winnerEntry = await services.GetService().FindEntryAsync(scope.TenantId, scope.AppId, OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId, PlayerOne); + if (winnerEntry != null) + { + break; + } + } + + // 发奖断言:胜方 +WinnerRewardAmount、负方 +ParticipantRewardAmount(样例币资产)。 + var assetStore = services.GetService(); + var winnerWallet = await assetStore.FindWalletAsync(scope.TenantId, scope.AppId, PlayerOne, OnlineRockPaperScissorsGame.RewardAssetId); + var loserWallet = await assetStore.FindWalletAsync(scope.TenantId, scope.AppId, PlayerTwo, OnlineRockPaperScissorsGame.RewardAssetId); + Assert.NotNull(winnerWallet); + Assert.Equal(OnlineRockPaperScissorsGame.WinnerRewardAmount, winnerWallet.Balance); + Assert.NotNull(loserWallet); + Assert.Equal(OnlineRockPaperScissorsGame.ParticipantRewardAmount, loserWallet.Balance); + + // 上榜断言:默认榜出现双方条目(胜方分高在前)。 + Assert.NotNull(winnerEntry); + var loserEntry = await services.GetService().FindEntryAsync(scope.TenantId, scope.AppId, OnlineLeaderboardProjectionOptions.DefaultMatchSettledBoardId, PlayerTwo); + Assert.NotNull(loserEntry); + Assert.True(winnerEntry.Score >= loserEntry.Score, "winner score (" + winnerEntry.Score + ") should rank above loser score (" + loserEntry.Score + ")"); + }, null, options => + { + options.Filter = new CapabilityAssemblyFilter(new[] { "online-foundation", "online-social", "online-matchmaking", "online-match", "online-assets", "online-competition" }); + options.HostOptions.SchedulerIntervalMilliseconds = 3600000; + }); + } + } +} diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs index b87b68b14..636d0120a 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs @@ -218,17 +218,18 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => } /// - /// 验证模块装配半边二:未配置投影榜 id 或 id 空白 → 不装配投影器、不注册重投 tick job(一轮 tick 比投影形态少执行一个 job),也不报错。 + /// 验证模块装配半边二(C460 默认开):零 Settings(缺省装配)与显式配置投影榜 id 均装配投影器 + 重投 tick job + ///(两者 tick job 数相同);显式配置空白榜单 id(覆盖关闭)→ 不装配投影器(一轮 tick 比投影形态少执行一个 job),不报错。 /// [Fact] - public async Task Compose_WithoutProjectionBoard_SkipsProjectorAndRetryJob() + public async Task Compose_ZeroSettingsDefaultsProjectionOn_BlankOverrideTurnsItOff() { - var withProjection = await RunOneTickRoundAsync(ProjectionSettings, true); - var withoutSettings = await RunOneTickRoundAsync(null, false); + var configured = await RunOneTickRoundAsync(ProjectionSettings, true); + var zeroSettings = await RunOneTickRoundAsync(null, true); var blankBoard = await RunOneTickRoundAsync("{\"online-competition\":{\"LeaderboardProjection\":{\"MatchSettledBoardId\":\" \"}}}", false); - Assert.Equal(withProjection - 1, withoutSettings); - Assert.Equal(withProjection - 1, blankBoard); + Assert.Equal(configured, zeroSettings); + Assert.Equal(configured - 1, blankBoard); } ///