From a9663acc681751d207ec5781d26a576c8dc3e238 Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 15:35:09 +0800 Subject: [PATCH 01/13] =?UTF-8?q?feat(capability-hosting):=20=E7=AE=A1?= =?UTF-8?q?=E7=90=86=E5=A5=91=E7=BA=A6=E4=B8=8A=E7=A7=BB=E5=A5=91=E7=BA=A6?= =?UTF-8?q?=E5=8C=85=E8=A7=A3=E5=80=92=E6=8C=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 管理动作契约 13 型(IAdminActionContributor、AdminActionRegistry、 AdminApiRequest、AdminApiClaimedScope 等)自 Hosting.AdminApi 上移 Hosting.Abstractions(命名空间保留),Online.Abstractions 拆除对 管理面运行时包的反向依赖、改直引契约包;AdminApi 侧经友元程序集访问 注册表内部成员;Hotfix.Tests 桥 harness 显式直引机制包。 BREAKING CHANGE: 管理契约类型定义程序集由 GameFrameX.Capability.Hosting.AdminApi 变更为 GameFrameX.Capability.Hosting.Abstractions(命名空间不变)。 Linear: GFX-1199 --- .../AdminActionException.cs | 0 .../AdminActionHandler.cs | 0 .../AdminActionRegistration.cs | 0 .../AdminActionRegistry.cs | 0 .../AdminApiClaimedScope.cs | 0 .../AdminApiErrorCode.cs | 0 .../AdminApiErrorCodes.cs | 0 .../AdminApiRequest.cs | 0 .../AdminIdempotencyOutcome.cs | 0 .../AdminIdempotencyOutcomeKind.cs | 0 ...meX.Capability.Hosting.Abstractions.csproj | 1 + .../IAdminActionContributor.cs | 0 .../IAdminApiIdempotencyAdapter.cs | 0 .../IAdminApiScopeAdapter.cs | 0 ...ameX.Capability.Online.Abstractions.csproj | 5 +- .../OnlineAdminLeaderboardHandlers.cs | 183 ++++ .../IOnlineLeaderboardStore.cs | 114 +++ .../InMemoryOnlineLeaderboardStore.cs | 410 +++++++++ .../OnlineCompetitionOptions.cs | 69 ++ .../OnlineLeaderboard.cs | 95 ++ .../OnlineLeaderboardApplyResult.cs | 55 ++ .../OnlineLeaderboardAroundQuery.cs | 67 ++ .../OnlineLeaderboardAroundView.cs | 62 ++ .../OnlineLeaderboardCreateRequest.cs | 60 ++ .../OnlineLeaderboardEntry.cs | 88 ++ .../OnlineLeaderboardEntryView.cs | 65 ++ .../OnlineLeaderboardEvents.cs | 195 +++++ .../OnlineLeaderboardOptions.cs | 71 ++ .../OnlineLeaderboardOrdering.cs | 114 +++ .../OnlineLeaderboardPage.cs | 58 ++ .../OnlineLeaderboardProjectionFailure.cs | 54 ++ .../OnlineLeaderboardProjectionOptions.cs | 43 + .../OnlineLeaderboardProjectionOutcome.cs | 69 ++ .../OnlineLeaderboardProjectionRetryStatus.cs | 57 ++ .../OnlineLeaderboardRateLimiter.cs | 188 ++++ .../OnlineLeaderboardResultProjector.cs | 244 ++++++ .../OnlineLeaderboardScoreSource.cs | 45 + .../OnlineLeaderboardScoreSubmission.cs | 66 ++ .../OnlineLeaderboardScoreUpdatePolicy.cs | 56 ++ .../OnlineLeaderboardService.cs | 579 +++++++++++++ .../OnlineLeaderboardSortOrder.cs | 50 ++ .../OnlineLeaderboardTopQuery.cs | 61 ++ .../OnlineLeaderboardWriteOutcome.cs | 65 ++ .../OnlineMatchSettledLeaderboardProjector.cs | 379 ++++++++ .../OnlineRockPaperScissorsGame.cs | 814 ++++++++++++++++++ .../OnlineRockPaperScissorsMove.cs | 52 ++ .../OnlineRockPaperScissorsState.cs | 90 ++ .../GameFrameX.Hotfix.Tests.csproj | 2 + .../OnlineAdminLiveOpsHandlers.cs | 403 +++++++++ .../detached-liveops/OnlineLiveOpsCommand.cs | 78 ++ .../detached-liveops/OnlineLiveOpsEntry.cs | 60 ++ .../OnlineLiveOpsOperation.cs | 42 + .../detached-liveops/OnlineLiveOpsRegistry.cs | 160 ++++ scripts/legacy/OnlineFriendLegacyMigration.cs | 205 +++++ 54 files changed, 5570 insertions(+), 4 deletions(-) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/AdminActionException.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/AdminActionHandler.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/AdminActionRegistration.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/AdminActionRegistry.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/AdminApiClaimedScope.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/AdminApiErrorCode.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/AdminApiErrorCodes.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/AdminApiRequest.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/AdminIdempotencyOutcome.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/AdminIdempotencyOutcomeKind.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/IAdminActionContributor.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/IAdminApiIdempotencyAdapter.cs (100%) rename Capability/{GameFrameX.Capability.Hosting.AdminApi => GameFrameX.Capability.Hosting.Abstractions}/IAdminApiScopeAdapter.cs (100%) create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/AdminApi/OnlineAdminLeaderboardHandlers.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/IOnlineLeaderboardStore.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/InMemoryOnlineLeaderboardStore.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineCompetitionOptions.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboard.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardApplyResult.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardAroundQuery.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardAroundView.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCreateRequest.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEntry.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEntryView.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEvents.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardOptions.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardOrdering.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardPage.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionFailure.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionOptions.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionOutcome.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionRetryStatus.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardRateLimiter.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardResultProjector.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreSource.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreSubmission.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreUpdatePolicy.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardService.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardSortOrder.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardTopQuery.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardWriteOutcome.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineMatchSettledLeaderboardProjector.cs create mode 100644 GameFrameX.Apps.Sample/OnlineRockPaperScissorsGame.cs create mode 100644 GameFrameX.Apps.Sample/OnlineRockPaperScissorsMove.cs create mode 100644 GameFrameX.Apps.Sample/OnlineRockPaperScissorsState.cs create mode 100644 scripts/detached-liveops/OnlineAdminLiveOpsHandlers.cs create mode 100644 scripts/detached-liveops/OnlineLiveOpsCommand.cs create mode 100644 scripts/detached-liveops/OnlineLiveOpsEntry.cs create mode 100644 scripts/detached-liveops/OnlineLiveOpsOperation.cs create mode 100644 scripts/detached-liveops/OnlineLiveOpsRegistry.cs create mode 100644 scripts/legacy/OnlineFriendLegacyMigration.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminActionException.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/AdminActionException.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/AdminActionException.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/AdminActionException.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminActionHandler.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/AdminActionHandler.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/AdminActionHandler.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/AdminActionHandler.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminActionRegistration.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/AdminActionRegistration.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/AdminActionRegistration.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/AdminActionRegistration.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminActionRegistry.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/AdminActionRegistry.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/AdminActionRegistry.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/AdminActionRegistry.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiClaimedScope.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/AdminApiClaimedScope.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiClaimedScope.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/AdminApiClaimedScope.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiErrorCode.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/AdminApiErrorCode.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiErrorCode.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/AdminApiErrorCode.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiErrorCodes.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/AdminApiErrorCodes.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiErrorCodes.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/AdminApiErrorCodes.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiRequest.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/AdminApiRequest.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/AdminApiRequest.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/AdminApiRequest.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminIdempotencyOutcome.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/AdminIdempotencyOutcome.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/AdminIdempotencyOutcome.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/AdminIdempotencyOutcome.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/AdminIdempotencyOutcomeKind.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/AdminIdempotencyOutcomeKind.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/AdminIdempotencyOutcomeKind.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/AdminIdempotencyOutcomeKind.cs diff --git a/Capability/GameFrameX.Capability.Hosting.Abstractions/GameFrameX.Capability.Hosting.Abstractions.csproj b/Capability/GameFrameX.Capability.Hosting.Abstractions/GameFrameX.Capability.Hosting.Abstractions.csproj index 2dc0f6caf..3de99c882 100644 --- a/Capability/GameFrameX.Capability.Hosting.Abstractions/GameFrameX.Capability.Hosting.Abstractions.csproj +++ b/Capability/GameFrameX.Capability.Hosting.Abstractions/GameFrameX.Capability.Hosting.Abstractions.csproj @@ -13,6 +13,7 @@ + diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/IAdminActionContributor.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/IAdminActionContributor.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/IAdminActionContributor.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/IAdminActionContributor.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/IAdminApiIdempotencyAdapter.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/IAdminApiIdempotencyAdapter.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/IAdminApiIdempotencyAdapter.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/IAdminApiIdempotencyAdapter.cs diff --git a/Capability/GameFrameX.Capability.Hosting.AdminApi/IAdminApiScopeAdapter.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/IAdminApiScopeAdapter.cs similarity index 100% rename from Capability/GameFrameX.Capability.Hosting.AdminApi/IAdminApiScopeAdapter.cs rename to Capability/GameFrameX.Capability.Hosting.Abstractions/IAdminApiScopeAdapter.cs diff --git a/Capability/GameFrameX.Capability.Online.Abstractions/GameFrameX.Capability.Online.Abstractions.csproj b/Capability/GameFrameX.Capability.Online.Abstractions/GameFrameX.Capability.Online.Abstractions.csproj index be89e0143..782111528 100644 --- a/Capability/GameFrameX.Capability.Online.Abstractions/GameFrameX.Capability.Online.Abstractions.csproj +++ b/Capability/GameFrameX.Capability.Online.Abstractions/GameFrameX.Capability.Online.Abstractions.csproj @@ -12,11 +12,8 @@ + - - - - diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/AdminApi/OnlineAdminLeaderboardHandlers.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/AdminApi/OnlineAdminLeaderboardHandlers.cs new file mode 100644 index 000000000..0c15b3f6c --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/AdminApi/OnlineAdminLeaderboardHandlers.cs @@ -0,0 +1,183 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the PRC and relevant 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.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Hosting.AdminApi; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Scope; +using GameFrameX.Capability.Online.Competition.Leaderboard; + +namespace GameFrameX.Capability.Online.Competition.AdminApi; + +/// +/// 排行榜域 admin 命令(query_leaderboard——只读榜单查询:单元信息 + Top 条目 + 可选玩家附近窗口)。 +/// +/// 维护约束:只读幂等包裹 false(无状态变更,与 query_match_settlement 同族);跨 App / 跨租户与 +/// 榜单不存在同构 ResourceNotFound(排行榜服务反预言红线);玩家附近窗口为尽力投影(玩家未上榜时省略)。 +/// +/// +public static class OnlineAdminLeaderboardHandlers +{ + /// + /// 注册排行榜查询 action(只读)。 + /// + /// 动作注册表。 + /// 排行榜服务(Register 期构造)。 + public static void RegisterLeaderboardQuery(AdminActionRegistry registry, OnlineLeaderboardService leaderboards) + { + registry.Register("query_leaderboard", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => QueryLeaderboardAsync(request, scope, cancellationToken, leaderboards)), false); + } + + /// + /// query_leaderboard:榜单单元信息 + Top N 条目(Rank/PlayerId/Score)+ 可选 AroundPlayer 窗口。 + /// + /// 请求。 + /// 作用域。 + /// 取消令牌。 + /// 排行榜服务。 + /// 查询响应。 + private static async Task QueryLeaderboardAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLeaderboardService leaderboards) + { + var leaderboardId = OnlineAdminApiContract.RequireString(request, "LeaderboardId"); + var count = request.ReadNullableInt32("Count") ?? 10; + var playerId = request.ReadNullableInt64("PlayerId") ?? 0; + + var boardResult = await leaderboards.ResolveBoardAsync(scope, leaderboardId, cancellationToken).ConfigureAwait(false); + if (!boardResult.IsSuccess) + { + throw new OnlineServiceException(boardResult.Code, boardResult.Message); + } + + var board = boardResult.Data; + var response = new LeaderboardQueryResponse + { + LeaderboardId = board.LeaderboardId, + SortOrder = board.SortOrder.ToString(), + ScoreUpdatePolicy = board.ScoreUpdatePolicy.ToString(), + Top = new List(), + }; + + var topResult = await leaderboards.GetTopAsync(scope, new OnlineLeaderboardTopQuery { LeaderboardId = leaderboardId, Count = count }, cancellationToken).ConfigureAwait(false); + if (topResult.IsSuccess) + { + foreach (var view in topResult.Data.Entries) + { + response.Top.Add(new LeaderboardEntryResponse + { + Rank = view.Rank, + PlayerId = view.Entry.PlayerId, + Score = view.Entry.Score, + }); + } + } + + if (playerId > 0) + { + // 附近窗口为尽力投影:玩家未上榜 / 榜单异常时省略,不阻断整体查询。 + var aroundResult = await leaderboards.GetAroundPlayerAsync(scope, new OnlineLeaderboardAroundQuery { LeaderboardId = leaderboardId, PlayerId = playerId, Before = 2, After = 2 }, cancellationToken).ConfigureAwait(false); + if (aroundResult.IsSuccess) + { + response.AroundPlayer = new LeaderboardAroundResponse + { + PlayerId = aroundResult.Data.PlayerId, + Rank = aroundResult.Data.Rank, + TotalCount = (int)aroundResult.Data.TotalCount, + Around = new List(), + }; + foreach (var view in aroundResult.Data.Around) + { + response.AroundPlayer.Around.Add(new LeaderboardEntryResponse + { + Rank = view.Rank, + PlayerId = view.Entry.PlayerId, + Score = view.Entry.Score, + }); + } + } + } + + return response; + } + + /// + /// 排行榜查询响应(JSON 投影)。 + /// + public sealed class LeaderboardQueryResponse + { + /// 获取或设置榜单标识。 + public string LeaderboardId { get; set; } + + /// 获取或设置排序方向名(Descending/Ascending)。 + public string SortOrder { get; set; } + + /// 获取或设置累计策略名(Best/Sum/Latest)。 + public string ScoreUpdatePolicy { get; set; } + + /// 获取或设置 Top 条目。 + public List Top { get; set; } = new List(); + + /// 获取或设置玩家附近窗口(未请求或玩家未上榜为 null)。 + public LeaderboardAroundResponse AroundPlayer { get; set; } + } + + /// + /// 榜单条目响应(JSON 投影)。 + /// + public sealed class LeaderboardEntryResponse + { + /// 获取或设置名次。 + public int Rank { get; set; } + + /// 获取或设置玩家标识。 + public long PlayerId { get; set; } + + /// 获取或设置分数。 + public long Score { get; set; } + } + + /// + /// 玩家附近窗口响应(JSON 投影)。 + /// + public sealed class LeaderboardAroundResponse + { + /// 获取或设置玩家标识。 + public long PlayerId { get; set; } + + /// 获取或设置玩家名次。 + public int Rank { get; set; } + + /// 获取或设置榜单总条数。 + public int TotalCount { get; set; } + + /// 获取或设置窗口条目(含玩家本人)。 + public List Around { get; set; } = new List(); + } +} diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/IOnlineLeaderboardStore.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/IOnlineLeaderboardStore.cs new file mode 100644 index 000000000..b3419f779 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/IOnlineLeaderboardStore.cs @@ -0,0 +1,114 @@ +// ========================================================================================== +// 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 see 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 System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜存储契约(榜单定义 + 条目;InMemory 为单进程默认实现,生产持久化归 Server 仓运行时装配)。 +/// +/// 维护约束(红线): +/// (1) 作用域隔离——所有查询以 (TenantId, AppId) 为前置条件,跨作用域访问与不存在同构(null,反预言); +/// (2) 是唯一条目写入入口,**累计策略裁决与条目落档必须在同一临界区**, +/// 并发投递不得交错撕裂(形态对齐票据 / 通知存储的临界区约定); +/// (3) 出入参一律防御性拷贝——返回对象与内部状态无别名,调用方改写不影响存储。 +/// +/// +public interface IOnlineLeaderboardStore +{ + /// + /// 创建榜单(同作用域同名榜单已存在时拒绝,返回 null,不覆盖)。 + /// + /// 榜单定义(作用域取其 TenantId / AppId)。 + /// 取消令牌。 + /// 创建后的榜单副本;已存在返回 null。 + Task CreateAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default); + + /// + /// 按作用域查找榜单定义。 + /// + /// 租户标识。 + /// App 标识。 + /// 榜单标识。 + /// 取消令牌。 + /// 榜单副本;不存在或跨作用域返回 null。 + Task FindAsync(long tenantId, long appId, string leaderboardId, CancellationToken cancellationToken = default); + + /// + /// 查找单玩家条目。 + /// + /// 租户标识。 + /// App 标识。 + /// 榜单标识。 + /// 玩家标识。 + /// 取消令牌。 + /// 条目副本;未上榜或榜单不存在返回 null。 + Task FindEntryAsync(long tenantId, long appId, string leaderboardId, long playerId, CancellationToken cancellationToken = default); + + /// + /// 应用一笔分数提交(原子:累计策略裁决 + 条目落档在同一临界区)。 + /// + /// + /// 红线:Sum 策略累加溢出(checked)时拒绝本笔写入并返回 null——条目零状态变更, + /// 不做饱和截断(不把异常数据悄悄写成 long.MaxValue)。未来持久化排行榜存储落地时, + /// 同样的溢出判断必须放进存储层的原子更新里。 + /// + /// 目标榜单定义(调用方先经 取得)。 + /// 分数提交。 + /// 取消令牌。 + /// 写入结果(聚合后条目 + 临界区内事实的前值);Sum 累加溢出拒绝时为 null。 + Task ApplySubmissionAsync(OnlineLeaderboard leaderboard, OnlineLeaderboardScoreSubmission submission, CancellationToken cancellationToken = default); + + /// + /// 列出榜单全序条目(按 排序的条目副本列表)。 + /// + /// 目标榜单定义。 + /// 取消令牌。 + /// 全序条目副本;空榜返回空列表。 + Task> ListOrderedEntriesAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default); + + /// + /// 清空榜上条目(**赛季重置的唯一移除入口**;CAS 语义——只有榜上条目集合与 + /// 逐项一致时才清空,否则拒绝且不改变任何状态)。 + /// + /// 维护约束(红线):「条目一经产生不从榜单移除」的规则在赛季维度由此方法开例外——重置作用于整榜, + /// 不做单条移除。CAS 比对是**榜首快照与清空之间的写入保护**:调用方(赛季服务)以「先持久化快照、 + /// 再按同一份快照清空」的次序执行,比对不一致即说明期间有写入落地,此时必须拒绝清空而不是把 + /// 这条已结算的真实成绩一并抹掉(赛季重置不得丢分)。 + /// + /// + /// 目标榜单定义(调用方先经 取得)。 + /// 调用方持有的全序条目快照(须来自 )。 + /// 取消令牌。 + /// 清空成功返回 true;榜上条目已变化而拒绝清空返回 false。 + Task TryResetAsync(OnlineLeaderboard leaderboard, IReadOnlyList expectedEntries, CancellationToken cancellationToken = default); +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/InMemoryOnlineLeaderboardStore.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/InMemoryOnlineLeaderboardStore.cs new file mode 100644 index 000000000..e7a17cd3c --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/InMemoryOnlineLeaderboardStore.cs @@ -0,0 +1,410 @@ +// ========================================================================================== +// 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 see 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 System; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Foundation.Localization.Core; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜内存存储(单进程默认实现;生产持久化 / 多实例分片归 Server 仓运行时装配)。 +/// +/// 维护约束(红线):榜单定义与条目同锁(单锁粒度:本实现以整体锁保证「策略裁决 + 落档」原子性与 +/// 查询快照一致性;热点写入的分片 / 批量优化属吞吐优化项,归运行时装配,不在此实现)。 +/// 出入参防御性拷贝,存储内对象与外界无别名。 +/// +/// +public sealed class InMemoryOnlineLeaderboardStore : IOnlineLeaderboardStore +{ + /// 全局读写锁(榜单与条目共用,保证快照一致性)。 + private readonly object _syncRoot = new(); + + /// 榜单定义表:键 = (TenantId, AppId, LeaderboardId)。 + private readonly Dictionary _boards = new(); + + /// 条目表:键 = 榜单键 → (PlayerId → 条目)。 + private readonly Dictionary> _entries = new(); + + /// + /// 初始化 。 + /// + public InMemoryOnlineLeaderboardStore() + { + } + + /// + /// 在全局锁内创建榜单:同作用域同标识已存在时拒绝返回 null,否则落档定义副本并初始化空条目表。 + /// + /// + /// Creates the leaderboard under the global lock: refuses with null when the same id already exists in the scope, otherwise stores a defensive copy of the definition and initializes an empty entry table. + /// + /// 榜单定义(作用域取自其 TenantId 与 AppId)/ The leaderboard definition (scope taken from its TenantId and AppId) + /// 取消令牌 / Cancellation token + /// 创建后的榜单副本;已存在返回 null / A copy of the created leaderboard; null when it already exists + /// 当 为 null 时抛出 / Thrown when is null + public Task CreateAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default) + { + if (leaderboard == null) + { + throw new ArgumentNullException(nameof(leaderboard)); + } + + lock (_syncRoot) + { + var key = BuildKey(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId); + if (_boards.ContainsKey(key)) + { + return Task.FromResult(null); + } + + _boards[key] = leaderboard.Copy(); + _entries[key] = new Dictionary(); + return Task.FromResult(leaderboard.Copy()); + } + } + + /// + /// 在全局锁内按作用域与榜单标识查找榜单定义,返回防御性副本。 + /// + /// + /// Finds the leaderboard definition by scope and leaderboard id under the global lock, returning a defensive copy. + /// + /// 租户标识 / The tenant id + /// App 标识 / The app id + /// 榜单标识 / The leaderboard id + /// 取消令牌 / Cancellation token + /// 榜单副本;不存在或跨作用域返回 null / A copy of the leaderboard; null when not found or cross-scope + public Task FindAsync(long tenantId, long appId, string leaderboardId, CancellationToken cancellationToken = default) + { + lock (_syncRoot) + { + return Task.FromResult(TryFindBoard(tenantId, appId, leaderboardId, out var board) ? board.Copy() : null); + } + } + + /// + /// 在全局锁内查找指定玩家的榜上条目,返回防御性副本。 + /// + /// + /// Finds a single player's entry on the board under the global lock, returning a defensive copy. + /// + /// 租户标识 / The tenant id + /// App 标识 / The app id + /// 榜单标识 / The leaderboard id + /// 玩家标识 / The player id + /// 取消令牌 / Cancellation token + /// 条目副本;未上榜或榜单不存在返回 null / A copy of the entry; null when the player is unranked or the board does not exist + public Task FindEntryAsync(long tenantId, long appId, string leaderboardId, long playerId, CancellationToken cancellationToken = default) + { + lock (_syncRoot) + { + if (!TryFindBoard(tenantId, appId, leaderboardId, out _) || !_entries.TryGetValue(BuildKey(tenantId, appId, leaderboardId), out var boardEntries) || !boardEntries.TryGetValue(playerId, out var entry)) + { + return Task.FromResult(null); + } + + return Task.FromResult(entry.Copy()); + } + } + + /// + /// 在全局锁内的同一临界区按累计策略裁决分数并落档条目,不存在则新建条目。 + /// + /// + /// Resolves the score by the accumulation policy and archives the entry within the same critical section under the global lock, creating the entry when absent. + /// + /// Sum 策略累加溢出(checked)时拒绝本笔写入并返回 null:条目零状态变更—— + /// 已有条目保持原分数与提交计数;本次新建的条目会被回滚移除,不留半截档。 + /// + /// + /// 目标榜单定义(调用方先经 取得)/ The target leaderboard definition (obtained by the caller via first) + /// 分数提交 / The score submission + /// 取消令牌 / The cancellation token + /// 写入结果(聚合后条目副本与临界区内事实的前值);Sum 累加溢出拒绝时为 null / The apply result (the merged entry copy and the pre-update facts observed inside the critical section); null when the Sum accumulation overflows and the write is refused + /// 当 或 为 null 时抛出 / Thrown when or is null + /// 当目标榜单未创建或已失效(未经 解析)时抛出 / Thrown when the target leaderboard is not created or has expired (not resolved via ) + public Task ApplySubmissionAsync(OnlineLeaderboard leaderboard, OnlineLeaderboardScoreSubmission submission, CancellationToken cancellationToken = default) + { + if (leaderboard == null) + { + throw new ArgumentNullException(nameof(leaderboard)); + } + + if (submission == null) + { + throw new ArgumentNullException(nameof(submission)); + } + + lock (_syncRoot) + { + var key = BuildKey(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId); + if (!_boards.ContainsKey(key) || !_entries.TryGetValue(key, out var boardEntries)) + { + // Localization: Online.Leaderboard.NotFoundOnWrite - 榜单不存在或已失效,写入前必须先经 FindAsync 解析 + throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Online.Leaderboard.NotFoundOnWrite)); + } + + if (!boardEntries.TryGetValue(submission.PlayerId, out var entry)) + { + entry = new OnlineLeaderboardEntry { PlayerId = submission.PlayerId, }; + boardEntries[submission.PlayerId] = entry; + } + + if (!TryResolveScore(leaderboard, entry, submission.IncomingScore, out var resolvedScore)) + { + // Sum 累加溢出:拒绝本笔写入,零状态变更(新建条目回滚移除,不递增提交计数)。 + if (entry.SubmissionCount == 0) + { + boardEntries.Remove(submission.PlayerId); + } + + return Task.FromResult(null); + } + + var oldScore = entry.Score; + var isNewEntry = entry.SubmissionCount == 0; + entry.Score = resolvedScore; + entry.SourceKind = submission.SourceKind; + entry.SourceMatchResultId = submission.SourceMatchResultId; + entry.LastUpdateTime = submission.SubmittedTime; + entry.SubmissionCount++; + + return Task.FromResult(new OnlineLeaderboardApplyResult + { + Entry = entry.Copy(), + OldScore = oldScore, + IsNewEntry = isNewEntry, + }); + } + } + + /// + /// 在全局锁内拷贝全榜条目,再按榜单排序规则排出全序返回。 + /// + /// + /// Copies every entry of the board under the global lock, then sorts the copies into the full order defined by the board's sort rule. + /// + /// 目标榜单定义 / The target leaderboard definition + /// 取消令牌 / Cancellation token + /// 全序条目副本;空榜返回空列表 / The ordered entry copies; an empty list for an empty board + /// 当 为 null 时抛出 / Thrown when is null + /// 当目标榜单未创建或已失效(未经 解析)时抛出 / Thrown when the target leaderboard is not created or has expired (not resolved via ) + public Task> ListOrderedEntriesAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default) + { + if (leaderboard == null) + { + throw new ArgumentNullException(nameof(leaderboard)); + } + + List copies; + lock (_syncRoot) + { + var key = BuildKey(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId); + if (!_entries.TryGetValue(key, out var boardEntries)) + { + // Localization: Online.Leaderboard.NotFoundOnQuery - 榜单不存在或已失效,查询前必须先经 FindAsync 解析 + throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Online.Leaderboard.NotFoundOnQuery)); + } + + copies = new List(boardEntries.Count); + foreach (var entry in boardEntries.Values) + { + copies.Add(entry.Copy()); + } + } + + OnlineLeaderboardOrdering.Sort(leaderboard.SortOrder, copies); + return Task.FromResult(copies); + } + + /// + /// 在全局锁内将榜上条目与期望快照做 CAS 比对,完全一致才清空整榜,否则拒绝且不改变状态。 + /// + /// + /// Compares the board entries against the expected snapshot as a CAS check under the global lock, clearing the whole board only on an exact match and otherwise refusing without any state change. + /// + /// 目标榜单定义 / The target leaderboard definition + /// 调用方持有的全序条目快照 / The ordered entry snapshot held by the caller + /// 取消令牌 / Cancellation token + /// 清空成功返回 true;榜上条目已变化而拒绝清空返回 false / True when the board is cleared; false when the entries changed and the reset is refused + /// 当 或 为 null 时抛出 / Thrown when or is null + /// 当目标榜单未创建或已失效(未经 解析)时抛出 / Thrown when the target leaderboard is not created or has expired (not resolved via ) + public Task TryResetAsync(OnlineLeaderboard leaderboard, IReadOnlyList expectedEntries, CancellationToken cancellationToken = default) + { + if (leaderboard == null) + { + throw new ArgumentNullException(nameof(leaderboard)); + } + + if (expectedEntries == null) + { + throw new ArgumentNullException(nameof(expectedEntries)); + } + + lock (_syncRoot) + { + var key = BuildKey(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId); + if (!_entries.TryGetValue(key, out var boardEntries)) + { + // Localization: Online.Leaderboard.NotFoundOnReset - 榜单不存在或已失效,重置前必须先经 FindAsync 解析 + throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Online.Leaderboard.NotFoundOnReset)); + } + + if (!MatchesExpectedOrdered(leaderboard, boardEntries, expectedEntries)) + { + return Task.FromResult(false); + } + + boardEntries.Clear(); + return Task.FromResult(true); + } + } + + /// + /// 在临界区内比对榜上条目与调用方持有的快照是否逐项一致(CAS 判据)。 + /// + /// 榜单定义(取排序方向重建全序)。 + /// 临界区内的条目表。 + /// 调用方持有的全序条目快照。 + /// 完全一致返回 true。 + private static bool MatchesExpectedOrdered(OnlineLeaderboard leaderboard, Dictionary boardEntries, IReadOnlyList expectedEntries) + { + if (boardEntries.Count != expectedEntries.Count) + { + return false; + } + + var current = new List(boardEntries.Values); + OnlineLeaderboardOrdering.Sort(leaderboard.SortOrder, current); + for (var index = 0; index < current.Count; index++) + { + if (!MatchesExpectedEntry(current[index], expectedEntries[index])) + { + return false; + } + } + + return true; + } + + /// + /// 比对单个条目是否与快照一致(玩家、分数、更新时间、提交计数四要素全等)。 + /// + /// 临界区内的条目。 + /// 快照中的条目。 + /// 一致返回 true。 + private static bool MatchesExpectedEntry(OnlineLeaderboardEntry current, OnlineLeaderboardEntry expected) + { + return expected != null + && current.PlayerId == expected.PlayerId + && current.Score == expected.Score + && current.LastUpdateTime == expected.LastUpdateTime + && current.SubmissionCount == expected.SubmissionCount; + } + + /// + /// 在锁内解析榜单定义(调用方已持锁)。 + /// + /// 租户标识。 + /// App 标识。 + /// 榜单标识。 + /// 解析到的榜单定义。 + /// 存在返回 true。 + private bool TryFindBoard(long tenantId, long appId, string leaderboardId, out OnlineLeaderboard board) + { + board = null; + if (string.IsNullOrEmpty(leaderboardId)) + { + return false; + } + + if (!_boards.TryGetValue(BuildKey(tenantId, appId, leaderboardId), out var stored)) + { + return false; + } + + board = stored; + return true; + } + + /// + /// 在临界区内按累计策略裁决新分数(首笔直接生效;Best 以榜向判优,Sum 累加(checked,溢出拒绝),Latest 覆盖)。 + /// + /// 榜单定义。 + /// 临界区内当前条目。 + /// 本笔分数。 + /// 裁决后的分数(失败时为条目原分数,不落档)。 + /// 裁决成功返回 true;Sum 累加溢出返回 false(本笔写入被拒绝,不做饱和截断)。 + private static bool TryResolveScore(OnlineLeaderboard leaderboard, OnlineLeaderboardEntry entry, long incomingScore, out long resolvedScore) + { + if (entry.SubmissionCount == 0) + { + resolvedScore = incomingScore; + return true; + } + + switch (leaderboard.ScoreUpdatePolicy) + { + case OnlineLeaderboardScoreUpdatePolicy.Sum: + try + { + resolvedScore = checked(entry.Score + incomingScore); + return true; + } + catch (OverflowException) + { + resolvedScore = entry.Score; + return false; + } + case OnlineLeaderboardScoreUpdatePolicy.Latest: + resolvedScore = incomingScore; + return true; + case OnlineLeaderboardScoreUpdatePolicy.Best: + default: + resolvedScore = OnlineLeaderboardOrdering.IsBetter(leaderboard.SortOrder, incomingScore, entry.Score) ? incomingScore : entry.Score; + return true; + } + } + + /// + /// 构造存储键(作用域 + 榜单标识;跨作用域访问因键不同而自然隔离)。 + /// + /// 租户标识。 + /// App 标识。 + /// 榜单标识。 + /// 存储键。 + private static string BuildKey(long tenantId, long appId, string leaderboardId) + { + return tenantId.ToString(CultureInfo.InvariantCulture) + ":" + appId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboardId; + } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineCompetitionOptions.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineCompetitionOptions.cs new file mode 100644 index 000000000..f548b97a9 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineCompetitionOptions.cs @@ -0,0 +1,69 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the PRC and relevant 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 GameFrameX.Capability.Hosting.Abstractions; +using GameFrameX.Capability.Online.Competition.Leaderboard; + +namespace GameFrameX.Capability.Online.Competition; + +/// +/// 竞技能力包级 Options 根类型(C294:聚合榜单组件参数与 Match.Settled 投影配置; +/// 投影子对象收编族级键 MatchBridgeLeaderboardId → Settings.online-competition.LeaderboardProjection.MatchSettledBoardId, +/// 默认值唯一来源 = 字段初始值)。 +/// +public sealed class OnlineCompetitionOptions : ICapabilityOptions +{ + /// + /// 获取或设置排行榜组件选项(防刷阈值 / 限流窗口 / 读缓存 / 分页上限)。 + /// + public OnlineLeaderboardOptions Leaderboard { get; set; } = new OnlineLeaderboardOptions(); + + /// + /// 获取或设置 Match.Settled 写榜投影配置(MatchSettledBoardId 空白 = 不投影不预建)。 + /// + public OnlineLeaderboardProjectionOptions LeaderboardProjection { get; set; } = new OnlineLeaderboardProjectionOptions(); + + /// + /// 校验排行榜组件选项:单次提交最大分数、限流最大提交次数、限流窗口秒数、缓存有效期秒数与最大分页大小均须为正数;投影配置不做校验(空白榜单标识表示不投影)。 + /// + /// + /// 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. + /// + /// 选项校验结果收集器 / Options validation collector + public void Validate(CapabilityOptionsValidation validation) + { + validation.RequirePositive("Leaderboard.DefaultMaxScorePerSubmission", Leaderboard.DefaultMaxScorePerSubmission); + validation.RequirePositive("Leaderboard.RateLimitMaxSubmissions", Leaderboard.RateLimitMaxSubmissions); + validation.RequirePositive("Leaderboard.RateLimitWindowSeconds", Leaderboard.RateLimitWindowSeconds); + validation.RequirePositive("Leaderboard.CacheTtlSeconds", Leaderboard.CacheTtlSeconds); + validation.RequirePositive("Leaderboard.MaxPageSize", Leaderboard.MaxPageSize); + } +} diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboard.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboard.cs new file mode 100644 index 000000000..62bffdfba --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboard.cs @@ -0,0 +1,95 @@ +// ========================================================================================== +// 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 see 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜榜单定义(第一版个人榜;作用域 = (TenantId, AppId),App 内跨区服聚合)。 +/// +/// 维护约束(红线):榜单归属租户与 App 双键隔离——跨 App / 跨租户读写一律查不到(ResourceNotFound 反预言, +/// 对齐存储与频道的既有先例,不泄露榜单存在性);ServerId 不参与榜单隔离, +/// 队伍榜 / 公会榜 / 复杂跨服排名延后(超出首版范围)。排序方向与累计策略创建后固化,运行期不可变更; +/// 赛季维度的生命周期(重置 / 快照)归赛季域,本类型不承载赛季字段。 +/// +/// +public sealed class OnlineLeaderboard +{ + /// + /// 获取或设置榜单标识(App 内唯一,创建方提供)。 + /// + public string LeaderboardId { get; set; } + + /// + /// 获取或设置租户标识(作用域隔离键)。 + /// + public long TenantId { get; set; } + + /// + /// 获取或设置 App 标识(作用域隔离键)。 + /// + public long AppId { get; set; } + + /// + /// 获取或设置排序方向(创建后固化)。 + /// + public OnlineLeaderboardSortOrder SortOrder { get; set; } + + /// + /// 获取或设置分数累计策略(创建后固化)。 + /// + public OnlineLeaderboardScoreUpdatePolicy ScoreUpdatePolicy { get; set; } + + /// + /// 获取或设置单次提交分数合理上限(防刷校验上界;0 = 使用 全局默认值)。 + /// + public long MaxScorePerSubmission { get; set; } + + /// + /// 获取或设置创建时刻(UTC 毫秒)。 + /// + public long CreatedTime { get; set; } + + /// + /// 复制榜单定义(存储出入参防御性拷贝)。 + /// + /// 榜单定义副本。 + public OnlineLeaderboard Copy() + { + return new OnlineLeaderboard + { + LeaderboardId = LeaderboardId, + TenantId = TenantId, + AppId = AppId, + SortOrder = SortOrder, + ScoreUpdatePolicy = ScoreUpdatePolicy, + MaxScorePerSubmission = MaxScorePerSubmission, + CreatedTime = CreatedTime, + }; + } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardApplyResult.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardApplyResult.cs new file mode 100644 index 000000000..cea4cead1 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardApplyResult.cs @@ -0,0 +1,55 @@ +// ========================================================================================== +// 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 see 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 存储临界区内的单笔写入结果(新条目 / 聚合后条目 + 临界区内事实的前值,供事件载荷使用)。 +/// +/// 维护约束: 与 均取自同一临界区快照——并发写入下 +/// 事件载荷的前后值也是真实前后值,不得由服务层先读后写拼装(会被并发交错撕裂)。 +/// +/// +public sealed class OnlineLeaderboardApplyResult +{ + /// + /// 获取或设置写入后的条目副本(含聚合分数与提交计数)。 + /// + public OnlineLeaderboardEntry Entry { get; set; } + + /// + /// 获取或设置写入前分数(首笔为 0;临界区内事实)。 + /// + public long OldScore { get; set; } + + /// + /// 获取或设置是否为本玩家首笔写入(此前未上榜)。 + /// + public bool IsNewEntry { get; set; } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardAroundQuery.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardAroundQuery.cs new file mode 100644 index 000000000..86da7c613 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardAroundQuery.cs @@ -0,0 +1,67 @@ +// ========================================================================================== +// 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 related 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 see the LICENSE file in the root directory of the source code. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 玩家附近排名窗口查询载荷( 除作用域外的全部查询维度; +/// 窗口含玩家本人,边界处截断)。 +/// +public sealed class OnlineLeaderboardAroundQuery +{ + /// + /// 获取或设置榜单标识。 + /// + /// Gets or sets the leaderboard id. + public string LeaderboardId { get; init; } + + /// + /// 获取或设置玩家标识(未上榜返回 ResourceNotFound)。 + /// + /// Gets or sets the player id (an unranked player yields ResourceNotFound). + public long PlayerId { get; init; } + + /// + /// 获取或设置前向窗口条数(缺省 0 = 不含前向邻居;Before / After 均缺省时窗口仅含本人)。 + /// + /// Gets or sets the number of entries before the player (default 0 = no preceding neighbors; when both Before and After are left at 0 the window contains only the player). + public int Before { get; init; } + + /// + /// 获取或设置后向窗口条数(缺省 0 = 不含后向邻居;Before / After 均缺省时窗口仅含本人)。 + /// + /// Gets or sets the number of entries after the player (default 0 = no following neighbors; when both Before and After are left at 0 the window contains only the player). + public int After { get; init; } + + /// + /// 获取或设置当前时刻(UTC 毫秒;传 0 取系统时钟)。 + /// + /// Gets or sets the current time (UTC milliseconds; 0 = system clock). + public long NowUnixMilliseconds { get; init; } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardAroundView.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardAroundView.cs new file mode 100644 index 000000000..6bbbd9c23 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardAroundView.cs @@ -0,0 +1,62 @@ +// ========================================================================================== +// 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 see 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 System.Collections.Generic; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 玩家附近排名视图(以目标玩家为中心的连续名次窗口,窗口含目标玩家本人)。 +/// +/// 维护约束:窗口在榜单边界处截断——榜首请求的前向窗口与榜尾请求的后向窗口返回实际存在的条目, +/// 不以占位条目填充(附近排名边界);窗口内名次连续(rank 单调 +1),供客户端直接渲染。 +/// +/// +public sealed class OnlineLeaderboardAroundView +{ + /// + /// 获取或设置目标玩家标识。 + /// + public long PlayerId { get; set; } + + /// + /// 获取或设置目标玩家名次(从 1 开始)。 + /// + public int Rank { get; set; } + + /// + /// 获取或设置榜单条目总数(当前快照口径)。 + /// + public long TotalCount { get; set; } + + /// + /// 获取或设置附近窗口条目(含目标玩家,按名次升序;窗口边界处截断)。 + /// + public List Around { get; set; } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCreateRequest.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCreateRequest.cs new file mode 100644 index 000000000..8934ef8ae --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCreateRequest.cs @@ -0,0 +1,60 @@ +// ========================================================================================== +// 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 see 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜创建请求(服务端运营 / 运行时装配入口;客户端无此入口)。 +/// +/// 维护约束:作用域取鉴权上下文的 ,请求体不携带 TenantId / AppId(服务端不信任请求体作用域); +/// 同名榜单在 (TenantId, AppId) 内已存在时创建被拒绝(ParameterInvalid),不覆盖既有榜单。 +/// +/// +public sealed class OnlineLeaderboardCreateRequest +{ + /// + /// 获取或设置榜单标识(App 内唯一,非空)。 + /// + public string LeaderboardId { get; set; } + + /// + /// 获取或设置排序方向(默认高分优先)。 + /// + public OnlineLeaderboardSortOrder SortOrder { get; set; } + + /// + /// 获取或设置分数累计策略(默认保留最优)。 + /// + public OnlineLeaderboardScoreUpdatePolicy ScoreUpdatePolicy { get; set; } + + /// + /// 获取或设置单次提交分数合理上限(0 = 使用全局默认值)。 + /// + public long MaxScorePerSubmission { get; set; } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEntry.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEntry.cs new file mode 100644 index 000000000..ef58b64ae --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEntry.cs @@ -0,0 +1,88 @@ +// ========================================================================================== +// 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 see 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜条目(单玩家在单榜单上的聚合状态;名次不在条目上,查询时按全序计算)。 +/// +/// 维护约束(红线):分数只经可信写入链路产生( 即来源白名单), +/// 使每笔分数可追溯到结算结果——争议判定的审计依据; +/// 条目一经产生不从榜单移除(第一版无移除语义,赛季重置归赛季域)。 +/// +/// +public sealed class OnlineLeaderboardEntry +{ + /// + /// 获取或设置玩家标识。 + /// + public long PlayerId { get; set; } + + /// + /// 获取或设置榜上分数(按榜单累计策略聚合后的当前值)。 + /// + public long Score { get; set; } + + /// + /// 获取或设置最近一次写入的分数来源。 + /// + public OnlineLeaderboardScoreSource SourceKind { get; set; } + + /// + /// 获取或设置最近一次写入的来源结算结果标识(追溯键)。 + /// + public string SourceMatchResultId { get; set; } + + /// + /// 获取或设置最近一次写入时刻(UTC 毫秒;并列分数的次级排序键,先写入者靠前)。 + /// + public long LastUpdateTime { get; set; } + + /// + /// 获取或设置累计提交次数(含未改变分数的提交,如 Best 策略下的非更优分数)。 + /// + public int SubmissionCount { get; set; } + + /// + /// 复制条目(存储出入参防御性拷贝)。 + /// + /// 条目副本。 + public OnlineLeaderboardEntry Copy() + { + return new OnlineLeaderboardEntry + { + PlayerId = PlayerId, + Score = Score, + SourceKind = SourceKind, + SourceMatchResultId = SourceMatchResultId, + LastUpdateTime = LastUpdateTime, + SubmissionCount = SubmissionCount, + }; + } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEntryView.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEntryView.cs new file mode 100644 index 000000000..b7de387cd --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEntryView.cs @@ -0,0 +1,65 @@ +// ========================================================================================== +// 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 see 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 System.Collections.Generic; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜查询条目视图(条目 + 按全序计算的名次;名次是查询时事实,不落存储)。 +/// +/// 维护约束:名次必须由 全序计算(并列时以更新时间与玩家标识稳定消解, +/// 不产生同名次空洞)——Top N / 附近排名 / 分页三个查询口径共用同一全序,保证结果可复算。 +/// +/// +public sealed class OnlineLeaderboardEntryView +{ + /// + /// 获取或设置名次(从 1 开始;全序唯一,无并列名次)。 + /// + public int Rank { get; set; } + + /// + /// 获取或设置榜上条目。 + /// + public OnlineLeaderboardEntry Entry { get; set; } + + /// + /// 复制视图(条目深拷贝)。 + /// + /// 视图副本。 + public OnlineLeaderboardEntryView Copy() + { + return new OnlineLeaderboardEntryView + { + Rank = Rank, + Entry = Entry == null ? null : Entry.Copy(), + }; + } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEvents.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEvents.cs new file mode 100644 index 000000000..797125442 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEvents.cs @@ -0,0 +1,195 @@ +// ========================================================================================== +// 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 see 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 System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.Json; +using GameFrameX.Capability.Online.Abstractions.Events; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行域事件工厂(统一信封事件,Source = "online-leaderboard")。 +/// +/// 维护约束(红线):事件是**事实不是状态**—— 只陈述「某玩家分数已由某结算结果 +/// 变更为某值」,榜上名次不进事件(名次是查询时事实,快照口径随读变化);载荷与审计字段都不含 +/// 玩家私有数据。分数变更事件只可能由可信写入链路产生(分数写入唯一入口即投影器)。 +/// +/// +public static class OnlineLeaderboardEvents +{ + /// 榜单创建。 + public const string LeaderboardCreated = "online.leaderboard.created"; + + /// 榜上分数更新(可信写入)。 + public const string ScoreUpdated = "online.leaderboard.scoreupdated"; + + /// 事件来源标识。 + public const string Source = "online-leaderboard"; + + /// + /// 构造榜单创建事件。 + /// + /// 租户标识。 + /// App 标识。 + /// 榜单标识(可空;载荷落空字符串)。 + /// 排序方向名。 + /// 累计策略名。 + /// 创建时刻(UTC 毫秒)。 + /// 事件信封实例。 + public static OnlineEvent CreateLeaderboardCreated(long tenantId, long appId, string leaderboardId, string sortOrder, string scoreUpdatePolicy, long createdTime) + { + var payload = new LeaderboardCreatedPayload + { + LeaderboardId = leaderboardId ?? string.Empty, + SortOrder = sortOrder, + ScoreUpdatePolicy = scoreUpdatePolicy, + CreatedTime = createdTime, + }; + var auditFields = new Dictionary + { + { "LeaderboardId", leaderboardId ?? string.Empty }, + { "SortOrder", sortOrder }, + { "ScoreUpdatePolicy", scoreUpdatePolicy }, + { "CreatedTime", createdTime.ToString(CultureInfo.InvariantCulture) }, + }; + return new OnlineEvent + { + EventId = "evt-" + Guid.NewGuid().ToString("N"), + EventType = LeaderboardCreated, + OccurredTime = createdTime > 0 ? createdTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + SchemaVersion = 1, + TenantId = tenantId, + AppId = appId, + ServerId = 0, + PlayerId = 0, + Source = Source, + CorrelationId = string.Empty, + Payload = JsonSerializer.SerializeToUtf8Bytes(payload), + PayloadAuditFields = auditFields, + }; + } + + /// + /// 构造榜上分数更新事件。 + /// + /// 租户标识。 + /// App 标识。 + /// 榜单标识(可空;载荷落空字符串)。 + /// 玩家标识。 + /// 变更前分数。 + /// 变更后分数。 + /// 来源结算结果标识(追溯键,兼作 CorrelationId)。 + /// 变更时刻(UTC 毫秒)。 + /// 事件信封实例。 + public static OnlineEvent CreateScoreUpdated(long tenantId, long appId, string leaderboardId, long playerId, long oldScore, long newScore, string sourceMatchResultId, long updatedTime) + { + var payload = new ScoreUpdatedPayload + { + LeaderboardId = leaderboardId ?? string.Empty, + PlayerId = playerId, + OldScore = oldScore, + NewScore = newScore, + SourceKind = OnlineLeaderboardScoreSource.MatchResult.ToString(), + SourceMatchResultId = sourceMatchResultId ?? string.Empty, + UpdatedTime = updatedTime, + }; + var auditFields = new Dictionary + { + { "LeaderboardId", leaderboardId ?? string.Empty }, + { "PlayerId", playerId.ToString(CultureInfo.InvariantCulture) }, + { "OldScore", oldScore.ToString(CultureInfo.InvariantCulture) }, + { "NewScore", newScore.ToString(CultureInfo.InvariantCulture) }, + { "SourceKind", OnlineLeaderboardScoreSource.MatchResult.ToString() }, + { "SourceMatchResultId", sourceMatchResultId ?? string.Empty }, + { "UpdatedTime", updatedTime.ToString(CultureInfo.InvariantCulture) }, + }; + return new OnlineEvent + { + EventId = "evt-" + Guid.NewGuid().ToString("N"), + EventType = ScoreUpdated, + OccurredTime = updatedTime > 0 ? updatedTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + SchemaVersion = 1, + TenantId = tenantId, + AppId = appId, + ServerId = 0, + PlayerId = playerId, + Source = Source, + CorrelationId = sourceMatchResultId ?? string.Empty, + Payload = JsonSerializer.SerializeToUtf8Bytes(payload), + PayloadAuditFields = auditFields, + }; + } + + /// + /// 榜单创建事件负载(SchemaVersion=1)。 + /// + private sealed class LeaderboardCreatedPayload + { + /// 榜单标识。 + public string LeaderboardId { get; set; } + + /// 排序方向名。 + public string SortOrder { get; set; } + + /// 累计策略名。 + public string ScoreUpdatePolicy { get; set; } + + /// 创建时刻(UTC 毫秒)。 + public long CreatedTime { get; set; } + } + + /// + /// 榜上分数更新事件负载(SchemaVersion=1)。 + /// + private sealed class ScoreUpdatedPayload + { + /// 榜单标识。 + public string LeaderboardId { get; set; } + + /// 玩家标识。 + public long PlayerId { get; set; } + + /// 变更前分数。 + public long OldScore { get; set; } + + /// 变更后分数。 + public long NewScore { get; set; } + + /// 分数来源名。 + public string SourceKind { get; set; } + + /// 来源结算结果标识。 + public string SourceMatchResultId { get; set; } + + /// 变更时刻(UTC 毫秒)。 + public long UpdatedTime { get; set; } + } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardOptions.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardOptions.cs new file mode 100644 index 000000000..0ab14baeb --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardOptions.cs @@ -0,0 +1,71 @@ +// ========================================================================================== +// 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 see 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜组件选项(防刷阈值 / 限流窗口 / 读缓存;运行时装配注入,缺省值即安全默认)。 +/// +/// 维护约束:阈值调整只影响「拦多拦少」,不得改变拦截语义(越界 → 风控拒绝、高频 → 限流拒绝); +/// 压测需同时验证「高频被拦」与「正常节奏不受影响」两半。 +/// 缓存 TTL 只影响读延迟不影响正确性——任何写榜立即失效对应榜单缓存。 +/// +/// +public sealed class OnlineLeaderboardOptions +{ + /// + /// 获取或设置单次提交分数合理上限的全局默认值(榜单未显式配置时生效;取绝对值比较,正负同界)。 + /// + public long DefaultMaxScorePerSubmission { get; set; } = 1_000_000; + + /// + /// 获取或设置限流窗口内允许的提交次数(按 玩家 分桶;仅首次执行分支计数,幂等重放不烧配额)。 + /// + public int RateLimitMaxSubmissions { get; set; } = 120; + + /// + /// 获取或设置限流滑动窗口时长(秒)。 + /// + public int RateLimitWindowSeconds { get; set; } = 60; + + /// + /// 获取或设置是否启用 Top N 读缓存。 + /// + public bool CacheEnabled { get; set; } = true; + + /// + /// 获取或设置读缓存 TTL(秒;过期后下次查询重建快照,写榜立即失效不受 TTL 约束)。 + /// + public int CacheTtlSeconds { get; set; } = 5; + + /// + /// 获取或设置单页条目数上限(防一次拉全榜;请求超出按上限截断)。 + /// + public int MaxPageSize { get; set; } = 200; +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardOrdering.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardOrdering.cs new file mode 100644 index 000000000..2e32dc8ef --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardOrdering.cs @@ -0,0 +1,114 @@ +// ========================================================================================== +// 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 see 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 System; +using System.Collections.Generic; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜全序比较器(唯一名次口径:分数按榜向 → 更新时间升序 → 玩家标识升序)。 +/// +/// 维护约束(红线):这是 Top N / 附近排名 / 分页 / keyset 游标共用的**唯一**排序事实来源, +/// 禁止在服务或存储里另写一份比较逻辑;次级键保证同分玩家也有确定全序(先写入者靠前,再按玩家标识消解), +/// 名次无并列空洞、结果可复算。修改比较语义 = 修改全部查询口径,须先经设计评审。 +/// +/// +public static class OnlineLeaderboardOrdering +{ + /// + /// 按榜单方向比较两个条目的名次先后。 + /// + /// 榜单排序方向。 + /// 左条目。 + /// 右条目。 + /// 左条目名次靠前返回负数;靠后返回正数;同一玩家返回 0。 + public static int Compare(OnlineLeaderboardSortOrder sortOrder, OnlineLeaderboardEntry left, OnlineLeaderboardEntry right) + { + if (ReferenceEquals(left, right)) + { + return 0; + } + + if (left == null) + { + return 1; + } + + if (right == null) + { + return -1; + } + + var scoreComparison = sortOrder == OnlineLeaderboardSortOrder.Ascending + ? left.Score.CompareTo(right.Score) + : right.Score.CompareTo(left.Score); + if (scoreComparison != 0) + { + return scoreComparison; + } + + var timeComparison = left.LastUpdateTime.CompareTo(right.LastUpdateTime); + if (timeComparison != 0) + { + return timeComparison; + } + + return left.PlayerId.CompareTo(right.PlayerId); + } + + /// + /// 判定候选分数是否优于既有分数(Best 策略裁决口径,与名次方向同源)。 + /// + /// 榜单排序方向。 + /// 候选分数。 + /// 当前分数。 + /// 候选更优返回 true;持平或更差返回 false。 + public static bool IsBetter(OnlineLeaderboardSortOrder sortOrder, long candidateScore, long currentScore) + { + return sortOrder == OnlineLeaderboardSortOrder.Ascending + ? candidateScore < currentScore + : candidateScore > currentScore; + } + + /// + /// 以榜单方向对条目列表做全序排序(原位排序;调用方保证传入副本)。 + /// + /// 榜单排序方向。 + /// 待排序列表。 + public static void Sort(OnlineLeaderboardSortOrder sortOrder, List entries) + { + if (entries == null) + { + throw new ArgumentNullException(nameof(entries)); + } + + entries.Sort((left, right) => Compare(sortOrder, left, right)); + } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardPage.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardPage.cs new file mode 100644 index 000000000..c698c3ea5 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardPage.cs @@ -0,0 +1,58 @@ +// ========================================================================================== +// 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 see 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 System.Collections.Generic; +using GameFrameX.Capability.Online.Abstractions.Contracts; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜分页结果(Top N / 翻页共用;keyset 游标,翻页期间新增数据不重复不漏项)。 +/// +/// 维护约束:游标由服务端按全序稳定键编码,客户端视为不透明令牌只回传不解释(稳定性约定沿用); +/// 翻页期间插入更高名次条目不会使后续页漏项或重复(keyset 语义,区别于偏移量分页)。 +/// +/// +public sealed class OnlineLeaderboardPage +{ + /// + /// 获取或设置本页条目(按榜单全序升序名次排列)。 + /// + public List Entries { get; set; } + + /// + /// 获取或设置分页游标(末页游标为空字符串)。 + /// + public OnlinePageCursor Cursor { get; set; } + + /// + /// 获取或设置榜单条目总数(当前快照口径)。 + /// + public long TotalCount { get; set; } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionFailure.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionFailure.cs new file mode 100644 index 000000000..7756441d6 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionFailure.cs @@ -0,0 +1,54 @@ +// ========================================================================================== +// 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 see 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 System.Collections.Generic; +using GameFrameX.Capability.Online.Abstractions.Contracts; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 单玩家投影失败明细(错误码 + 拒绝原因;逐玩家隔离,不阻塞其余玩家)。 +/// +public sealed class OnlineLeaderboardProjectionFailure +{ + /// + /// 获取或设置玩家标识。 + /// + public long PlayerId { get; set; } + + /// + /// 获取或设置失败错误码(防刷拒绝 / 限流 / 幂等冲突 / 占位繁忙等)。 + /// + public OnlineErrorCode Code { get; set; } + + /// + /// 获取或设置失败原因(脱敏后的可读描述,供日志与排查)。 + /// + public string Message { get; set; } +} diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionOptions.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionOptions.cs new file mode 100644 index 000000000..241945c3f --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionOptions.cs @@ -0,0 +1,43 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the PRC and relevant 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜投影选项( 的子对象; +/// 非空白才装配 Match.Settled 投影与激活期榜单预建, +/// 空白 / 缺省 = 不投影,不报错)。 +/// +public sealed class OnlineLeaderboardProjectionOptions +{ + /// + /// 获取或设置 Match.Settled 事件的目标榜单标识(空白 = 不投影)。 + /// + public string MatchSettledBoardId { get; set; } +} diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionOutcome.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionOutcome.cs new file mode 100644 index 000000000..b43a60e01 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionOutcome.cs @@ -0,0 +1,69 @@ +// ========================================================================================== +// 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 see 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 System.Collections.Generic; +using GameFrameX.Capability.Online.Abstractions.Contracts; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 可信结果投影回执(一次投递对一榜的逐玩家执行汇总)。 +/// +/// 维护约束:同结果事件重复投递时,首次 计入、后续全部计入 +/// (分数不重复累计); 是逐玩家隔离结果—— +/// 一个玩家被防刷 / 限流拒绝不影响同结果其余玩家落榜(「正常玩家不受影响」)。 +/// +/// +public sealed class OnlineLeaderboardProjectionOutcome +{ + /// + /// 获取或设置投影的结算结果标识。 + /// + public string MatchResultId { get; set; } + + /// + /// 获取或设置目标榜单标识。 + /// + public string LeaderboardId { get; set; } + + /// + /// 获取或设置本次首次落榜的玩家数。 + /// + public int AppliedCount { get; set; } + + /// + /// 获取或设置本次命中幂等回放(此前已落榜)的玩家数。 + /// + public int ReplayCount { get; set; } + + /// + /// 获取或设置被拒绝玩家的失败明细列表。 + /// + public List FailedPlayers { get; set; } = new(); +} diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionRetryStatus.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionRetryStatus.cs new file mode 100644 index 000000000..b4b66f3f9 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionRetryStatus.cs @@ -0,0 +1,57 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the PRC and relevant 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.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Events; +using GameFrameX.Capability.Online.Abstractions.Idempotency; +using GameFrameX.Capability.Online.Abstractions.Scope; +using GameFrameX.Capability.Online.Match; +using GameFrameX.Foundation.Idempotency; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜投影待重试条目状态(QueryStatus 投影形态)。 +/// +public sealed class OnlineLeaderboardProjectionRetryStatus +{ + /// 获取结算结果标识。 + public string MatchResultId { get; set; } + + /// 获取对局标识。 + public string MatchId { get; set; } + + /// 获取累计投递尝试次数。 + public int Attempts { get; set; } +} diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardRateLimiter.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardRateLimiter.cs new file mode 100644 index 000000000..eaecf9a1b --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardRateLimiter.cs @@ -0,0 +1,188 @@ +// ========================================================================================== +// 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 see 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 System; +using System.Collections.Generic; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜提交限流器(防刷校验的高频半边:高频提交被拒、正常玩家不受影响)。 +/// +/// 维护约束(天花板):滑动窗口计数,按 (TenantId, AppId, PlayerId) 分桶——阈值与窗口由 +/// 覆盖;只在幂等 Execute 分支计数(重放不烧配额)。 +/// 形态对齐 OnlineMatchRateLimiter / OnlineChatRateLimiter(滑动窗口,不新增依赖); +/// 桶在窗口过期后整桶重置,进程重启即清零——限流是速率保护不是配额,可接受;多实例共享存储归运行时装配。 +/// +/// +public sealed class OnlineLeaderboardRateLimiter +{ + /// 全局读写锁。 + private readonly object _syncRoot = new(); + + /// 窗口计数桶:键 = (TenantId, AppId, PlayerId)。 + private readonly Dictionary _windows = new(); + + /// 上一次全量清扫时刻(UTC 毫秒)。 + private long _lastSweepAtTime; + + /// 窗口内允许的提交次数。 + private readonly int _maxSubmissions; + + /// 窗口时长(毫秒)。 + private readonly long _windowMilliseconds; + + /// + /// 初始化 。 + /// + /// 窗口内允许的提交次数(必须为正)。 + /// 窗口时长(秒;必须为正)。 + public OnlineLeaderboardRateLimiter(int maxSubmissions, int windowSeconds) + { + _maxSubmissions = maxSubmissions > 0 ? maxSubmissions : 1; + _windowMilliseconds = (windowSeconds > 0 ? windowSeconds : 1) * 1000L; + } + + /// + /// 清扫间隔(毫秒):取窗口时长与 60 秒的较大值,保证任何流量都会周期性推进过期桶回收。 + /// + private long SweepIntervalMilliseconds => _windowMilliseconds > 60000L ? _windowMilliseconds : 60000L; + + /// + /// 尝试为玩家获取一次提交配额(滑动窗口限流)。 + /// + /// + /// Tries to acquire one submission slot for the player within the sliding window. + /// + /// 租户 ID / The tenant id + /// 应用 ID / The app id + /// 玩家 ID / The player id + /// 当前 Unix 毫秒时间戳(0 表示取当前时间)/ The current Unix time in milliseconds (0 for now) + /// 窗口未满获取成功返回 true;已满返回 false / true if acquired within the window; false when the window is full + public bool TryAcquire(long tenantId, long appId, long playerId, long nowUnixMilliseconds = 0) + { + var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var key = tenantId + ":" + appId + ":" + playerId; + + lock (_syncRoot) + { + if (now - _lastSweepAtTime >= SweepIntervalMilliseconds) + { + SweepExpiredCore(now); + } + + if (!_windows.TryGetValue(key, out var window) || now - window.StartedAtTime >= _windowMilliseconds) + { + _windows[key] = new Window + { + StartedAtTime = now, + Count = 1, + }; + return true; + } + + if (window.Count >= _maxSubmissions) + { + return false; + } + + window.Count++; + return true; + } + } + + /// + /// 删除全部已过期的窗口桶(运维/测试可显式触发;TryAcquire 亦按清扫间隔自动触发)。 + /// + /// 当前 Unix 毫秒时间戳(0 表示取当前时间)/ The current Unix time in milliseconds (0 for now) + /// 本次删除的桶数量 / The number of expired buckets removed + public int SweepExpired(long nowUnixMilliseconds = 0) + { + var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + + lock (_syncRoot) + { + return SweepExpiredCore(now); + } + } + + /// + /// 锁内全量清扫过期桶(调用方必须已持有 )。 + /// + /// 当前时刻(UTC 毫秒)。 + /// 本次删除的桶数量。 + private int SweepExpiredCore(long now) + { + _lastSweepAtTime = now; + List expiredKeys = null; + foreach (var pair in _windows) + { + if (now - pair.Value.StartedAtTime >= _windowMilliseconds) + { + (expiredKeys ?? (expiredKeys = new List())).Add(pair.Key); + } + } + + if (expiredKeys == null) + { + return 0; + } + + for (var index = 0; index < expiredKeys.Count; index++) + { + _windows.Remove(expiredKeys[index]); + } + + return expiredKeys.Count; + } + + /// + /// 清空全部窗口(测试与运维重置用)。 + /// + public void Reset() + { + lock (_syncRoot) + { + _windows.Clear(); + } + } + + + /// + /// 滑动窗口计数桶。 + /// + private sealed class Window + { + /// 获取或设置窗口起始时刻(UTC 毫秒)。 + public long StartedAtTime { get; set; } + + /// 获取或设置窗口内已计数。 + public int Count { get; set; } + } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardResultProjector.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardResultProjector.cs new file mode 100644 index 000000000..52dda6631 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardResultProjector.cs @@ -0,0 +1,244 @@ +// ========================================================================================== +// 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 see 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 System; +using System.Globalization; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Idempotency; +using GameFrameX.Capability.Online.Match; +using GameFrameX.Capability.Online.Abstractions.Scope; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 可信结果写榜投影器(排行榜只接受服务端可信事件,客户端分数提交被拒绝)。 +/// +/// 维护约束(红线): +/// (1) **载荷零信任**——结算结果只从 (结算唯一落定点)按 +/// (TenantId, AppId, MatchId) 读取,且核对调用方传入的 MatchResultId 与存储值一致;本类型不接受 +/// 任何调用方直接携带分数 / 结果载荷的入口(伪造标识 → ResourceNotFound,篡改载荷 → RiskControlRejected); +/// (2) **写入幂等**——复用 ,键确定性派生 +/// lb-{MatchResultId}-{LeaderboardId}-{PlayerId}(沿用「业务单号由结果标识派生」的既有约定), +/// 同结果事件重复投递只计一次;幂等记录过期后的重投残留与资产域同款; +/// (3) 逐玩家失败隔离——防刷 / 限流 / 幂等冲突只影响该玩家,不阻塞同结果其余玩家。 +/// +/// +public sealed class OnlineLeaderboardResultProjector +{ + /// 对局结算结果存储(可信事实唯一来源)。 + private readonly IOnlineMatchResultStore _matchResultStore; + + /// 排行榜服务(榜单解析 + 可信写入)。 + private readonly OnlineLeaderboardService _leaderboardService; + + /// 幂等服务。 + private readonly OnlineIdempotencyService _idempotencyService; + + /// + /// 初始化 。 + /// + /// 对局结算结果存储。 + /// 排行榜服务。 + /// 幂等服务。 + public OnlineLeaderboardResultProjector(IOnlineMatchResultStore matchResultStore, OnlineLeaderboardService leaderboardService, OnlineIdempotencyService idempotencyService) + { + _matchResultStore = matchResultStore ?? throw new ArgumentNullException(nameof(matchResultStore)); + _leaderboardService = leaderboardService ?? throw new ArgumentNullException(nameof(leaderboardService)); + _idempotencyService = idempotencyService ?? throw new ArgumentNullException(nameof(idempotencyService)); + } + + /// + /// 将一局已结算结果投影到目标榜单(幂等;逐玩家失败隔离)。 + /// + /// 生效作用域(榜单与结果的 TenantId / AppId 以此为准)。 + /// 目标榜单标识。 + /// 对局标识(据此从结算存储读取结果)。 + /// 调用方持有的结果标识(与存储值核对,防伪造载荷)。 + /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 + /// 取消令牌。 + /// 投影回执(首次落榜数 / 回放数 / 逐玩家失败明细);失败返回对应错误码。 + public async Task> ProjectAsync(OnlineScope scope, string leaderboardId, string matchId, string expectedMatchResultId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + + if (string.IsNullOrEmpty(leaderboardId)) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识不能为空"); + } + + if (string.IsNullOrEmpty(matchId)) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "对局标识不能为空"); + } + + if (string.IsNullOrEmpty(expectedMatchResultId)) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "结果标识不能为空"); + } + + var boardResult = await _leaderboardService.ResolveBoardAsync(scope, leaderboardId, cancellationToken).ConfigureAwait(false); + if (!boardResult.IsSuccess) + { + return OnlineResult.Fail(boardResult.Code, boardResult.Message); + } + + var board = boardResult.Data; + var stored = await _matchResultStore.FindByMatchAsync(scope.TenantId, scope.AppId, matchId, cancellationToken).ConfigureAwait(false); + if (stored == null) + { + return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "对局结果不存在或未结算"); + } + + if (!string.Equals(stored.MatchResultId, expectedMatchResultId, StringComparison.Ordinal)) + { + return OnlineResult.Fail(OnlineErrorCode.RiskControlRejected, "结果标识与结算事实不一致"); + } + + var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var outcome = new OnlineLeaderboardProjectionOutcome + { + MatchResultId = stored.MatchResultId, + LeaderboardId = leaderboardId, + }; + + if (stored.Entries == null) + { + return OnlineResult.Ok(outcome); + } + + foreach (var entry in stored.Entries) + { + if (entry == null) + { + continue; + } + + await ProjectEntryAsync(board, stored, entry, now, outcome, cancellationToken).ConfigureAwait(false); + } + + return OnlineResult.Ok(outcome); + } + + /// + /// 投影单玩家条目:幂等判定 → 首次执行写入 → 落定幂等记录;失败逐玩家隔离。 + /// + /// 目标榜单。 + /// 可信结算结果。 + /// 结果条目。 + /// 当前时刻(UTC 毫秒)。 + /// 累计回执。 + /// 取消令牌。 + /// 完成通知。 + private async Task ProjectEntryAsync(OnlineLeaderboard board, OnlineMatchResult result, OnlineMatchResultEntry entry, long now, OnlineLeaderboardProjectionOutcome outcome, CancellationToken cancellationToken) + { + var playerScope = new OnlineScope(result.TenantId, result.AppId, result.ServerId, entry.PlayerId); + var idempotencyKey = BuildIdempotencyKey(result.MatchResultId, board.LeaderboardId, entry.PlayerId); + var decision = await _idempotencyService.BeginAsync(playerScope, idempotencyKey, BuildCanonicalRequestText(result.MatchResultId, board.LeaderboardId, entry.PlayerId, entry.Score), true, cancellationToken).ConfigureAwait(false); + + if (decision.Kind == OnlineIdempotencyOutcomeKind.Replay) + { + outcome.ReplayCount++; + return; + } + + if (!decision.CanExecute) + { + outcome.FailedPlayers.Add(new OnlineLeaderboardProjectionFailure + { + PlayerId = entry.PlayerId, + Code = decision.ErrorCode, + Message = "幂等判定未放行:" + decision.Kind, + }); + return; + } + + var write = await _leaderboardService.ApplyTrustedScoreAsync(board, new OnlineLeaderboardScoreSubmission + { + PlayerId = entry.PlayerId, + IncomingScore = entry.Score, + SourceKind = OnlineLeaderboardScoreSource.MatchResult, + SourceMatchResultId = result.MatchResultId, + SubmittedTime = now, + }, now, cancellationToken).ConfigureAwait(false); + + if (write.IsSuccess) + { + await _idempotencyService.CompleteAsync(playerScope, idempotencyKey, Encoding.UTF8.GetBytes(write.Entry.Score.ToString(CultureInfo.InvariantCulture)), true, cancellationToken).ConfigureAwait(false); + outcome.AppliedCount++; + return; + } + + await _idempotencyService.FailAsync(playerScope, idempotencyKey, true, cancellationToken).ConfigureAwait(false); + outcome.FailedPlayers.Add(new OnlineLeaderboardProjectionFailure + { + PlayerId = entry.PlayerId, + Code = write.Code, + Message = write.Message, + }); + } + + /// + /// 构造确定性幂等键(同结果同榜同玩家重投同值)。 + /// + /// 结算结果标识。 + /// 榜单标识。 + /// 玩家标识。 + /// 幂等键。 + private static string BuildIdempotencyKey(string matchResultId, string leaderboardId, long playerId) + { + return string.Concat("lb-", matchResultId, "-", leaderboardId, "-", playerId.ToString(CultureInfo.InvariantCulture)); + } + + /// + /// 构造规范化请求文本(同一业务意图的重复投递必须产生相同文本,幂等摘要据此判定冲突)。 + /// + /// 结算结果标识。 + /// 榜单标识。 + /// 玩家标识。 + /// 本笔分数。 + /// 规范化请求文本。 + private static string BuildCanonicalRequestText(string matchResultId, string leaderboardId, long playerId, long score) + { + return string.Concat( + "leaderboard-score|", + matchResultId, + "|", + leaderboardId, + "|", + playerId.ToString(CultureInfo.InvariantCulture), + "|", + score.ToString(CultureInfo.InvariantCulture)); + } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreSource.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreSource.cs new file mode 100644 index 000000000..e006e5dc3 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreSource.cs @@ -0,0 +1,45 @@ +// ========================================================================================== +// 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 see 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜分数来源(「分数来源」约束:每笔榜上分数必须可追溯到可信产生方)。 +/// +/// 维护约束(红线):第一版唯一合法来源是对局结算结果(Online.Match.Settled 可信事件链路); +/// 客户端直接提交的分数没有任何来源枚举值可承载——枚举即白名单,新增来源(如运营调整)必须先扩枚举并评审。 +/// +/// +public enum OnlineLeaderboardScoreSource +{ + /// + /// 权威对局结算结果(分数来自 OnlineMatchResultEntry.Score,经可信写入链路落榜)。 + /// + MatchResult = 1, +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreSubmission.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreSubmission.cs new file mode 100644 index 000000000..0f4d53bef --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreSubmission.cs @@ -0,0 +1,66 @@ +// ========================================================================================== +// 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 see 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜分数提交(单玩家单笔;只由可信写入链路构造,不暴露给客户端)。 +/// +/// 维护约束(红线):本类型是存储临界区的唯一写入载体——分数与来源由投影器从结算结果逐字段抄录, +/// 调用链上任何一层都不接受外部传入的「裸分数」; 仍须过防刷上限校验 +/// (可信链路也可能被上游缺陷 / 被攻陷结点灌入异常分数,防线不能省)。 +/// +/// +public sealed class OnlineLeaderboardScoreSubmission +{ + /// + /// 获取或设置玩家标识。 + /// + public long PlayerId { get; set; } + + /// + /// 获取或设置本笔提交分数(进入累计策略裁决前的原始值)。 + /// + public long IncomingScore { get; set; } + + /// + /// 获取或设置分数来源。 + /// + public OnlineLeaderboardScoreSource SourceKind { get; set; } + + /// + /// 获取或设置来源结算结果标识(追溯键)。 + /// + public string SourceMatchResultId { get; set; } + + /// + /// 获取或设置提交时刻(UTC 毫秒;写入条目的 LastUpdateTime)。 + /// + public long SubmittedTime { get; set; } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreUpdatePolicy.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreUpdatePolicy.cs new file mode 100644 index 000000000..2d8f926ea --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardScoreUpdatePolicy.cs @@ -0,0 +1,56 @@ +// ========================================================================================== +// 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 see 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜分数累计策略(「分数来源」语义的一部分:同玩家多次可信写入如何合并为榜上分数)。 +/// +/// 维护约束(红线):策略裁决必须发生在存储临界区内(InMemoryOnlineLeaderboardStore.ApplySubmissionAsync), +/// 与条目落档同一临界区,保证并发投递下「读旧值 → 算新值 → 写入」不被交错撕裂; +/// 服务层不得先读后写绕开该临界区。 +/// +/// +public enum OnlineLeaderboardScoreUpdatePolicy +{ + /// + /// 保留按榜向更优的分数(Descending 榜取更大值,Ascending 榜取更小值;首笔写入直接生效)。 + /// + Best = 0, + + /// + /// 累加全部写入分数(赛季积分类榜单;幂等重放不计入——重放在幂等层被拦截,不进入本策略)。 + /// + Sum = 1, + + /// + /// 以最近一次写入覆盖(连胜 / 当前段位类榜单)。 + /// + Latest = 2, +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardService.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardService.cs new file mode 100644 index 000000000..87fd6d486 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardService.cs @@ -0,0 +1,579 @@ +// ========================================================================================== +// 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 see 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 System; +using System.Collections.Generic; +using System.Globalization; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Events; +using GameFrameX.Capability.Online.Abstractions.Scope; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜服务(创建 / Top N / 玩家附近排名 / 游标分页 / 读缓存;查询侧作用域反预言)。 +/// +/// 维护约束(红线): +/// (1) **本服务没有任何接受「裸分数」的公开提交 API**——分数写入只经内部 +/// (由可信写入链路 调用), +/// 客户端无入口可刷分; +/// (2) 跨 App / 跨租户读写与「榜单不存在」同构返回 ResourceNotFound(反预言,不泄露榜单存在性); +/// (3) Top N 读缓存 TTL + 写失效——任何成功写榜立即失效该榜缓存,缓存只影响读延迟不影响正确性。 +/// +/// +public sealed class OnlineLeaderboardService +{ + /// 排行榜存储。 + private readonly IOnlineLeaderboardStore _store; + + /// 组件选项。 + private readonly OnlineLeaderboardOptions _options; + + /// 事件发布器(可空)。 + private readonly IOnlineEventPublisher _eventPublisher; + + /// 提交限流器(防刷高频半边)。 + private readonly OnlineLeaderboardRateLimiter _rateLimiter; + + /// 读缓存与缓存锁。 + private readonly object _cacheSyncRoot = new(); + + /// Top N 快照读缓存:键 = 榜单存储键。 + private readonly Dictionary _snapshotCache = new(); + + /// + /// 初始化 。 + /// + /// 排行榜存储。 + /// 组件选项(必填;默认值唯一来源 = 字段初始值)。 + /// 事件发布器(可空;未接线时不发事件)。 + public OnlineLeaderboardService(IOnlineLeaderboardStore store, OnlineLeaderboardOptions options, IOnlineEventPublisher eventPublisher = null) + { + _store = store ?? throw new ArgumentNullException(nameof(store)); + _options = options ?? throw new ArgumentNullException(nameof(options)); + _eventPublisher = eventPublisher; + _rateLimiter = new OnlineLeaderboardRateLimiter(_options.RateLimitMaxSubmissions, _options.RateLimitWindowSeconds); + } + + /// + /// 创建榜单(同作用域同名榜单已存在时拒绝;创建成功发布 Online.Leaderboard.Created 事件)。 + /// + /// 生效作用域(鉴权上下文产物;榜单归属取其 TenantId / AppId)。 + /// 创建请求。 + /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 + /// 取消令牌。 + /// 创建后的榜单定义;失败返回对应错误码。 + public async Task> CreateAsync(OnlineScope scope, OnlineLeaderboardCreateRequest request, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + + if (request == null) + { + throw new ArgumentNullException(nameof(request)); + } + + if (string.IsNullOrEmpty(request.LeaderboardId)) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识不能为空"); + } + + if (request.SortOrder != OnlineLeaderboardSortOrder.Descending && request.SortOrder != OnlineLeaderboardSortOrder.Ascending) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "排序方向取值非法"); + } + + if (request.ScoreUpdatePolicy != OnlineLeaderboardScoreUpdatePolicy.Best && request.ScoreUpdatePolicy != OnlineLeaderboardScoreUpdatePolicy.Sum && request.ScoreUpdatePolicy != OnlineLeaderboardScoreUpdatePolicy.Latest) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "累计策略取值非法"); + } + + if (request.MaxScorePerSubmission < 0) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "单次分数上限不得为负"); + } + + var board = new OnlineLeaderboard + { + LeaderboardId = request.LeaderboardId, + TenantId = scope.TenantId, + AppId = scope.AppId, + SortOrder = request.SortOrder, + ScoreUpdatePolicy = request.ScoreUpdatePolicy, + MaxScorePerSubmission = request.MaxScorePerSubmission, + CreatedTime = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + }; + + var created = await _store.CreateAsync(board, cancellationToken).ConfigureAwait(false); + if (created == null) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识已存在"); + } + + await PublishAsync(OnlineLeaderboardEvents.CreateLeaderboardCreated(created.TenantId, created.AppId, created.LeaderboardId, created.SortOrder.ToString(), created.ScoreUpdatePolicy.ToString(), created.CreatedTime), cancellationToken).ConfigureAwait(false); + return OnlineResult.Ok(created); + } + + /// + /// 查询 Top N(带 keyset 游标分页;游标由本服务编码,客户端不透明)。 + /// + /// 生效作用域(跨 App / 跨租户与不存在同构拒绝)。 + /// Top N 查询载荷。 + /// 取消令牌。 + /// 本页条目与后继游标;失败返回对应错误码。 + public async Task> GetTopAsync(OnlineScope scope, OnlineLeaderboardTopQuery query, CancellationToken cancellationToken = default) + { + if (query == null) + { + throw new ArgumentNullException(nameof(query)); + } + + var leaderboardId = query.LeaderboardId; + var count = query.Count; + var cursor = query.Cursor; + var nowUnixMilliseconds = query.NowUnixMilliseconds; + if (count <= 0) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "条目数必须为正"); + } + + var boardResult = await ResolveBoardAsync(scope, leaderboardId, cancellationToken).ConfigureAwait(false); + if (!boardResult.IsSuccess) + { + return OnlineResult.Fail(boardResult.Code, boardResult.Message); + } + + var board = boardResult.Data; + OnlineLeaderboardEntry cursorKey = null; + if (!string.IsNullOrEmpty(cursor)) + { + cursorKey = DecodeCursor(cursor); + if (cursorKey == null) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "分页游标非法"); + } + } + + var snapshot = await GetSnapshotAsync(board, nowUnixMilliseconds, cancellationToken).ConfigureAwait(false); + var pageSize = _options.MaxPageSize > 0 ? Math.Min(count, _options.MaxPageSize) : count; + var startIndex = cursorKey == null ? 0 : FindIndexAfter(snapshot, board.SortOrder, cursorKey); + var page = new OnlineLeaderboardPage + { + Entries = new List(), + TotalCount = snapshot.Count, + }; + + var index = startIndex; + while (index < snapshot.Count && page.Entries.Count < pageSize) + { + page.Entries.Add(new OnlineLeaderboardEntryView + { + Rank = index + 1, + Entry = snapshot[index].Copy(), + }); + index++; + } + + var hasMore = index < snapshot.Count; + page.Cursor = hasMore && page.Entries.Count > 0 + ? new OnlinePageCursor(EncodeCursor(page.Entries[page.Entries.Count - 1].Entry), true) + : new OnlinePageCursor(string.Empty, false); + return OnlineResult.Ok(page); + } + + /// + /// 查询玩家名次(未上榜返回 ResourceNotFound)。 + /// + /// 生效作用域。 + /// 榜单标识。 + /// 玩家标识。 + /// 当前时刻(UTC 毫秒;传 0 取系统时钟)。 + /// 取消令牌。 + /// 条目与名次视图;失败返回对应错误码。 + public async Task> GetPlayerRankAsync(OnlineScope scope, string leaderboardId, long playerId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + { + var boardResult = await ResolveBoardAsync(scope, leaderboardId, cancellationToken).ConfigureAwait(false); + if (!boardResult.IsSuccess) + { + return OnlineResult.Fail(boardResult.Code, boardResult.Message); + } + + var snapshot = await GetSnapshotAsync(boardResult.Data, nowUnixMilliseconds, cancellationToken).ConfigureAwait(false); + var index = snapshot.FindIndex(entry => entry.PlayerId == playerId); + if (index < 0) + { + return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "玩家未上榜"); + } + + return OnlineResult.Ok(new OnlineLeaderboardEntryView + { + Rank = index + 1, + Entry = snapshot[index].Copy(), + }); + } + + /// + /// 查询玩家附近排名(窗口含玩家本人,边界处截断)。 + /// + /// 生效作用域。 + /// 附近排名窗口查询载荷。 + /// 取消令牌。 + /// 附近排名窗口;失败返回对应错误码。 + public async Task> GetAroundPlayerAsync(OnlineScope scope, OnlineLeaderboardAroundQuery query, CancellationToken cancellationToken = default) + { + if (query == null) + { + throw new ArgumentNullException(nameof(query)); + } + + var leaderboardId = query.LeaderboardId; + var playerId = query.PlayerId; + var before = query.Before; + var after = query.After; + var nowUnixMilliseconds = query.NowUnixMilliseconds; + if (before < 0 || after < 0) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "附近排名窗口不得为负"); + } + + var boardResult = await ResolveBoardAsync(scope, leaderboardId, cancellationToken).ConfigureAwait(false); + if (!boardResult.IsSuccess) + { + return OnlineResult.Fail(boardResult.Code, boardResult.Message); + } + + var snapshot = await GetSnapshotAsync(boardResult.Data, nowUnixMilliseconds, cancellationToken).ConfigureAwait(false); + var index = snapshot.FindIndex(entry => entry.PlayerId == playerId); + if (index < 0) + { + return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "玩家未上榜"); + } + + var view = new OnlineLeaderboardAroundView + { + PlayerId = playerId, + Rank = index + 1, + TotalCount = snapshot.Count, + Around = new List(), + }; + + var startIndex = Math.Max(0, index - before); + var endIndex = Math.Min(snapshot.Count - 1, index + after); + for (var windowIndex = startIndex; windowIndex <= endIndex; windowIndex++) + { + view.Around.Add(new OnlineLeaderboardEntryView + { + Rank = windowIndex + 1, + Entry = snapshot[windowIndex].Copy(), + }); + } + + return OnlineResult.Ok(view); + } + + /// + /// 内部:按作用域解析榜单定义(跨作用域与不存在同构返回失败 ResourceNotFound)。 + /// + /// 生效作用域。 + /// 榜单标识。 + /// 取消令牌。 + /// 榜单定义;不存在返回失败。 + internal async Task> ResolveBoardAsync(OnlineScope scope, string leaderboardId, CancellationToken cancellationToken = default) + { + if (scope == null) + { + throw new ArgumentNullException(nameof(scope)); + } + + if (string.IsNullOrEmpty(leaderboardId)) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识不能为空"); + } + + var board = await _store.FindAsync(scope.TenantId, scope.AppId, leaderboardId, cancellationToken).ConfigureAwait(false); + if (board == null) + { + return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "排行榜不存在"); + } + + return OnlineResult.Ok(board); + } + + /// + /// 内部:可信分数写入(防刷上限 + 限流 + 原子落榜 + 缓存失效 + 事件;幂等由投影器承载,本方法不重复判定)。 + /// + /// 目标榜单(调用方已解析)。 + /// 分数提交。 + /// 当前时刻(UTC 毫秒;传 0 取系统时钟)。 + /// 取消令牌。 + /// 写入回执(成功含条目与旧分数,失败含错误码)。 + internal async Task ApplyTrustedScoreAsync(OnlineLeaderboard leaderboard, OnlineLeaderboardScoreSubmission submission, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) + { + if (leaderboard == null) + { + throw new ArgumentNullException(nameof(leaderboard)); + } + + if (submission == null) + { + throw new ArgumentNullException(nameof(submission)); + } + + if (string.IsNullOrEmpty(submission.SourceMatchResultId)) + { + return Failed(OnlineErrorCode.ParameterInvalid, "分数来源结算结果标识缺失"); + } + + var maxScore = leaderboard.MaxScorePerSubmission > 0 ? leaderboard.MaxScorePerSubmission : _options.DefaultMaxScorePerSubmission; + if (maxScore > 0 && Math.Abs(submission.IncomingScore) > maxScore) + { + return Failed(OnlineErrorCode.RiskControlRejected, "分数超出合理范围,已风控拒绝"); + } + + var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + if (!_rateLimiter.TryAcquire(leaderboard.TenantId, leaderboard.AppId, submission.PlayerId, now)) + { + return Failed(OnlineErrorCode.RateLimitExceeded, "提交过于频繁,已限流"); + } + + var applied = await _store.ApplySubmissionAsync(leaderboard, submission, cancellationToken).ConfigureAwait(false); + if (applied == null) + { + // Sum 累加溢出被存储层拒绝:条目保持原值,不发事件、不失效缓存(消息承载榜单/玩家/本笔分数供观测定位;原分数以榜上条目为准)。 + return Failed(OnlineErrorCode.ParameterInvalid, string.Format(CultureInfo.InvariantCulture, "累计分数超出范围,已拒绝写入:leaderboardId={0}, playerId={1}, incomingScore={2}", leaderboard.LeaderboardId, submission.PlayerId, submission.IncomingScore)); + } + + InvalidateCache(leaderboard); + await PublishAsync(OnlineLeaderboardEvents.CreateScoreUpdated(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId, submission.PlayerId, applied.OldScore, applied.Entry.Score, submission.SourceMatchResultId, applied.Entry.LastUpdateTime), cancellationToken).ConfigureAwait(false); + + return new OnlineLeaderboardWriteOutcome + { + IsSuccess = true, + Entry = applied.Entry, + OldScore = applied.OldScore, + }; + } + + /// + /// 内部:读取榜单全序条目(赛季结束取快照专用;**绕过读缓存直读存储**——快照必须是重置前的最新事实, + /// 取到缓存旧值会漏掉刚刚落榜的成绩)。 + /// + /// 目标榜单(调用方已解析)。 + /// 取消令牌。 + /// 全序条目副本。 + internal Task> ListOrderedEntriesForSeasonAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default) + { + if (leaderboard == null) + { + throw new ArgumentNullException(nameof(leaderboard)); + } + + return _store.ListOrderedEntriesAsync(leaderboard, cancellationToken); + } + + /// + /// 内部:赛季重置清空榜单条目(CAS;成功后**立即失效读缓存**——否则重置后 TTL 内仍会返回旧榜)。 + /// + /// 目标榜单(调用方已解析)。 + /// 调用方持有的全序条目快照(CAS 判据)。 + /// 取消令牌。 + /// 清空成功返回 true;榜上条目已变化返回 false。 + internal async Task TryResetForSeasonAsync(OnlineLeaderboard leaderboard, IReadOnlyList expectedEntries, CancellationToken cancellationToken = default) + { + if (leaderboard == null) + { + throw new ArgumentNullException(nameof(leaderboard)); + } + + var reset = await _store.TryResetAsync(leaderboard, expectedEntries, cancellationToken).ConfigureAwait(false); + if (reset) + { + InvalidateCache(leaderboard); + } + + return reset; + } + + /// + /// 构造失败回执。 + /// + /// 错误码。 + /// 原因。 + /// 失败回执。 + private static OnlineLeaderboardWriteOutcome Failed(OnlineErrorCode code, string message) + { + return new OnlineLeaderboardWriteOutcome + { + IsSuccess = false, + Code = code, + Message = message, + }; + } + + /// + /// 读取榜单全序快照(缓存命中直接返回;未启用缓存或过期时从存储重建并回填缓存)。 + /// + /// 榜单定义。 + /// 当前时刻(UTC 毫秒;缓存 TTL 判定)。 + /// 取消令牌。 + /// 全序快照(服务私有,调用方不得改写)。 + private async Task> GetSnapshotAsync(OnlineLeaderboard leaderboard, long nowUnixMilliseconds, CancellationToken cancellationToken) + { + var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var cacheKey = leaderboard.TenantId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.AppId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.LeaderboardId; + if (_options.CacheEnabled) + { + lock (_cacheSyncRoot) + { + if (_snapshotCache.TryGetValue(cacheKey, out var slot) && slot.ExpiresAtTime > now) + { + return slot.Snapshot; + } + } + } + + var snapshot = await _store.ListOrderedEntriesAsync(leaderboard, cancellationToken).ConfigureAwait(false); + if (_options.CacheEnabled && _options.CacheTtlSeconds > 0) + { + lock (_cacheSyncRoot) + { + _snapshotCache[cacheKey] = new CacheSlot + { + Snapshot = snapshot, + ExpiresAtTime = now + _options.CacheTtlSeconds * 1000L, + }; + } + } + + return snapshot; + } + + /// + /// 失效榜单读缓存(任何成功写榜后调用)。 + /// + /// 榜单定义。 + private void InvalidateCache(OnlineLeaderboard leaderboard) + { + var cacheKey = leaderboard.TenantId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.AppId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.LeaderboardId; + lock (_cacheSyncRoot) + { + _snapshotCache.Remove(cacheKey); + } + } + + /// + /// 编码 keyset 游标(稳定排序键三元组;客户端视为不透明令牌)。 + /// + /// 游标锚点条目。 + /// 游标字符串。 + private static string EncodeCursor(OnlineLeaderboardEntry entry) + { + return string.Concat( + entry.Score.ToString(CultureInfo.InvariantCulture), + ":", + entry.LastUpdateTime.ToString(CultureInfo.InvariantCulture), + ":", + entry.PlayerId.ToString(CultureInfo.InvariantCulture)); + } + + /// + /// 解码 keyset 游标为伪条目(仅稳定排序键三字段有效)。 + /// + /// 游标字符串。 + /// 伪条目;无法解析返回 null。 + private static OnlineLeaderboardEntry DecodeCursor(string cursor) + { + var parts = cursor.Split(':'); + if (parts.Length != 3) + { + return null; + } + + if (!long.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var score) + || !long.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var time) + || !long.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var playerId)) + { + return null; + } + + return new OnlineLeaderboardEntry { PlayerId = playerId, Score = score, LastUpdateTime = time, }; + } + + /// + /// 在全序快照中定位「严格晚于游标键」的首个下标(keyset 语义:翻页期间新增不重不漏)。 + /// + /// 全序快照。 + /// 排序方向。 + /// 游标伪条目。 + /// 起始下标;游标键晚于全部条目时为快照长度。 + private static int FindIndexAfter(List snapshot, OnlineLeaderboardSortOrder sortOrder, OnlineLeaderboardEntry cursorKey) + { + for (var index = 0; index < snapshot.Count; index++) + { + if (OnlineLeaderboardOrdering.Compare(sortOrder, snapshot[index], cursorKey) > 0) + { + return index; + } + } + + return snapshot.Count; + } + + /// + /// 发布事件(发布器可空;发布失败不改变已落定的写入事实)。 + /// + /// 待发布事件。 + /// 取消令牌。 + /// 完成通知。 + private async Task PublishAsync(OnlineEvent onlineEvent, CancellationToken cancellationToken) + { + if (_eventPublisher == null) + { + return; + } + + await _eventPublisher.PublishAsync(onlineEvent, cancellationToken).ConfigureAwait(false); + } + + /// + /// 读缓存槽(榜单全序快照 + 绝对过期时刻)。 + /// + private sealed class CacheSlot + { + /// 获取或设置全序条目快照。 + public List Snapshot { get; set; } + + /// 获取或设置过期时刻(UTC 毫秒)。 + public long ExpiresAtTime { get; set; } + } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardSortOrder.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardSortOrder.cs new file mode 100644 index 000000000..e800554ff --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardSortOrder.cs @@ -0,0 +1,50 @@ +// ========================================================================================== +// 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 see 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 排行榜排序方向(第一版个人榜支持高分优先与低分优先两种方向)。 +/// +/// 维护约束:方向在榜单创建时固化,写入侧(「更好分数」的判定)与查询侧(Top N / 附近排名 / 分页) +/// 必须使用同一方向语义(统一经 比较),禁止两处各写一份判定。 +/// +/// +public enum OnlineLeaderboardSortOrder +{ + /// + /// 分数高者排名靠前(竞技得分榜默认)。 + /// + Descending = 0, + + /// + /// 分数低者排名靠前(用时榜 / 步数榜等「越小越好」语义)。 + /// + Ascending = 1, +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardTopQuery.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardTopQuery.cs new file mode 100644 index 000000000..ff243cf23 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardTopQuery.cs @@ -0,0 +1,61 @@ +// ========================================================================================== +// 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 related 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 see the LICENSE file in the root directory of the source code. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// Top N 查询载荷( 除作用域外的全部查询维度; +/// keyset 游标由服务编码,客户端不透明)。 +/// +public sealed class OnlineLeaderboardTopQuery +{ + /// + /// 获取或设置榜单标识。 + /// + /// Gets or sets the leaderboard id. + public string LeaderboardId { get; init; } + + /// + /// 获取或设置本页条目数(超出 MaxPageSize 按上限截断)。 + /// + /// Gets or sets the page size (clamped to MaxPageSize). + public int Count { get; init; } + + /// + /// 获取或设置上一页返回的游标(首页传 null 或空串)。 + /// + /// Gets or sets the cursor returned by the previous page (null or empty for the first page). + public string Cursor { get; init; } + + /// + /// 获取或设置当前时刻(UTC 毫秒;传 0 取系统时钟,缓存 TTL 判定用)。 + /// + /// Gets or sets the current time (UTC milliseconds; 0 = system clock; used for cache TTL checks). + public long NowUnixMilliseconds { get; init; } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardWriteOutcome.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardWriteOutcome.cs new file mode 100644 index 000000000..d94f36c0c --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardWriteOutcome.cs @@ -0,0 +1,65 @@ +// ========================================================================================== +// 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 see 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! +// 本项目组织与贡献者概不承担。 +// 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.Capability.Online.Abstractions.Contracts; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// 可信写入单玩家执行回执(服务内部类型:投影器在幂等 Execute 分支内调用写入,承载成功条目或拒绝码)。 +/// +/// 维护约束:失败语义与错误码段位固定(分数越界 → RiskControlRejected;高频 → RateLimitExceeded), +/// 调用方(投影器)据此决定幂等记录落 Fail 并逐玩家隔离;本类型不进公共 API 面。 +/// +/// +internal sealed class OnlineLeaderboardWriteOutcome +{ + /// + /// 获取或设置是否成功落榜。 + /// + public bool IsSuccess { get; set; } + + /// + /// 获取或设置失败错误码(失败时有效)。 + /// + public OnlineErrorCode Code { get; set; } + + /// + /// 获取或设置失败原因(失败时有效)。 + /// + public string Message { get; set; } + + /// + /// 获取或设置落榜后的条目副本(成功时有效)。 + /// + public OnlineLeaderboardEntry Entry { get; set; } + + /// + /// 获取或设置落榜前分数(成功时有效;事件载荷的 OldScore)。 + /// + public long OldScore { get; set; } +} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineMatchSettledLeaderboardProjector.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineMatchSettledLeaderboardProjector.cs new file mode 100644 index 000000000..86031ada5 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineMatchSettledLeaderboardProjector.cs @@ -0,0 +1,379 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the PRC and relevant 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.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Events; +using GameFrameX.Capability.Online.Abstractions.Idempotency; +using GameFrameX.Capability.Online.Abstractions.Scope; +using GameFrameX.Capability.Online.Match; +using GameFrameX.Foundation.Idempotency; + +namespace GameFrameX.Capability.Online.Competition.Leaderboard; + +/// +/// Match.Settled → 排行榜投影订阅体:消费对局结算完成事件,经 +/// (可信源 result store + MatchResultId 核对 + 幂等键) +/// 投影到预置榜单;失败进待重试表,由 tick job leaderboard-projection-retry 逐轮重投。 +/// +/// 维护约束(红线): +/// (1) **双层去重**——(EventId 去重,Operations 审计桥先例)挡同事件重投, +/// 投影器幂等键(lb-{MatchResultId}-{LeaderboardId}-{PlayerId})挡不同 EventId 同结果的重复投递; +/// (2) **异常不外抛**——订阅体异常吞掉记录(先例:Operations 审计桥「投影异常不得阻断业务事件分发」), +/// 失败只进待重试表经 可观测;不可解析载荷无从重投,直接丢弃; +/// (3) **终态裁决**——重投时结果事实已不存在(store 清理)视作不可投影终态,移除待重试条目。 +/// +/// +public sealed class OnlineMatchSettledLeaderboardProjector +{ + /// 可信结果写榜投影器(真实投影执行体)。 + private readonly OnlineLeaderboardResultProjector _projector; + + /// 对局结算结果存储(终态裁决用)。 + private readonly IOnlineMatchResultStore _matchResultStore; + + /// 目标榜单标识。 + private readonly string _leaderboardId; + + /// EventId 去重消费者(同事件重投短路)。 + private readonly OnlineEventConsumer _consumer; + + /// 待重试表与并发锁。 + private readonly object _pendingLock = new(); + + /// 待重试条目(键 = MatchResultId,去重)。 + private readonly Dictionary _pending = new(StringComparer.Ordinal); + + /// + /// 初始化 。 + /// + /// 对局结算结果存储(可信事实唯一来源)。 + /// 排行榜服务。 + /// 幂等服务。 + /// 目标榜单标识。 + public OnlineMatchSettledLeaderboardProjector(IOnlineMatchResultStore matchResultStore, OnlineLeaderboardService leaderboardService, OnlineIdempotencyService idempotencyService, string leaderboardId) + { + _matchResultStore = matchResultStore ?? throw new ArgumentNullException(nameof(matchResultStore)); + _projector = new OnlineLeaderboardResultProjector(matchResultStore, leaderboardService, idempotencyService); + _leaderboardId = leaderboardId ?? throw new ArgumentNullException(nameof(leaderboardId)); + _consumer = new OnlineEventConsumer(new InMemoryEventDeduplicator()); + } + + /// + /// 订阅体入口:解析 Match.Settled 载荷并投影到目标榜单;失败(榜单缺失 / 结果缺失 / 异常)记待重试, + /// 异常不向订阅方抛(吞掉记录)。 + /// + /// Online 事件(应为 Match.Settled)。 + /// 完成通知。 + public async Task HandleEventAsync(OnlineEvent onlineEvent) + { + MatchSettledPayload payload; + OnlineEvent sourceEvent = onlineEvent; + try + { + if (onlineEvent == null || onlineEvent.EventType != OnlineMatchRuntimeEvents.MatchSettled) + { + return; + } + + if (!_consumer.TryConsume(onlineEvent)) + { + return; + } + + payload = DeserializePayload(onlineEvent.Payload); + if (payload == null || string.IsNullOrEmpty(payload.MatchResultId) || string.IsNullOrEmpty(payload.MatchId)) + { + // 载荷不可解析 / 缺标识:无从重投,直接丢弃(不记待重试)。 + return; + } + } + catch (Exception) + { + // 去重 / 解析段异常无从定位业务标识,吞掉不外抛、不记待重试。 + return; + } + + try + { + // 榜单级作用域(PlayerId=0):投影器内部逐玩家以结算事实重建 scope。 + var scope = new OnlineScope(sourceEvent.TenantId, sourceEvent.AppId, sourceEvent.ServerId, 0); + var projected = await _projector.ProjectAsync(scope, _leaderboardId, payload.MatchId, payload.MatchResultId).ConfigureAwait(false); + if (!projected.IsSuccess) + { + RecordPending(sourceEvent, payload); + } + } + catch (Exception) + { + // 投影段异常同样记待重试(重投幂等键保证不双计);不向订阅方抛。 + RecordPending(sourceEvent, payload); + } + } + + /// + /// 重投待重试条目(幂等键保证不双计):成功或结果事实已不存在(不可投影终态)移除;失败 Attempts++ 保留。 + /// + /// 取消令牌。 + /// 完成通知。 + + public async Task RetryPendingAsync(CancellationToken cancellationToken) + { + PendingProjection[] snapshot; + lock (_pendingLock) + { + if (_pending.Count == 0) + { + return; + } + + snapshot = new PendingProjection[_pending.Count]; + _pending.Values.CopyTo(snapshot, 0); + } + + foreach (var entry in snapshot) + { + var stored = await _matchResultStore.FindByMatchAsync(entry.TenantId, entry.AppId, entry.MatchId, cancellationToken).ConfigureAwait(false); + if (stored == null) + { + // 结果已被清理:不可投影终态,移除。 + RemovePending(entry.MatchResultId); + continue; + } + + var scope = new OnlineScope(entry.TenantId, entry.AppId, entry.ServerId, 0); + var projected = await _projector.ProjectAsync(scope, _leaderboardId, entry.MatchId, entry.MatchResultId, 0, cancellationToken).ConfigureAwait(false); + if (projected.IsSuccess) + { + RemovePending(entry.MatchResultId); + } + else + { + BumpPending(entry.MatchResultId); + } + } + } + + /// + /// 查询待重试条目快照(admin 可观测面;条目 = MatchResultId / MatchId / Attempts)。 + /// + /// 待重试条目副本。 + public IReadOnlyList QueryStatus() + { + lock (_pendingLock) + { + var items = new List(_pending.Count); + foreach (var entry in _pending.Values) + { + items.Add(new OnlineLeaderboardProjectionRetryStatus + { + MatchResultId = entry.MatchResultId, + MatchId = entry.MatchId, + Attempts = entry.Attempts, + }); + } + + return items; + } + } + + /// + /// 反序列化结算事件载荷(字段名与 MatchSettledPayload 线缆形态一致)。 + /// + /// UTF8 JSON 载荷。 + /// 载荷;不可解析返回 null。 + private static MatchSettledPayload DeserializePayload(ReadOnlyMemory payload) + { + if (payload.IsEmpty) + { + return null; + } + + try + { + return JsonSerializer.Deserialize(payload.Span); + } + catch (JsonException) + { + return null; + } + } + + /// + /// 记录待重试条目(按 MatchResultId 去重;重复失败 Attempts 不衰减)。 + /// + /// 来源事件(作用域三元组)。 + /// 已解析载荷。 + private void RecordPending(OnlineEvent onlineEvent, MatchSettledPayload payload) + { + lock (_pendingLock) + { + if (_pending.TryGetValue(payload.MatchResultId, out var existing)) + { + existing.Attempts++; + return; + } + + _pending[payload.MatchResultId] = new PendingProjection + { + MatchResultId = payload.MatchResultId, + MatchId = payload.MatchId, + TenantId = onlineEvent.TenantId, + AppId = onlineEvent.AppId, + ServerId = onlineEvent.ServerId, + Attempts = 1, + }; + } + } + + /// + /// 移除待重试条目。 + /// + /// 结果标识。 + private void RemovePending(string matchResultId) + { + lock (_pendingLock) + { + _pending.Remove(matchResultId); + } + } + + /// + /// 重投失败:Attempts++ 保留。 + /// + /// 结果标识。 + private void BumpPending(string matchResultId) + { + lock (_pendingLock) + { + if (_pending.TryGetValue(matchResultId, out var existing)) + { + existing.Attempts++; + } + } + } + + /// + /// 反序列化结算事件载荷(字段名与 MatchSettledPayload 线缆形态一致)。 + /// + /// UTF8 JSON 载荷。 + /// 载荷;不可解析返回 null。 + private static MatchSettledPayload DeserializePayload(byte[] payload) + { + if (payload == null || payload.Length == 0) + { + return null; + } + + try + { + return JsonSerializer.Deserialize(payload); + } + catch (JsonException) + { + return null; + } + } + + /// + /// 结算事件负载(私有 DTO,字段名与 OnlineMatchRuntimeEvents 的 MatchSettledPayload 一致)。 + /// + private sealed class MatchSettledPayload + { + /// 结果标识(幂等边界)。 + public string MatchResultId { get; set; } + + /// 对局标识。 + public string MatchId { get; set; } + + /// 玩法模式。 + public int Mode { get; set; } + + /// 区域。 + public int Region { get; set; } + + /// 结束方式名。 + public string Outcome { get; set; } + + /// 结算时刻(UTC 毫秒)。 + public long SettledTime { get; set; } + + /// 玩家条目集合。 + public List Entries { get; set; } + } + + /// + /// 结算事件单玩家条目负载。 + /// + private sealed class MatchSettledEntryPayload + { + /// 玩家标识。 + public long PlayerId { get; set; } + + /// 名次。 + public int Rank { get; set; } + + /// 是否胜方。 + public bool IsWinner { get; set; } + + /// 玩法得分。 + public long Score { get; set; } + + /// 奖励条目数。 + public int RewardCount { get; set; } + } + + /// + /// 待重试条目(进程内易失,重启即失效)。 + /// + private sealed class PendingProjection + { + /// 结果标识。 + public string MatchResultId { get; set; } + + /// 对局标识。 + public string MatchId { get; set; } + + /// 租户标识。 + public long TenantId { get; set; } + + /// App 标识。 + public long AppId { get; set; } + + /// 区服标识。 + public long ServerId { get; set; } + + /// 累计投递尝试次数(首发失败 = 1)。 + public int Attempts { get; set; } + } +} diff --git a/GameFrameX.Apps.Sample/OnlineRockPaperScissorsGame.cs b/GameFrameX.Apps.Sample/OnlineRockPaperScissorsGame.cs new file mode 100644 index 000000000..7e367c75f --- /dev/null +++ b/GameFrameX.Apps.Sample/OnlineRockPaperScissorsGame.cs @@ -0,0 +1,814 @@ +// ========================================================================================== +// 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 related 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 see 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 legitimate 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 System.Collections.Generic; +using System.Text.Json; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Assets; + +namespace GameFrameX.Capability.Online.Match; + +/// +/// 石头剪刀布样例玩法(使用石头剪刀布或小型回合制玩法作为第一版样例)。 +/// +/// 规则:两人对局,三局两胜(先得 局者胜,最多 局); +/// 每局双方各提交一次出拳,服务端判定胜负;单局无人出拳则本局作废。 +/// 单局超时()由服务端按规则推进:已出拳方判该局胜,双方均未出拳则本局作废—— +/// 这使「玩家不做操作」也收敛到确定结果,而非永久挂起。 +/// 参与奖资格红线:任意一方全程零有效出拳(挂机)时,结算抑制全部非胜方参与奖(胜方奖励不受影响)。 +/// +/// +/// 维护约束(红线):本类不做任何鉴权与身份判定(由 Actor 负责),也不产出 MatchResultId +/// (由结算服务统一分配)——玩法只回答「这一手合法吗、现在谁赢了」。 +/// +/// +public sealed class OnlineRockPaperScissorsGame : IOnlineMatchGame +{ + /// 模式标识(与现网客户端契约 _0410_RockPaperScissors 对齐)。 + public const int MatchMode = 410; + + /// 获胜所需局数。 + public const int WinTarget = 2; + + /// 最大局数(先胜 局即终局)。 + public const int MaxRounds = WinTarget * 2 - 1; + + /// 单局时限(毫秒)。 + public const long RoundTimeoutMilliseconds = 30000L; + + /// 样例奖励资产标识。 + public const string RewardAssetId = "sample-coin"; + + /// 胜方奖励数量。 + public const long WinnerRewardAmount = 100L; + + /// 参与奖数量(负方与平局发放;前提是双方均有有效出拳——任意一方零出拳时整场抑制,防挂机刷奖)。 + public const long ParticipantRewardAmount = 10L; + + /// 出拳提交事件。 + private const string GestureSubmittedEventType = "GestureSubmitted"; + + /// 单局结算事件。 + private const string RoundResolvedEventType = "RoundResolved"; + + /// + /// 获取模式标识。 + /// + public int Mode + { + get { return MatchMode; } + } + + /// + /// 获取最小玩家数。 + /// + public int MinPlayers + { + get { return 2; } + } + + /// + /// 获取最大玩家数。 + /// + public int MaxPlayers + { + get { return 2; } + } + + /// + /// 构造初始玩法状态:为全部在局成员建计分位,进入第 1 局。 + /// + /// 对局。 + /// 序列化后的初始状态。 + public byte[] CreateInitialState(OnlineMatch match) + { + var state = new OnlineRockPaperScissorsState + { + Round = 1, + WinnerPlayerId = 0, + RoundDeadlineTime = 0, + Players = new List(), + }; + + if (match.Members != null) + { + foreach (var member in match.Members) + { + if (member == null || member.State == OnlineMatchMemberState.Left || member.State == OnlineMatchMemberState.Kicked) + { + continue; + } + + state.Players.Add(new OnlineRockPaperScissorsState.OnlineRockPaperScissorsPlayerState + { + PlayerId = member.PlayerId, + Wins = 0, + Gesture = OnlineRockPaperScissorsMove.None, + ValidGestureCount = 0, + }); + } + } + + return Serialize(state); + } + + /// + /// 处理一次出拳意图(只接受本局未出拳的成员;出拳值非契约枚举一律拒绝)。 + /// + /// 对局。 + /// 提交成员(身份已由 Actor 校验)。 + /// 输入意图( = 出拳值)。 + /// 处理结果。 + public OnlineMatchGameStepResult ApplyInput(OnlineMatch match, OnlineMatchMember member, OnlineMatchInput input) + { + var state = Deserialize(match.GameState); + if (state == null || state.Players == null || state.Players.Count == 0) + { + return Reject(OnlineMatchInputRejection.IllegalAction, "对局状态不可用"); + } + + var me = FindPlayer(state, member.PlayerId); + if (me == null) + { + return Reject(OnlineMatchInputRejection.NotMember, "玩家不在本局计分表中"); + } + + if (!IsGestureValid(input.ActionId)) + { + return Reject(OnlineMatchInputRejection.IllegalAction, "非法出拳"); + } + + if (me.Gesture != OnlineRockPaperScissorsMove.None) + { + return Reject(OnlineMatchInputRejection.Duplicate, "本局已提交过出拳"); + } + + me.Gesture = (OnlineRockPaperScissorsMove)input.ActionId; + me.ValidGestureCount += 1; + + var submittedCount = 0; + foreach (var player in state.Players) + { + if (player.Gesture != OnlineRockPaperScissorsMove.None) + { + submittedCount++; + } + } + + var emittedEvents = new List + { + BuildEvent(GestureSubmittedEventType, new GestureSubmittedPayload + { + Round = state.Round, + PlayerId = member.PlayerId, + SubmittedCount = submittedCount, + PlayerCount = state.Players.Count, + }), + }; + + if (submittedCount >= state.Players.Count) + { + emittedEvents.Add(BuildEvent(RoundResolvedEventType, SettleRound(state, ResolveWinner(state), false))); + } + + return new OnlineMatchGameStepResult + { + Accepted = true, + Rejection = OnlineMatchInputRejection.None, + GameState = Serialize(state), + ServerEvents = emittedEvents, + Message = "已接受", + }; + } + + /// + /// 时间推进:布防回合时钟;到点按超时规则判定本局(已出拳方胜,双方未出拳则本局作废)。 + /// + /// 对局。 + /// 当前时刻(UTC 毫秒)。 + /// 本次推进要追加的服务器事件。 + /// 状态是否被改写。 + public bool Advance(OnlineMatch match, long nowUnixMilliseconds, List emittedEvents) + { + var state = Deserialize(match.GameState); + if (state == null || state.Players == null || state.Players.Count == 0) + { + return false; + } + + if (state.RoundDeadlineTime == 0) + { + state.RoundDeadlineTime = nowUnixMilliseconds + RoundTimeoutMilliseconds; + match.GameState = Serialize(state); + return true; + } + + if (nowUnixMilliseconds < state.RoundDeadlineTime) + { + return false; + } + + emittedEvents.Add(BuildEvent(RoundResolvedEventType, SettleRound(state, ResolveWinner(state), true))); + match.GameState = Serialize(state); + return true; + } + + /// + /// 判定是否已分出结果(有人达到胜局数,或局数已超过上限)。 + /// + /// 对局。 + /// 已分出结果返回 true。 + public bool IsCompleted(OnlineMatch match) + { + var state = Deserialize(match.GameState); + if (state == null || state.Players == null || state.Players.Count == 0) + { + return false; + } + + if (state.Round > MaxRounds) + { + return true; + } + + foreach (var player in state.Players) + { + if (player.Wins >= WinTarget) + { + return true; + } + } + + return false; + } + + /// + /// 产出结算结果:名次按胜局数,胜方得胜方奖励、负方与平局在双方均有有效出拳时得参与奖。 + /// + /// 反刷奖规则(红线):任意一方累计有效出拳数为 0(全程挂机)时,抑制全部非胜方参与奖—— + /// 胜方奖励不受影响(胜局只能由已出拳方取得,零出拳者不可能成为胜方); + /// 结果置 供风控消费。 + /// + /// + /// 对局。 + /// 结算结果;状态缺失返回 null。 + public OnlineMatchResult BuildResult(OnlineMatch match) + { + var state = Deserialize(match.GameState); + if (state == null || state.Players == null || state.Players.Count == 0) + { + return null; + } + + var winnerPlayerId = FindWinner(state); + var participationRewardSuppressed = HasPlayerWithoutValidGesture(state); + var result = new OnlineMatchResult + { + Mode = match.Mode, + Region = match.Region, + ParticipationRewardsSuppressed = participationRewardSuppressed, + Entries = new List(), + }; + + foreach (var player in state.Players) + { + var isWinner = winnerPlayerId != 0 && player.PlayerId == winnerPlayerId; + var rewards = new List(); + if (isWinner) + { + rewards.Add(new OnlineAssetChangeLine(OnlineAssetKind.Currency, RewardAssetId, WinnerRewardAmount)); + } + else if (!participationRewardSuppressed) + { + rewards.Add(new OnlineAssetChangeLine(OnlineAssetKind.Currency, RewardAssetId, ParticipantRewardAmount)); + } + + result.Entries.Add(new OnlineMatchResultEntry + { + PlayerId = player.PlayerId, + Rank = winnerPlayerId == 0 || isWinner ? 1 : 2, + IsWinner = isWinner, + Score = player.Wins, + Rewards = rewards, + }); + } + + return result; + } + + /// + /// 构造对局桥视图(保密投影):玩法属主自行决定对外可见性—— + /// 当前局未结算一律不回显真实出拳,已结算局回显最近一次 RoundResolved 事件载荷中的真实出拳; + /// 整局胜者仅终局非 0(平局为 0)。 + /// + /// 维护约束(红线):本投影只读快照与事件流,不改写任何对局状态; + /// 终局判定复用本类规则( / ),不引入第二套判定。 + /// + /// + /// 房间标识(回显请求侧关联键)。 + /// 对局快照(权威状态切片)。 + /// 事件流(取自 Actor 增量;用于回显最近一次已结算局的真实出拳)。 + /// 桥接视图;玩法状态缺失时返回仅含生命周期状态的空投影视图。 + public OnlineMatchBridgeGameView BuildBridgeView(long roomId, OnlineMatchSnapshot snapshot, IReadOnlyList events) + { + var state = Deserialize(snapshot == null ? null : snapshot.GameState); + var view = new OnlineMatchBridgeGameView + { + RoomId = roomId, + MatchId = snapshot == null ? string.Empty : snapshot.MatchId, + Mode = snapshot == null ? MatchMode : snapshot.Mode, + State = ProjectState(snapshot == null ? OnlineMatchState.Created : snapshot.State), + Round = 1, + WinnerPlayerId = 0, + Players = new List(), + }; + + if (state == null || state.Players == null || state.Players.Count == 0) + { + return view; + } + + view.Round = state.Round; + if (IsFinal(state)) + { + view.WinnerPlayerId = FindWinner(state); + } + + var revealed = FindLatestResolvedPlays(events, state.Round); + foreach (var player in state.Players) + { + if (player == null) + { + continue; + } + + view.Players.Add(new OnlineMatchBridgePlayerView + { + PlayerId = player.PlayerId, + HasGesture = player.Gesture != OnlineRockPaperScissorsMove.None, + Wins = player.Wins, + Gesture = revealed != null && revealed.TryGetValue(player.PlayerId, out var gesture) ? (int)gesture : 0, + }); + } + + return view; + } + + /// + /// 判定玩法是否已终局(复用本类规则:局数超上限或任一玩家达到胜局数)。 + /// + /// 玩法状态。 + /// 终局返回 true。 + private static bool IsFinal(OnlineRockPaperScissorsState state) + { + if (state.Round > MaxRounds) + { + return true; + } + + foreach (var player in state.Players) + { + if (player != null && player.Wins >= WinTarget) + { + return true; + } + } + + return false; + } + + /// + /// 回显最近一次已结算局的真实出拳(仅当该局正是当前局的上一局——当前局进行中不回显任何真实出拳)。 + /// + /// 事件流。 + /// 当前局数。 + /// 玩家 → 真实出拳映射;无可回显局返回 null。 + private static Dictionary FindLatestResolvedPlays(IReadOnlyList events, int currentRound) + { + var payload = FindLatestResolvedPayload(events, currentRound); + if (payload == null) + { + return null; + } + + return CollectPlays(payload); + } + + /// + /// 倒序定位最近一次已结算局载荷:仅当其局数恰为当前局的上一局才返回; + /// 载荷解析失败或校验不通过即返回 null 终止(不再回扫更早事件)。 + /// + /// 事件流。 + /// 当前局数。 + /// 可回显的单局结算载荷;无可回显局返回 null。 + private static RoundResolvedPayload FindLatestResolvedPayload(IReadOnlyList events, int currentRound) + { + if (events == null) + { + return null; + } + + for (var index = events.Count - 1; index >= 0; index--) + { + var item = events[index]; + if (item == null || !string.Equals(item.EventType, RoundResolvedEventType, System.StringComparison.Ordinal)) + { + continue; + } + + RoundResolvedPayload payload; + try + { + payload = item.Payload == null ? null : JsonSerializer.Deserialize(item.Payload); + } + catch (JsonException) + { + return null; + } + + if (payload == null || payload.Plays == null || payload.Round != currentRound - 1) + { + return null; + } + + return payload; + } + + return null; + } + + /// + /// 将已结算局载荷中的双方出拳收集为玩家 → 出拳映射(null 出拳条目跳过)。 + /// + /// 已通过局数校验的单局结算载荷。 + /// 玩家 → 真实出拳映射。 + private static Dictionary CollectPlays(RoundResolvedPayload payload) + { + var plays = new Dictionary(); + foreach (var play in payload.Plays) + { + if (play != null) + { + plays[play.PlayerId] = play.Gesture; + } + } + + return plays; + } + + /// + /// 平台对局状态 → 桥接生命周期状态投影。 + /// + /// 平台对局状态。 + /// 桥接状态。 + private static OnlineMatchBridgeGameState ProjectState(OnlineMatchState state) + { + switch (state) + { + case OnlineMatchState.Created: + case OnlineMatchState.Waiting: + return OnlineMatchBridgeGameState.Waiting; + case OnlineMatchState.Ready: + return OnlineMatchBridgeGameState.Ready; + case OnlineMatchState.Running: + return OnlineMatchBridgeGameState.Running; + case OnlineMatchState.Settling: + return OnlineMatchBridgeGameState.Settling; + case OnlineMatchState.Completed: + return OnlineMatchBridgeGameState.Completed; + case OnlineMatchState.SettlementFailed: + return OnlineMatchBridgeGameState.SettlementFailed; + default: + return OnlineMatchBridgeGameState.Terminated; + } + } + + /// + /// 解析本局胜负:仅出一拳者胜;两拳相同为平局;否则按克制关系判定。 + /// + /// 玩法状态。 + /// 胜者玩家标识;平局或无法判定返回 0。 + private static long ResolveWinner(OnlineRockPaperScissorsState state) + { + if (state.Players.Count < 2) + { + return 0; + } + + var first = state.Players[0]; + var second = state.Players[1]; + + if (first.Gesture == OnlineRockPaperScissorsMove.None && second.Gesture == OnlineRockPaperScissorsMove.None) + { + return 0; + } + + if (first.Gesture == OnlineRockPaperScissorsMove.None) + { + return second.PlayerId; + } + + if (second.Gesture == OnlineRockPaperScissorsMove.None) + { + return first.PlayerId; + } + + if (first.Gesture == second.Gesture) + { + return 0; + } + + return Beats(first.Gesture, second.Gesture) ? first.PlayerId : second.PlayerId; + } + + /// + /// 收束本局:计分、清空出拳、进入下一局(并解除回合时钟布防)。 + /// + /// 玩法状态。 + /// 本局胜者(0 = 平局)。 + /// 是否由超时触发。 + /// 本局结算事件载荷。 + private static RoundResolvedPayload SettleRound(OnlineRockPaperScissorsState state, long winnerPlayerId, bool timedOut) + { + var resolvedRound = state.Round; + var plays = new List(); + var scores = new List(); + foreach (var player in state.Players) + { + plays.Add(new RoundPlayPayload + { + PlayerId = player.PlayerId, + Gesture = player.Gesture, + }); + + if (winnerPlayerId != 0 && player.PlayerId == winnerPlayerId) + { + player.Wins++; + } + } + + state.WinnerPlayerId = winnerPlayerId; + state.Round = resolvedRound + 1; + state.RoundDeadlineTime = 0; + + foreach (var player in state.Players) + { + scores.Add(new RoundScorePayload + { + PlayerId = player.PlayerId, + Wins = player.Wins, + }); + + player.Gesture = OnlineRockPaperScissorsMove.None; + } + + return new RoundResolvedPayload + { + Round = resolvedRound, + WinnerPlayerId = winnerPlayerId, + TimedOut = timedOut, + Plays = plays, + Scores = scores, + }; + } + + /// + /// 判定是否存在零有效出拳玩家(全程挂机——参与奖抑制条件)。 + /// + /// 玩法状态。 + /// 存在零出拳玩家返回 true。 + private static bool HasPlayerWithoutValidGesture(OnlineRockPaperScissorsState state) + { + foreach (var player in state.Players) + { + if (player == null || player.ValidGestureCount == 0) + { + return true; + } + } + + return false; + } + + /// + /// 判定胜负并返回胜者标识(平局返回 0)。 + /// + /// 玩法状态。 + /// 胜者玩家标识;平局返回 0。 + private static long FindWinner(OnlineRockPaperScissorsState state) + { + long winnerPlayerId = 0; + var bestWins = -1; + var bestCount = 0; + foreach (var player in state.Players) + { + if (player.Wins > bestWins) + { + bestWins = player.Wins; + winnerPlayerId = player.PlayerId; + bestCount = 1; + } + else if (player.Wins == bestWins) + { + bestCount++; + } + } + + return bestCount > 1 || bestWins <= 0 ? 0 : winnerPlayerId; + } + + /// + /// 判定出拳值是否在契约枚举范围内。 + /// + /// 出拳值。 + /// 合法返回 true。 + private static bool IsGestureValid(int actionId) + { + return actionId >= (int)OnlineRockPaperScissorsMove.Rock && actionId <= (int)OnlineRockPaperScissorsMove.Paper; + } + + /// + /// 判定 是否克制 。 + /// + /// 左方出拳。 + /// 右方出拳。 + /// 左方胜返回 true。 + private static bool Beats(OnlineRockPaperScissorsMove left, OnlineRockPaperScissorsMove right) + { + return (left == OnlineRockPaperScissorsMove.Rock && right == OnlineRockPaperScissorsMove.Scissors) + || (left == OnlineRockPaperScissorsMove.Scissors && right == OnlineRockPaperScissorsMove.Paper) + || (left == OnlineRockPaperScissorsMove.Paper && right == OnlineRockPaperScissorsMove.Rock); + } + + /// + /// 在计分表中查找玩家。 + /// + /// 玩法状态。 + /// 玩家标识。 + /// 玩家状态;不存在返回 null。 + private static OnlineRockPaperScissorsState.OnlineRockPaperScissorsPlayerState FindPlayer(OnlineRockPaperScissorsState state, long playerId) + { + foreach (var player in state.Players) + { + if (player.PlayerId == playerId) + { + return player; + } + } + + return null; + } + + /// + /// 构造拒绝结果。 + /// + /// 拒绝原因。 + /// 说明。 + /// 处理结果。 + private static OnlineMatchGameStepResult Reject(OnlineMatchInputRejection rejection, string message) + { + return new OnlineMatchGameStepResult + { + Accepted = false, + Rejection = rejection, + Message = message, + }; + } + + /// + /// 构造服务器事件(序号与发生时刻由 Actor 统一分配)。 + /// + /// 载荷类型。 + /// 事件类型。 + /// 载荷。 + /// 服务器事件。 + private static OnlineMatchServerEvent BuildEvent(string eventType, TPayload payload) + { + return new OnlineMatchServerEvent + { + EventType = eventType, + Payload = JsonSerializer.SerializeToUtf8Bytes(payload), + }; + } + + /// + /// 序列化玩法状态。 + /// + /// 玩法状态。 + /// 字节数组。 + private static byte[] Serialize(OnlineRockPaperScissorsState state) + { + return JsonSerializer.SerializeToUtf8Bytes(state); + } + + /// + /// 反序列化玩法状态。 + /// + /// 字节数组。 + /// 玩法状态;为空或损坏返回 null。 + private static OnlineRockPaperScissorsState Deserialize(byte[] gameState) + { + if (gameState == null || gameState.Length == 0) + { + return null; + } + + try + { + return JsonSerializer.Deserialize(gameState); + } + catch (JsonException) + { + return null; + } + } + + /// + /// 出拳提交事件负载(不含出拳值——未结算前不得泄露,防窥屏)。 + /// + private sealed class GestureSubmittedPayload + { + /// 当前局数。 + public int Round { get; set; } + + /// 提交者玩家标识。 + public long PlayerId { get; set; } + + /// 本局已提交人数。 + public int SubmittedCount { get; set; } + + /// 本局参与人数。 + public int PlayerCount { get; set; } + } + + /// + /// 单局结算事件负载(已结算,故可携带真实出拳)。 + /// + private sealed class RoundResolvedPayload + { + /// 被结算的局数。 + public int Round { get; set; } + + /// 本局胜者(0 = 平局)。 + public long WinnerPlayerId { get; set; } + + /// 是否由超时触发。 + public bool TimedOut { get; set; } + + /// 本局双方出拳。 + public List Plays { get; set; } + + /// 结算后的累计胜局。 + public List Scores { get; set; } + } + + /// + /// 单局出拳负载。 + /// + private sealed class RoundPlayPayload + { + /// 玩家标识。 + public long PlayerId { get; set; } + + /// 出拳。 + public OnlineRockPaperScissorsMove Gesture { get; set; } + } + + /// + /// 结算后计分负载。 + /// + private sealed class RoundScorePayload + { + /// 玩家标识。 + public long PlayerId { get; set; } + + /// 累计胜局。 + public int Wins { get; set; } + } +} \ No newline at end of file diff --git a/GameFrameX.Apps.Sample/OnlineRockPaperScissorsMove.cs b/GameFrameX.Apps.Sample/OnlineRockPaperScissorsMove.cs new file mode 100644 index 000000000..536bc9cc8 --- /dev/null +++ b/GameFrameX.Apps.Sample/OnlineRockPaperScissorsMove.cs @@ -0,0 +1,52 @@ +// ========================================================================================== +// 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 related 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 see 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 legitimate 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Match; + +/// +/// 石头剪刀布出拳(取值与现网客户端契约 RockPaperScissors_410.RockPaperScissorsGesture 一致)。 +/// +/// 维护约束(红线):客户端只提交**意图**(本枚举值),服务端负责判定胜负并产生结果—— +/// 客户端不得提交任何比分、胜负或奖励字段。 +/// +/// +public enum OnlineRockPaperScissorsMove +{ + /// 未出拳(未结算前对外一律呈现为该值)。 + None = 0, + + /// 石头。 + Rock = 1, + + /// 剪刀。 + Scissors = 2, + + /// 布。 + Paper = 3, +} \ No newline at end of file diff --git a/GameFrameX.Apps.Sample/OnlineRockPaperScissorsState.cs b/GameFrameX.Apps.Sample/OnlineRockPaperScissorsState.cs new file mode 100644 index 000000000..4d32a0957 --- /dev/null +++ b/GameFrameX.Apps.Sample/OnlineRockPaperScissorsState.cs @@ -0,0 +1,90 @@ +// ========================================================================================== +// 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 related 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 see 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 legitimate 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 System.Collections.Generic; + +namespace GameFrameX.Capability.Online.Match; + +/// +/// 石头剪刀布玩法状态(序列化后存于 )。 +/// +/// 维护约束(红线): 持有**未结算**的出拳, +/// 因此本状态的序列化结果属于服务端内部数据——不得原样下发给客户端(否则对手可在结算前窥屏)。 +/// 客户端可见的出拳只出现在已结算的 RoundResolved 事件载荷中(未结算前对外为 None)。 +/// +/// +public sealed class OnlineRockPaperScissorsState +{ + /// + /// 获取或设置当前局数(从 1 开始)。 + /// + public int Round { get; set; } + + /// + /// 获取或设置上一局胜者(平局为 0)。 + /// + public long WinnerPlayerId { get; set; } + + /// + /// 获取或设置本局截止时刻(UTC 毫秒;0 = 未布防,由 布防)。 + /// + public long RoundDeadlineTime { get; set; } + + /// + /// 获取或设置玩家状态集合。 + /// + public List Players { get; set; } + + /// + /// 单玩家玩法状态。 + /// + public sealed class OnlineRockPaperScissorsPlayerState + { + /// + /// 获取或设置玩家标识。 + /// + public long PlayerId { get; set; } + + /// + /// 获取或设置已胜局数。 + /// + public int Wins { get; set; } + + /// + /// 获取或设置本局出拳( = 未出拳)。 + /// + public OnlineRockPaperScissorsMove Gesture { get; set; } + + /// + /// 获取或设置累计有效出拳次数(跨局累计;参与奖资格判定依据——任意玩家为 0 时结算抑制全部参与奖)。 + /// 唯一写入点是 接受合法出拳;每局结算不清零。 + /// + public int ValidGestureCount { get; set; } + } +} \ No newline at end of file diff --git a/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj b/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj index 19a8f5f12..b6bc776f6 100644 --- a/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj +++ b/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj @@ -33,6 +33,8 @@ + + diff --git a/scripts/detached-liveops/OnlineAdminLiveOpsHandlers.cs b/scripts/detached-liveops/OnlineAdminLiveOpsHandlers.cs new file mode 100644 index 000000000..1b6bed42d --- /dev/null +++ b/scripts/detached-liveops/OnlineAdminLiveOpsHandlers.cs @@ -0,0 +1,403 @@ +// ========================================================================================== +// 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 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, +// 侵犯他人合法权益等法律法规所禁止的行为! +// 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://cnb.cool/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.Foundation.Json; +using GameFrameX.Foundation.Localization.Core; +using GameFrameX.Capability.Hosting.AdminApi; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Competition.LiveOps; +using GameFrameX.Capability.Online.Abstractions.Scope; + +namespace GameFrameX.Capability.Online.Competition.AdminApi; + +/// +/// LiveOps 域 admin 命令(publishRemoteConfig / syncDeviceGroup / syncScheduledTask / pushAnnouncement / +/// syncPlayerSegment / publishConfigRollout / rollbackConfigRollout)。 +/// +/// 维护约束:InMemory 追加式注册表为最小承载(admin 面下发留痕与最新态查询), +/// 生产级配置分发管道(存储 / 灰度计算 / 客户端推送)另行演进;七个 action 均为 Admin 无幂等键族, +/// 不做调度器层幂等包裹;ConfigKind 线缆数字 1~4 固定映射 RemoteConfig / Announcement / DeviceGroup / ScheduledTask。 +/// +/// +public static class OnlineAdminLiveOpsHandlers +{ + + /// + /// 注册 LiveOps 域 action:LiveOps 注册表经模块 Register 装配后传入。 + /// + /// 动作注册表。 + /// LiveOps 注册表。 + public static void RegisterLiveOps(AdminActionRegistry registry, OnlineLiveOpsRegistry liveOps) + { + registry.Register("publishRemoteConfig", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => PublishRemoteConfigAsync(request, scope, cancellationToken, liveOps)), false); + registry.Register("syncDeviceGroup", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => SyncDeviceGroupAsync(request, scope, cancellationToken, liveOps)), false); + registry.Register("syncScheduledTask", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => SyncScheduledTaskAsync(request, scope, cancellationToken, liveOps)), false); + registry.Register("pushAnnouncement", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => PushAnnouncementAsync(request, scope, cancellationToken, liveOps)), false); + registry.Register("syncPlayerSegment", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => SyncPlayerSegmentAsync(request, scope, cancellationToken, liveOps)), false); + registry.Register("publishConfigRollout", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => PublishConfigRolloutAsync(request, scope, cancellationToken, liveOps)), false); + registry.Register("rollbackConfigRollout", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => RollbackConfigRolloutAsync(request, scope, cancellationToken, liveOps)), false); + } + + /// + /// publishRemoteConfig:远程配置发布留痕。 + /// + /// 请求。 + /// 作用域。 + /// 取消令牌。 + /// LiveOps 注册表。 + /// LiveOps 回执。 + private static Task PublishRemoteConfigAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) + { + var configId = RequireId(request, "ConfigId"); + var reason = OnlineAdminApiContract.RequireString(request, "Reason"); + var entry = liveOps.Publish(new OnlineLiveOpsCommand + { + Kind = "RemoteConfig", + Key = configId.ToString(System.Globalization.CultureInfo.InvariantCulture), + Version = string.Empty, + PayloadText = reason, + OperatorId = "admin", + CorrelationId = request.ReadRequestId(), + }); + return Task.FromResult(BuildResponse(entry, 0)); + } + + /// + /// syncDeviceGroup:设备分组同步留痕。 + /// + /// 请求。 + /// 作用域。 + /// 取消令牌。 + /// LiveOps 注册表。 + /// LiveOps 回执。 + private static Task SyncDeviceGroupAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) + { + var deviceGroupId = RequireId(request, "DeviceGroupId"); + var reason = OnlineAdminApiContract.RequireString(request, "Reason"); + var entry = liveOps.Sync(new OnlineLiveOpsCommand + { + Kind = "DeviceGroup", + Key = deviceGroupId.ToString(System.Globalization.CultureInfo.InvariantCulture), + PayloadText = reason, + OperatorId = "admin", + CorrelationId = request.ReadRequestId(), + }); + return Task.FromResult(BuildResponse(entry, 0)); + } + + /// + /// syncScheduledTask:定时任务同步留痕。 + /// + /// 请求。 + /// 作用域。 + /// 取消令牌。 + /// LiveOps 注册表。 + /// LiveOps 回执。 + private static Task SyncScheduledTaskAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) + { + var jobId = RequireId(request, "JobId"); + var reason = OnlineAdminApiContract.RequireString(request, "Reason"); + var entry = liveOps.Sync(new OnlineLiveOpsCommand + { + Kind = "ScheduledTask", + Key = jobId.ToString(System.Globalization.CultureInfo.InvariantCulture), + PayloadText = reason, + OperatorId = "admin", + CorrelationId = request.ReadRequestId(), + }); + return Task.FromResult(BuildResponse(entry, 0)); + } + + /// + /// pushAnnouncement:公告推送留痕。 + /// + /// 请求。 + /// 作用域。 + /// 取消令牌。 + /// LiveOps 注册表。 + /// LiveOps 回执。 + private static Task PushAnnouncementAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) + { + var announcementId = RequireId(request, "AnnouncementId"); + var reason = OnlineAdminApiContract.RequireString(request, "Reason"); + var entry = liveOps.Publish(new OnlineLiveOpsCommand + { + Kind = "Announcement", + Key = announcementId.ToString(System.Globalization.CultureInfo.InvariantCulture), + Version = string.Empty, + PayloadText = reason, + OperatorId = "admin", + CorrelationId = request.ReadRequestId(), + }); + return Task.FromResult(BuildResponse(entry, 0)); + } + + /// + /// syncPlayerSegment:玩家分群同步留痕(载荷 = 名称 + 条件原文)。 + /// + /// 请求。 + /// 作用域。 + /// 取消令牌。 + /// LiveOps 注册表。 + /// LiveOps 回执。 + private static Task SyncPlayerSegmentAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) + { + var segmentId = RequireId(request, "SegmentId"); + var name = OnlineAdminApiContract.RequireString(request, "Name"); + var conditions = OnlineAdminApiContract.ReadOptionalString(request, "Conditions") ?? string.Empty; + var reason = OnlineAdminApiContract.RequireString(request, "Reason"); + var payload = JsonHelper.Serialize(new SegmentPayload { Name = name, Conditions = conditions, Reason = reason, }); + var entry = liveOps.Sync(new OnlineLiveOpsCommand + { + Kind = "PlayerSegment", + Key = segmentId.ToString(System.Globalization.CultureInfo.InvariantCulture), + PayloadText = payload, + OperatorId = "admin", + CorrelationId = request.ReadRequestId(), + }); + return Task.FromResult(BuildResponse(entry, segmentId)); + } + + /// + /// publishConfigRollout:配置灰度发布留痕(ConfigKind 1~4 + 键 + 版本 + 分群 + 百分比)。 + /// + /// 请求。 + /// 作用域。 + /// 取消令牌。 + /// LiveOps 注册表。 + /// LiveOps 回执。 + private static Task PublishConfigRolloutAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) + { + var configKind = ReadConfigKind(request); + var configKey = OnlineAdminApiContract.RequireString(request, "ConfigKey"); + var configVersion = RequireVersion(request, "ConfigVersion"); + var segmentId = request.ReadNullableInt64("SegmentId") ?? 0; + var percent = ReadRolloutPercent(request); + var reason = OnlineAdminApiContract.RequireString(request, "Reason"); + var payload = JsonHelper.Serialize(new RolloutPayload + { + ConfigKind = configKind, + SegmentId = segmentId, + Percent = percent, + Reason = reason, + }); + var entry = liveOps.Publish(new OnlineLiveOpsCommand + { + Kind = RolloutKind(configKind), + Key = configKey, + Version = configVersion.ToString(System.Globalization.CultureInfo.InvariantCulture), + PayloadText = payload, + OperatorId = "admin", + CorrelationId = request.ReadRequestId(), + }); + return Task.FromResult(BuildResponse(entry, segmentId)); + } + + /// + /// rollbackConfigRollout:配置灰度回滚留痕(目标版本即回滚后生效版本)。 + /// + /// 请求。 + /// 作用域。 + /// 取消令牌。 + /// LiveOps 注册表。 + /// LiveOps 回执。 + private static Task RollbackConfigRolloutAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) + { + var configKind = ReadConfigKind(request); + var configKey = OnlineAdminApiContract.RequireString(request, "ConfigKey"); + var targetVersion = RequireVersion(request, "TargetVersion"); + var reason = OnlineAdminApiContract.RequireString(request, "Reason"); + var entry = liveOps.Rollback(new OnlineLiveOpsCommand + { + Kind = RolloutKind(configKind), + Key = configKey, + Version = targetVersion.ToString(System.Globalization.CultureInfo.InvariantCulture), + PayloadText = reason, + OperatorId = "admin", + CorrelationId = request.ReadRequestId(), + }); + return Task.FromResult(BuildResponse(entry, 0)); + } + + /// + /// 读取必填正整数标识。 + /// + /// 请求。 + /// 字段名。 + /// 标识。 + private static long RequireId(AdminApiRequest request, string name) + { + var value = request.ReadNullableInt64(name); + if (value.HasValue && value.Value > 0) + { + return value.Value; + } + + // Localization: Online.AdminApi.PositiveNumberRequired - {0} 必须为正数。 + throw new OnlineServiceException(OnlineErrorCode.ParameterInvalid, LocalizationService.GetString(Localization.Keys.Online.AdminApi.PositiveNumberRequired, name)); + } + + /// + /// 读取必填正版本号。 + /// + /// 请求。 + /// 字段名。 + /// 版本号。 + private static int RequireVersion(AdminApiRequest request, string name) + { + var value = request.ReadNullableInt32(name); + if (value.HasValue && value.Value > 0) + { + return value.Value; + } + + // Localization: Online.AdminApi.PositiveNumberRequired - {0} 必须为正数。 + throw new OnlineServiceException(OnlineErrorCode.ParameterInvalid, LocalizationService.GetString(Localization.Keys.Online.AdminApi.PositiveNumberRequired, name)); + } + + /// + /// 读取 ConfigKind(线缆数字 1~4)。 + /// + /// 请求。 + /// ConfigKind 数字。 + private static int ReadConfigKind(AdminApiRequest request) + { + var value = request.ReadNullableInt32("ConfigKind"); + if (value.HasValue && value.Value >= 1 && value.Value <= 4) + { + return value.Value; + } + + // Localization: Online.AdminApi.ConfigKindInvalid - ConfigKind 必须是 [1,4] 范围内的数字(RemoteConfig/Announcement/DeviceGroup/ScheduledTask)。 + throw new OnlineServiceException(OnlineErrorCode.ParameterInvalid, LocalizationService.GetString(Localization.Keys.Online.AdminApi.ConfigKindInvalid)); + } + + /// + /// 读取灰度百分比(0~100,缺省 100)。 + /// + /// 请求。 + /// 灰度百分比。 + private static int ReadRolloutPercent(AdminApiRequest request) + { + var value = request.ReadNullableInt32("Percent") ?? 100; + if (value >= 0 && value <= 100) + { + return value; + } + + // Localization: Online.AdminApi.RolloutPercentInvalid - Percent 必须是 [0,100] 范围内的灰度百分比。 + throw new OnlineServiceException(OnlineErrorCode.ParameterInvalid, LocalizationService.GetString(Localization.Keys.Online.AdminApi.RolloutPercentInvalid)); + } + + /// + /// ConfigKind 数字 → 灰度注册表 kind 前缀。 + /// + /// ConfigKind 数字。 + /// 注册表 kind。 + private static string RolloutKind(int configKind) + { + switch (configKind) + { + case 1: + return "ConfigRollout:RemoteConfig"; + case 2: + return "ConfigRollout:Announcement"; + case 3: + return "ConfigRollout:DeviceGroup"; + default: + return "ConfigRollout:ScheduledTask"; + } + } + + /// + /// 构造 LiveOps 回执(ConfirmVersion = 版本号,缺省回退注册表序号)。 + /// + /// 注册表条目。 + /// 分群标识(无关命令传 0)。 + /// LiveOps 回执。 + private static OnlineLiveOpsResponse BuildResponse(OnlineLiveOpsEntry entry, long segmentId) + { + return new OnlineLiveOpsResponse + { + ConfirmVersion = string.IsNullOrEmpty(entry.Version) + ? entry.Sequence.ToString(System.Globalization.CultureInfo.InvariantCulture) + : entry.Version, + SegmentId = segmentId, + ServerTime = OnlineAdminApiContract.NowSeconds() * 1000, + }; + } + + /// + /// 分群载荷。 + /// + public sealed class SegmentPayload + { + /// 获取或设置分群名称。 + public string Name { get; set; } + + /// 获取或设置条件原文。 + public string Conditions { get; set; } + + /// 获取或设置原因。 + public string Reason { get; set; } + } + + /// + /// 灰度载荷。 + /// + public sealed class RolloutPayload + { + /// 获取或设置 ConfigKind(1=RemoteConfig/2=Announcement/3=DeviceGroup/4=ScheduledTask)。 + public int ConfigKind { get; set; } + + /// 获取或设置分群标识。 + public long SegmentId { get; set; } + + /// 获取或设置灰度百分比(0~100)。 + public int Percent { get; set; } + + /// 获取或设置原因。 + public string Reason { get; set; } + } + + /// + /// LiveOps 回执(对齐 Admin OnlineLiveOpsResponse)。 + /// + public sealed class OnlineLiveOpsResponse + { + /// 获取或设置确认版本。 + public string ConfirmVersion { get; set; } + + /// 获取或设置分群标识(未返回为 0)。 + public long SegmentId { get; set; } + + /// 获取或设置消息(未返回为 null)。 + public string Message { get; set; } + + /// 获取或设置服务端时刻(UTC 毫秒)。 + public long ServerTime { get; set; } + } +} \ No newline at end of file diff --git a/scripts/detached-liveops/OnlineLiveOpsCommand.cs b/scripts/detached-liveops/OnlineLiveOpsCommand.cs new file mode 100644 index 000000000..72c5917bc --- /dev/null +++ b/scripts/detached-liveops/OnlineLiveOpsCommand.cs @@ -0,0 +1,78 @@ +// ========================================================================================== +// 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 related 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 see the LICENSE file in the root directory of the source code. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯其他合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate 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/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.LiveOps; + +/// +/// LiveOps 登记命令载荷(// +/// 的唯一提交形态;操作语义由 枚举承载)。 +/// +/// 维护约束:载荷原样登记(供查询端点回读),登记表 append-only——命令只追加不修改; +/// 六个字段历史上以相邻 string 摊排(位置互换零编译告警),收敛为命名字段后该风险消除。 +/// 语义下 不消费(实体 upsert 无版本概念)。 +/// +/// +public sealed class OnlineLiveOpsCommand +{ + /// + /// 获取或设置配置/实体种类(如 RemoteConfig / DeviceGroup / ScheduledTask / PlayerSegment / Announcement)。 + /// + /// Gets or sets the kind (e.g. RemoteConfig / DeviceGroup / ScheduledTask / PlayerSegment / Announcement). + public string Kind { get; init; } + + /// + /// 获取或设置种类内唯一键。 + /// + /// Gets or sets the kind-unique key. + public string Key { get; init; } + + /// + /// 获取或设置版本号(Publish/Rollback 使用;Sync 不消费)。 + /// + /// Gets or sets the version (used by Publish/Rollback; not consumed by Sync). + public string Version { get; init; } + + /// + /// 获取或设置载荷原文(原样登记,供查询端点回读)。 + /// + /// Gets or sets the raw payload text (registered as-is for read-back). + public string PayloadText { get; init; } + + /// + /// 获取或设置操作者。 + /// + /// Gets or sets the operator id. + public string OperatorId { get; init; } + + /// + /// 获取或设置关联标识。 + /// + /// Gets or sets the correlation id. + public string CorrelationId { get; init; } +} \ No newline at end of file diff --git a/scripts/detached-liveops/OnlineLiveOpsEntry.cs b/scripts/detached-liveops/OnlineLiveOpsEntry.cs new file mode 100644 index 000000000..bd8cfb6ad --- /dev/null +++ b/scripts/detached-liveops/OnlineLiveOpsEntry.cs @@ -0,0 +1,60 @@ +// ========================================================================================== +// 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, +// 侵犯他人合法权益等法律法规所禁止的行为! +// 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://cnb.cool/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.LiveOps; + +/// +/// LiveOps 登记条目(append-only;载荷原样登记不解释,见 )。 +/// +public sealed class OnlineLiveOpsEntry +{ + /// 获取登记序号(进程内单调递增)。 + public long Sequence { get; set; } + + /// 获取登记操作。 + public OnlineLiveOpsOperation Operation { get; set; } + + /// 获取配置种类。 + public string Kind { get; set; } = string.Empty; + + /// 获取配置键。 + public string Key { get; set; } = string.Empty; + + /// 获取版本号(Sync 操作为空串)。 + public string Version { get; set; } = string.Empty; + + /// 获取载荷原文。 + public string PayloadText { get; set; } = string.Empty; + + /// 获取操作者。 + public string OperatorId { get; set; } = string.Empty; + + /// 获取关联标识。 + public string CorrelationId { get; set; } = string.Empty; + + /// 获取登记时刻(UTC 毫秒)。 + public long CreatedAtTime { get; set; } +} \ No newline at end of file diff --git a/scripts/detached-liveops/OnlineLiveOpsOperation.cs b/scripts/detached-liveops/OnlineLiveOpsOperation.cs new file mode 100644 index 000000000..666519a49 --- /dev/null +++ b/scripts/detached-liveops/OnlineLiveOpsOperation.cs @@ -0,0 +1,42 @@ +// ========================================================================================== +// 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, +// 侵犯他人合法权益等法律法规所禁止的行为! +// 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://cnb.cool/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.LiveOps; + +/// +/// LiveOps 登记操作( append-only 登记表的条目操作语义)。 +/// +public enum OnlineLiveOpsOperation +{ + /// 发布版本。 + Publish = 0, + + /// 回滚版本。 + Rollback = 1, + + /// 同步实体(upsert)。 + Sync = 2, +} \ No newline at end of file diff --git a/scripts/detached-liveops/OnlineLiveOpsRegistry.cs b/scripts/detached-liveops/OnlineLiveOpsRegistry.cs new file mode 100644 index 000000000..edf3252b6 --- /dev/null +++ b/scripts/detached-liveops/OnlineLiveOpsRegistry.cs @@ -0,0 +1,160 @@ +// ========================================================================================== +// 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, +// 侵犯他人合法权益等法律法规所禁止的行为! +// 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://cnb.cool/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +namespace GameFrameX.Capability.Online.Competition.LiveOps; + +/// +/// LiveOps 最小承载(InMemory 版本登记表 + publish/rollback 语义)。 +/// +/// 维护约束:这是装配层对 Admin LiveOps 同步命令的**最小**承接(远端下发 / 灰度引擎不存在, +/// 只承担服务端半边)——只做 append-only 登记与最新版本视图,不实现灰度分流、设备分群计算、 +/// 定时触发等引擎语义(全量引擎另行演进);登记表不持久化(进程内,随宿主生命周期)。 +/// +/// +public sealed class OnlineLiveOpsRegistry +{ + /// + /// 同步锁(登记表为普通列表 + 字典,全部操作临界区内完成)。 + /// + private readonly object _sync = new(); + + /// + /// 登记表(append-only)。 + /// + private readonly List _entries = new(); + + /// + /// 最新条目索引(kind:key → 条目;回滚后指向回滚条目)。 + /// + private readonly Dictionary _latest = new(StringComparer.Ordinal); + + /// + /// 登记序号分配器。 + /// + private long _sequence; + + /// + /// 发布配置版本(同 kind+key 重复发布即追加新条目并接管最新视图)。 + /// + /// 登记命令载荷(Publish 语义:版本号参与登记)。 + /// 登记条目。 + public OnlineLiveOpsEntry Publish(OnlineLiveOpsCommand command) + { + return Append(OnlineLiveOpsOperation.Publish, command); + } + + /// + /// 回滚配置版本(登记回滚条目并接管最新视图;不删除历史条目)。 + /// + /// 登记命令载荷(Rollback 语义:版本号为被回滚到的目标版本)。 + /// 登记条目。 + public OnlineLiveOpsEntry Rollback(OnlineLiveOpsCommand command) + { + return Append(OnlineLiveOpsOperation.Rollback, command); + } + + /// + /// 同步实体(设备分群 / 定时任务 / 玩家分群等 upsert 语义:追加条目并接管最新视图)。 + /// + /// 登记命令载荷(Sync 语义:版本号不消费)。 + /// 登记条目。 + public OnlineLiveOpsEntry Sync(OnlineLiveOpsCommand command) + { + return Append(OnlineLiveOpsOperation.Sync, command); + } + + /// + /// 查询最新条目。 + /// + /// 配置种类。 + /// 配置键。 + /// 最新条目;无登记返回 null。 + public OnlineLiveOpsEntry FindLatest(string kind, string key) + { + lock (_sync) + { + _latest.TryGetValue(BuildKey(kind, key), out var entry); + return entry; + } + } + + /// + /// 按种类列出登记条目(时间倒序,最新在前)。 + /// + /// 配置种类(空串表示不限种类)。 + /// 最多返回条数。 + /// 条目列表。 + public IReadOnlyList List(string kind, int maxCount) + { + lock (_sync) + { + var source = string.IsNullOrEmpty(kind) + ? _entries + : _entries.Where(entry => string.Equals(entry.Kind, kind, StringComparison.Ordinal)).ToList(); + return source.OrderByDescending(entry => entry.Sequence).Take(Math.Max(1, maxCount)).ToList(); + } + } + + /// + /// 追加条目并接管最新视图。 + /// + /// 登记操作。 + /// 登记命令载荷。 + /// 登记条目。 + private OnlineLiveOpsEntry Append(OnlineLiveOpsOperation operation, OnlineLiveOpsCommand command) + { + var entry = new OnlineLiveOpsEntry + { + Sequence = Interlocked.Increment(ref _sequence), + Operation = operation, + Kind = command.Kind ?? string.Empty, + Key = command.Key ?? string.Empty, + Version = operation == OnlineLiveOpsOperation.Sync ? string.Empty : command.Version ?? string.Empty, + PayloadText = command.PayloadText ?? string.Empty, + OperatorId = command.OperatorId ?? string.Empty, + CorrelationId = command.CorrelationId ?? string.Empty, + CreatedAtTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + }; + lock (_sync) + { + _entries.Add(entry); + _latest[BuildKey(entry.Kind, entry.Key)] = entry; + } + + return entry; + } + + /// + /// 构造最新视图索引键。 + /// + /// 配置种类。 + /// 配置键。 + /// 索引键。 + private static string BuildKey(string kind, string key) + { + return (kind ?? string.Empty) + ":" + (key ?? string.Empty); + } +} \ No newline at end of file diff --git a/scripts/legacy/OnlineFriendLegacyMigration.cs b/scripts/legacy/OnlineFriendLegacyMigration.cs new file mode 100644 index 000000000..f68a7693f --- /dev/null +++ b/scripts/legacy/OnlineFriendLegacyMigration.cs @@ -0,0 +1,205 @@ +// ========================================================================================== +// 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 related 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 see 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 legitimate 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 System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Apps.Player.Friend.Entity; +using GameFrameX.Apps.ServerRole.Friend.Entity; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Scope; + +namespace GameFrameX.Capability.Online.Social; + +/// +/// 旧好友数据一次性迁移(C244 T3 落地,C294 自组合根逐语句迁入社交能力包;开关 = +/// ,模块激活期显式授权触发): +/// 读取本进程 GameDb 的旧 (域 120 旧链,Status=0 行 = 已建立关系) +/// 与旧 660 档案文档(Outgoing = 待答申请),经 +/// 真实写路径( 编排面)幂等收敛为 Online 好友关系。 +/// +/// 维护约束(红线): +/// ① 只读单向复制——旧表 / 旧文档零改动,回退 = 重部署旧版本代码即回旧链旧数据; +/// ② 幂等——重复执行经 SaveIfAbsent / 幂等收敛不产生第二条关系(已建立优先于待答); +/// ③ 零静默丢失——单条失败计数并继续(containment,不中断整体迁移),失败明细以返回汇总披露 +///(能力包零 LogHelper 惯例,逐条 Error 日志不再随迁,失败数与总数对账即披露面); +/// ④ 分进程旧数据在 Social 库时,须在 GameDb 指向该库的进程上执行(AllInOne 天然满足,spec 披露); +/// ⑤ 软删行(Status != 0)不迁移 = 已删除语义。 +/// +/// +public static class OnlineFriendLegacyMigration +{ + /// + /// 执行旧好友数据迁移(社交能力模块在激活期、好友域桥发布后调用)。 + /// + /// 好友域服务(真实写路径的唯一属主)。 + /// 租户标识(宿主 OnlineScope 三元组)。 + /// App 标识。 + /// 区服标识。 + /// 取消令牌。 + /// 迁移汇总(已建立关系数 / 待答申请数 / 失败数)。 + public static async Task<(int Established, int Pending, int Failed)> MigrateAsync(OnlineFriendService friends, long tenantId, long appId, long serverId, CancellationToken cancellationToken = default) + { + var domain = new OnlineFriendDomainFace(friends); + + // ① 域 120 旧链:FriendRelationState Status=0 → 已建立关系(Establish = 申请 + 立即接受,幂等收敛)。 + var (established, relationFailed) = await MigrateEstablishedRelationsAsync(domain, tenantId, appId, serverId, cancellationToken).ConfigureAwait(false); + + // ② 域 660 旧链:FriendState 档案 Outgoing → 待答申请(对已建立的对幂等无效果)。 + var (pending, profileFailed) = await MigratePendingRequestsAsync(domain, tenantId, appId, serverId, cancellationToken).ConfigureAwait(false); + + var failed = relationFailed + profileFailed; + return (established, pending, failed); + } + + /// + /// 迁移域 120 旧链:读取 FriendRelationState Status=0 行,逐条经 Establish 收敛为已建立关系 + /// (Establish = 申请 + 立即接受,幂等收敛);单条失败计数并继续(containment)。 + /// + /// Online 好友域契约面。 + /// 租户标识。 + /// App 标识。 + /// 区服标识。 + /// 取消令牌。 + /// (已建立关系数,失败数)。 + private static async Task<(int Established, int Failed)> MigrateEstablishedRelationsAsync(OnlineFriendDomainFace domain, long tenantId, long appId, long serverId, CancellationToken cancellationToken) + { + var established = 0; + var failed = 0; + var relations = await GameFrameX.DataBase.GameDb.FindListAsync(state => state.Status == 0).ConfigureAwait(false); + foreach (var relation in relations) + { + var low = relation.PlayerIdA; + var high = relation.PlayerIdB; + if (low <= 0 || high <= 0 || low == high) + { + continue; + } + + var result = await domain.EstablishAsync(PlayerScope(tenantId, appId, serverId, low), high, cancellationToken).ConfigureAwait(false); + if (result.IsSuccess && result.Data.After == OnlineFriendRelationKind.Friend) + { + established++; + } + else + { + failed++; + } + } + + return (established, failed); + } + + /// + /// 迁移域 660 旧链:读取 FriendState 档案文档,逐档案的 Outgoing 待答申请经真实写路径收敛 + /// (对已建立的对幂等无效果)。 + /// + /// Online 好友域契约面。 + /// 租户标识。 + /// App 标识。 + /// 区服标识。 + /// 取消令牌。 + /// (待答申请数,失败数)。 + private static async Task<(int Pending, int Failed)> MigratePendingRequestsAsync(OnlineFriendDomainFace domain, long tenantId, long appId, long serverId, CancellationToken cancellationToken) + { + var pending = 0; + var failed = 0; + var profiles = await GameFrameX.DataBase.GameDb.FindListAsync(state => state.Id >= 0).ConfigureAwait(false); + foreach (var document in profiles) + { + if (document?.Profiles == null) + { + continue; + } + + foreach (var profile in document.Profiles.Values) + { + if (profile?.Outgoing == null) + { + continue; + } + + var (entryPending, entryFailed) = await MigrateOutgoingRequestsAsync(domain, tenantId, appId, serverId, profile, cancellationToken).ConfigureAwait(false); + pending += entryPending; + failed += entryFailed; + } + } + + return (pending, failed); + } + + /// + /// 迁移单个旧档案的 Outgoing 待答申请:逐目标玩家校验后经 Request 真实写路径请求, + /// 单条失败计数并继续(containment)。 + /// + /// Online 好友域契约面。 + /// 租户标识。 + /// App 标识。 + /// 区服标识。 + /// 旧 660 好友档案。 + /// 取消令牌。 + /// (待答申请数,失败数)。 + private static async Task<(int Pending, int Failed)> MigrateOutgoingRequestsAsync(OnlineFriendDomainFace domain, long tenantId, long appId, long serverId, FriendProfileState profile, CancellationToken cancellationToken) + { + var pending = 0; + var failed = 0; + foreach (var targetPlayerId in profile.Outgoing) + { + if (profile.PlayerId <= 0 || targetPlayerId <= 0 || targetPlayerId == profile.PlayerId) + { + continue; + } + + var result = await domain.RequestAsync(PlayerScope(tenantId, appId, serverId, profile.PlayerId), targetPlayerId, cancellationToken).ConfigureAwait(false); + if (result.IsSuccess) + { + pending++; + } + else + { + failed++; + } + } + + return (pending, failed); + } + + /// + /// 构造玩家作用域(三元组取宿主 OnlineScope 值,玩家位为迁移主体)。 + /// + /// 租户标识。 + /// App 标识。 + /// 区服标识。 + /// 玩家标识。 + /// 生效作用域。 + private static OnlineScope PlayerScope(long tenantId, long appId, long serverId, long playerId) + { + return new OnlineScope(tenantId, appId, serverId, playerId); + } +} From a494ba224e701c9c234fba946fc5f95dec417254 Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 15:35:16 +0800 Subject: [PATCH 02/13] =?UTF-8?q?feat(online-social):=20=E6=8B=86=E9=99=A4?= =?UTF-8?q?=E5=AF=B9=E7=8E=A9=E6=B3=95=E5=B1=82=E4=B8=8E=E6=95=B0=E6=8D=AE?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=E7=9A=84=E5=BC=95=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 旧好友数据一次性迁移(依赖 Apps 旧链实体与 GameDb 静态门面)随旧链 状态退役移出能力包,原文存档 scripts/legacy/ 供独立迁移工具复用; 模块激活期迁移调用与 MigrateLegacyFriendData 开关随之移除,admin 载荷序列化改显式直引 Foundation.Json。 BREAKING CHANGE: Online.Settings.online-social.Friend.MigrateLegacyFriendData 配置键废止——能力配置绑定器对未知字段严格 fail-fast,存量配置须删除该键。 Linear: GFX-1199 --- ...GameFrameX.Capability.Online.Social.csproj | 14 +- .../OnlineFriendLegacyMigration.cs | 195 ------------- .../OnlineFriendOptions.cs | 10 - .../OnlineSocialCapabilityModule.cs | 31 +- .../OnlineFriendLegacyMigrationTests.cs | 273 ------------------ scripts/legacy/README.md | 10 + 6 files changed, 30 insertions(+), 503 deletions(-) delete mode 100644 Capability/GameFrameX.Capability.Online.Social/OnlineFriendLegacyMigration.cs delete mode 100644 Tests/GameFrameX.Tests/Online/OnlineFriendLegacyMigrationTests.cs create mode 100644 scripts/legacy/README.md diff --git a/Capability/GameFrameX.Capability.Online.Social/GameFrameX.Capability.Online.Social.csproj b/Capability/GameFrameX.Capability.Online.Social/GameFrameX.Capability.Online.Social.csproj index bc70d82ff..f2cadb207 100644 --- a/Capability/GameFrameX.Capability.Online.Social/GameFrameX.Capability.Online.Social.csproj +++ b/Capability/GameFrameX.Capability.Online.Social/GameFrameX.Capability.Online.Social.csproj @@ -2,19 +2,21 @@ - GameFrameX.Capability.Online.Social,GFX Online 社交能力包:好友/群组/聊天/通知/处罚/举报裁决六域 + 聊天审计投影 + 旧好友数据一次性迁移(InMemory 默认存储,描述符服务面 Override 替换)+ admin handlers(kick/revoke/mute/查询族). Social capability package for the GFX Online family: friends, groups, chat, notifications, punishments and report adjudication plus the chat-audit projection and the one-shot legacy friend-data migration with in-memory default stores and admin handlers. Documentation: https://gameframex.doc.alianblank.com + GameFrameX.Capability.Online.Social,GFX Online 社交能力包:好友/群组/聊天/通知/处罚/举报裁决六域 + 聊天审计投影(InMemory 默认存储,描述符服务面 Override 替换)+ admin handlers(kick/revoke/mute/查询族). Social capability package for the GFX Online family: friends, groups, chat, notifications, punishments and report adjudication plus the chat-audit projection with in-memory default stores and admin handlers. Documentation: https://gameframex.doc.alianblank.com GameFrameX,Capability,Online,Social,Friend,Chat,Punishment,GameServer - + + + + + + - - diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendLegacyMigration.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineFriendLegacyMigration.cs deleted file mode 100644 index 8dd19c682..000000000 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendLegacyMigration.cs +++ /dev/null @@ -1,195 +0,0 @@ -// ========================================================================================== -// 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 related 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 see 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 legitimate 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 System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using GameFrameX.Apps.Player.Friend.Entity; -using GameFrameX.Apps.ServerRole.Friend.Entity; -using GameFrameX.Capability.Online.Abstractions.Contracts; -using GameFrameX.Capability.Online.Abstractions.Scope; - -namespace GameFrameX.Capability.Online.Social; - -/// -/// 旧好友数据一次性迁移(C244 T3 落地,C294 自组合根逐语句迁入社交能力包;开关 = -/// ,模块激活期显式授权触发): -/// 读取本进程 GameDb 的旧 (域 120 旧链,Status=0 行 = 已建立关系) -/// 与旧 660 档案文档(Outgoing = 待答申请),经 -/// 真实写路径( 编排面)幂等收敛为 Online 好友关系。 -/// -/// 维护约束(红线): -/// ① 只读单向复制——旧表 / 旧文档零改动,回退 = 重部署旧版本代码即回旧链旧数据; -/// ② 幂等——重复执行经 SaveIfAbsent / 幂等收敛不产生第二条关系(已建立优先于待答); -/// ③ 零静默丢失——单条失败计数并继续(containment,不中断整体迁移),失败明细以返回汇总披露 -///(能力包零 LogHelper 惯例,逐条 Error 日志不再随迁,失败数与总数对账即披露面); -/// ④ 分进程旧数据在 Social 库时,须在 GameDb 指向该库的进程上执行(AllInOne 天然满足,spec 披露); -/// ⑤ 软删行(Status != 0)不迁移 = 已删除语义。 -/// -/// -public static class OnlineFriendLegacyMigration -{ - /// - /// 执行旧好友数据迁移(社交能力模块在激活期、好友域桥发布后调用)。 - /// - /// 好友域服务(真实写路径的唯一属主)。 - /// 区服标识。 - /// 取消令牌。 - /// 迁移汇总(已建立关系数 / 待答申请数 / 失败数)。 - public static async Task<(int Established, int Pending, int Failed)> MigrateAsync(OnlineFriendService friends, long serverId, CancellationToken cancellationToken = default) - { - var domain = new OnlineFriendDomainFace(friends); - - // ① 域 120 旧链:FriendRelationState Status=0 → 已建立关系(Establish = 申请 + 立即接受,幂等收敛)。 - var (established, relationFailed) = await MigrateEstablishedRelationsAsync(domain, serverId, cancellationToken).ConfigureAwait(false); - - // ② 域 660 旧链:FriendState 档案 Outgoing → 待答申请(对已建立的对幂等无效果)。 - var (pending, profileFailed) = await MigratePendingRequestsAsync(domain, serverId, cancellationToken).ConfigureAwait(false); - - var failed = relationFailed + profileFailed; - return (established, pending, failed); - } - - /// - /// 迁移域 120 旧链:读取 FriendRelationState Status=0 行,逐条经 Establish 收敛为已建立关系 - /// (Establish = 申请 + 立即接受,幂等收敛);单条失败计数并继续(containment)。 - /// - /// Online 好友域契约面。 - /// 区服标识。 - /// 取消令牌。 - /// (已建立关系数,失败数)。 - private static async Task<(int Established, int Failed)> MigrateEstablishedRelationsAsync(OnlineFriendDomainFace domain, long serverId, CancellationToken cancellationToken) - { - var established = 0; - var failed = 0; - var relations = await GameFrameX.DataBase.GameDb.FindListAsync(state => state.Status == 0).ConfigureAwait(false); - foreach (var relation in relations) - { - var low = relation.PlayerIdA; - var high = relation.PlayerIdB; - if (low <= 0 || high <= 0 || low == high) - { - continue; - } - - var result = await domain.EstablishAsync(PlayerScope(serverId, low), high, cancellationToken).ConfigureAwait(false); - if (result.IsSuccess && result.Data.After == OnlineFriendRelationKind.Friend) - { - established++; - } - else - { - failed++; - } - } - - return (established, failed); - } - - /// - /// 迁移域 660 旧链:读取 FriendState 档案文档,逐档案的 Outgoing 待答申请经真实写路径收敛 - /// (对已建立的对幂等无效果)。 - /// - /// Online 好友域契约面。 - /// 区服标识。 - /// 取消令牌。 - /// (待答申请数,失败数)。 - private static async Task<(int Pending, int Failed)> MigratePendingRequestsAsync(OnlineFriendDomainFace domain, long serverId, CancellationToken cancellationToken) - { - var pending = 0; - var failed = 0; - var profiles = await GameFrameX.DataBase.GameDb.FindListAsync(state => state.Id >= 0).ConfigureAwait(false); - foreach (var document in profiles) - { - if (document?.Profiles == null) - { - continue; - } - - foreach (var profile in document.Profiles.Values) - { - if (profile?.Outgoing == null) - { - continue; - } - - var (entryPending, entryFailed) = await MigrateOutgoingRequestsAsync(domain, serverId, profile, cancellationToken).ConfigureAwait(false); - pending += entryPending; - failed += entryFailed; - } - } - - return (pending, failed); - } - - /// - /// 迁移单个旧档案的 Outgoing 待答申请:逐目标玩家校验后经 Request 真实写路径请求, - /// 单条失败计数并继续(containment)。 - /// - /// Online 好友域契约面。 - /// 区服标识。 - /// 旧 660 好友档案。 - /// 取消令牌。 - /// (待答申请数,失败数)。 - private static async Task<(int Pending, int Failed)> MigrateOutgoingRequestsAsync(OnlineFriendDomainFace domain, long serverId, FriendProfileState profile, CancellationToken cancellationToken) - { - var pending = 0; - var failed = 0; - foreach (var targetPlayerId in profile.Outgoing) - { - if (profile.PlayerId <= 0 || targetPlayerId <= 0 || targetPlayerId == profile.PlayerId) - { - continue; - } - - var result = await domain.RequestAsync(PlayerScope(serverId, profile.PlayerId), targetPlayerId, cancellationToken).ConfigureAwait(false); - if (result.IsSuccess) - { - pending++; - } - else - { - failed++; - } - } - - return (pending, failed); - } - - /// - /// 构造玩家作用域(区服键取宿主 OnlineScope 值,玩家位为迁移主体)。 - /// - /// 区服标识。 - /// 玩家标识。 - /// 生效作用域。 - private static OnlineScope PlayerScope(long serverId, long playerId) - { - return new OnlineScope(serverId, playerId); - } -} diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendOptions.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineFriendOptions.cs index 207b542a7..82e38fd35 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineFriendOptions.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineFriendOptions.cs @@ -52,14 +52,4 @@ public sealed class OnlineFriendOptions /// 获取或设置好友列表返回条数上限(默认 200;同时也是好友上限裁决依据)。 /// public int FriendLimit { get; set; } = 200; - - /// - /// 获取或设置是否在模块激活期执行旧好友数据一次性迁移(默认 false;C294 收编原族级 - /// Online.MigrateLegacyFriendData 开关,配置路径 Online.Settings.online-social.Friend.MigrateLegacyFriendData)。 - /// - /// 维护约束:迁移只读单向复制旧表(域 120 FriendRelationState / 域 660 FriendState),旧数据零改动; - /// 幂等可重复执行;详见 。 - /// - /// - public bool MigrateLegacyFriendData { get; set; } } diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs index c0783d35c..c7781f197 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs @@ -55,8 +55,7 @@ namespace GameFrameX.Capability.Online.Social; /// /// ActivateAsync:发布 好友域桥契约面( /// 薄编排实现);枚举 扩展点注入聊天服务(群组探针以 "group" -/// 命名注册,兄弟域如 matchmaking 的 "party" 探针同面注入);按 -/// 触发旧好友数据一次性迁移()。 +/// 命名注册,兄弟域如 matchmaking 的 "party" 探针同面注入)。 /// /// /// 钩子声明: 聊天内容审核扩展点以默认放行策略声明 @@ -71,8 +70,8 @@ namespace GameFrameX.Capability.Online.Social; /// extension point via RequireHostService; the presence probe resolves through the required online-foundation /// dependency; outward products are registered back into the shared face; two expiry-sweep tick jobs anchor their /// tenant / app on the family infrastructure. ActivateAsync publishes the -/// bridge face, injects channel-membership probes into the chat service by -/// enumerating the extension point, and triggers the one-shot legacy friend-data migration when the option is on. +/// bridge face and injects channel-membership probes into the chat service by +/// enumerating the extension point. /// The chat moderation extension point is declared with the default allow-all strategy, replaced atomically by the /// hot-update side through CapabilityHook<T>.Attach. /// @@ -116,7 +115,7 @@ public sealed class OnlineSocialCapabilityModule : ICapabilityModule, IAdminActi private OnlineChatAuditProjection _chatAudit; /// - /// 好友服务(好友关系生命周期的唯一写者;激活期执行旧数据迁移的真实写路径)。 + /// 好友服务(好友关系生命周期的唯一写者)。 /// private OnlineFriendService _friends; @@ -136,12 +135,12 @@ public sealed class OnlineSocialCapabilityModule : ICapabilityModule, IAdminActi private OnlineSessionTokenService _tokens; /// - /// 合并校验后的社交 Options(Register 期取用;激活期迁移开关读取面)。 + /// 合并校验后的社交 Options(Register 期取用)。 /// private OnlineSocialOptions _options; /// - /// 族基建作用域(Register 期解析;迁移玩家作用域区服键来源)。 + /// 族基建作用域(Register 期解析)。 /// private OnlineScope _scope; @@ -225,26 +224,24 @@ public void Register(CapabilityRegistrationContext context) var scope = _scope; context.AddTickJob("notification-expiry-sweep", async ct => { - await _notifications.SweepExpiredAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); + await _notifications.SweepExpiredAsync(scope.TenantId, scope.AppId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); }); context.AddTickJob("friend-request-expiry-sweep", async ct => { - await _friends.SweepExpiredAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); + await _friends.SweepExpiredAsync(scope.TenantId, scope.AppId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); }); } /// - /// 激活社交能力:发布好友域桥,向聊天服务注入全部已注册的频道成员资格探针; - /// 仅当好友选项开启旧数据迁移时,执行一次旧好友数据迁移。 + /// 激活社交能力:发布好友域桥,向聊天服务注入全部已注册的频道成员资格探针。 /// /// - /// Publishes the friend domain bridge, attaches all registered channel membership probes to the chat service, - /// and runs the legacy friend data migration only when it is enabled in the friend options. + /// Publishes the friend domain bridge and attaches all registered channel membership probes to the chat service. /// /// 能力激活上下文 / Capability activation context /// 取消令牌 / Cancellation token /// 表示异步操作的任务 / A task representing the asynchronous operation - public async Task ActivateAsync(CapabilityActivationContext context, CancellationToken cancellationToken) + public Task ActivateAsync(CapabilityActivationContext context, CancellationToken cancellationToken) { // 好友域桥契约面发布(发布者身份 = 本能力;撤销由宿主停止期自动完成)。 context.Bridges.Publish(new OnlineFriendDomainFace(_friends)); @@ -252,11 +249,7 @@ public async Task ActivateAsync(CapabilityActivationContext context, Cancellatio // 频道成员资格探针注入(Activate 期才允许枚举扩展点;群组 "group" + 兄弟域 "party" 等一并注入)。 _chat.AttachChannelMembershipProbes(context.Services.GetServices()); - // 旧好友数据一次性迁移(显式开关,默认关闭;只读单向 + 幂等 + 逐条 containment + 汇总)。 - if (_options.Friend.MigrateLegacyFriendData) - { - await OnlineFriendLegacyMigration.MigrateAsync(_friends, _scope.ServerId, cancellationToken).ConfigureAwait(false); - } + return Task.CompletedTask; } /// diff --git a/Tests/GameFrameX.Tests/Online/OnlineFriendLegacyMigrationTests.cs b/Tests/GameFrameX.Tests/Online/OnlineFriendLegacyMigrationTests.cs deleted file mode 100644 index 50b9e2de7..000000000 --- a/Tests/GameFrameX.Tests/Online/OnlineFriendLegacyMigrationTests.cs +++ /dev/null @@ -1,273 +0,0 @@ -// ========================================================================================== -// 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 legitimate rights and interests of others, as prohibited by laws and regulations. -// 因基于本项目二次开发所产生的一切法律纠纷与责任, -// Any legal disputes or liabilities arising from secondary development based on this project -// 本组织及其贡献者不承担任何责任,开发者应自行承担。 -// The organization and contributors assume no responsibility; developers shall bear the responsibility themselves. -// 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 System; -using System.Collections.Generic; -using System.Text.Json; -using System.Threading.Tasks; -using GameFrameX.Apps.Player.Friend.Entity; -using GameFrameX.Apps.ServerRole.Friend.Entity; -using GameFrameX.Capability.Hosting.Abstractions; -using GameFrameX.Capability.Hosting.Core; -using GameFrameX.Capability.Online.Abstractions; -using GameFrameX.Capability.Online.Abstractions.Contracts; -using GameFrameX.Capability.Online.Abstractions.Scope; -using GameFrameX.Capability.Online.Operations.HotfixRollback; -using GameFrameX.Capability.Online.Social; -using GameFrameX.DataBase; -using GameFrameX.DataBase.Abstractions; -using GameFrameX.DataBase.Sqlite; -using Xunit; - -namespace GameFrameX.Tests.Online; - -/// -/// 旧好友数据一次性迁移测试(C244 T3 → C294 机制化):域 120 旧链 FriendRelationState 与域 660 旧 FriendState -/// 档案经真实写路径收敛为 Online 好友关系;只读单向复制(旧数据零改动)、幂等重放、软删行不迁移; -/// 配置开关 online-social.Friend.MigrateLegacyFriendData 打开时社交能力在 Activate 期自动执行迁移。 -/// -/// -/// Tests for the one-shot legacy friend-data migration (C244 T3, mechanism rewrite C294): the legacy domain-120 -/// FriendRelationState rows and the legacy domain-660 FriendState profiles converge into Online -/// friendships through the real write path; the migration is a read-only one-way copy (legacy data -/// untouched), idempotent on replay, skips soft-deleted rows, and runs automatically during activation -/// when the social option switch is on. -/// -[Collection("GameDbStaticStateCollection")] -public sealed class OnlineFriendLegacyMigrationTests -{ - /// 测试作用域租户标识。 - private const long TenantId = 9L; - - /// 测试作用域 App 标识。 - private const long AppId = 4L; - - /// 测试作用域区服标识。 - private const long ServerId = 1001; - - /// - /// 门面初始化后必须归还(关闭 + 复位静态注册表;串行集合保证静态门面独占)。 - /// - private static async Task WithSqliteFacadeAsync(Func action) - { - var opened = await GameDb.InitAsync(new DbOptions - { - ConnectionString = "Data Source=:memory:", - Name = "c244-friend-migration-tests", - }); - Assert.True(opened); - try - { - await action(); - } - finally - { - await GameDb.CloseAsync(); - GameDb.ResetForTesting(); - } - } - - /// - /// 组合 foundation + social(族配置段作用域 9/4/1001;好友 store 保持 InMemory 默认,迁移写路径与生产一致)并启动, - /// 执行用例主体后恒停止撤桥。 - /// - /// 用例主体(入参:已启动的组合产物)。 - /// Settings 子对象原文(null = 不写 Settings 键)。 - /// 异步任务。 - private static async Task WithStartedSocialRuntimeAsync(Func body, string settingsJson = null) - { - var settings = string.IsNullOrEmpty(settingsJson) ? string.Empty : ",\"Settings\":" + settingsJson; - var section = JsonDocument.Parse("{\"TenantId\":9,\"AppId\":4,\"ServerId\":1001" + settings + "}").RootElement.Clone(); - var options = new CapabilityCompositionOptions(section, new CollectingCapabilityAssemblyLog()) - { - HostOptions = new CapabilityHostOptions { ServerId = ServerId, }, - Filter = new CapabilityAssemblyFilter(new[] { "online-foundation", "online-social" }), - }; - options.Override(new OnlineCapabilityTestHarness.EmptyPlayerDirectory()); - options.Override(new OnlineCapabilityTestHarness.NoopHotfixRollbackExecutor()); - - var runtime = CapabilityComposition.Compose(new OnlineCapabilityFamily(), options); - try - { - await runtime.Host.StartAsync(); - await body(runtime); - } - finally - { - await runtime.StopAsync(); - } - } - - /// - /// 构造迁移作用域内的玩家作用域。 - /// - /// 玩家标识。 - /// 玩家作用域。 - private static OnlineScope PlayerScope(long playerId) - { - return new OnlineScope(ServerId, playerId); - } - - /// - /// 预置旧数据:一条已建立关系(11-22,Status=0)、一条软删关系(33-44,Status=1)、 - /// 一份 660 档案(55 → Outgoing[66])。 - /// - private static async Task SeedLegacyDataAsync() - { - await GameDb.AddOrUpdateAsync(new FriendRelationState { Id = 1, PlayerIdA = 11, PlayerIdB = 22, Status = 0, CreateTime = DateTime.UtcNow, CreatedBy = 11 }); - await GameDb.AddOrUpdateAsync(new FriendRelationState { Id = 2, PlayerIdA = 33, PlayerIdB = 44, Status = 1, CreateTime = DateTime.UtcNow, CreatedBy = 33 }); - - var legacyProfiles = new FriendState { Id = 3 }; - legacyProfiles.Profiles[55] = new FriendProfileState { PlayerId = 55 }; - legacyProfiles.Profiles[55].Outgoing.Add(66); - await GameDb.AddOrUpdateAsync(legacyProfiles); - } - - /// - /// 断言迁移收敛结果:11-22 已成友;55-66 待答;33-44(软删)无关系。 - /// - /// 好友服务。 - /// 异步任务。 - private static async Task AssertConvergedRelationsAsync(OnlineFriendService friends) - { - var friendPair = await friends.FindAsync(PlayerScope(11), 22); - Assert.True(friendPair.IsSuccess); - Assert.NotNull(friendPair.Data); - Assert.Equal(OnlineFriendshipState.Accepted, friendPair.Data.State); - var pendingPair = await friends.FindAsync(PlayerScope(55), 66); - Assert.True(pendingPair.IsSuccess); - Assert.NotNull(pendingPair.Data); - Assert.Equal(OnlineFriendshipState.Requested, pendingPair.Data.State); - var deletedPair = await friends.FindAsync(PlayerScope(33), 44); - Assert.True(deletedPair.IsSuccess); - Assert.Null(deletedPair.Data); - } - - /// - /// 迁移收敛:已建立对成友、待答申请入列、软删行不迁移、旧数据零改动。 - /// - [Fact] - public async Task Migrate_ConvergesLegacyData_WithoutTouchingLegacyRows() - { - await WithSqliteFacadeAsync(async () => - { - await SeedLegacyDataAsync(); - await WithStartedSocialRuntimeAsync(async runtime => - { - var friends = runtime.Host.Services.GetService(); - - var (established, pending, failed) = await OnlineFriendLegacyMigration.MigrateAsync(friends, ServerId); - - Assert.Equal(1, established); - Assert.Equal(1, pending); - Assert.Equal(0, failed); - await AssertConvergedRelationsAsync(friends); - - // 旧数据零改动:行数、状态、档案内容原样。 - var relations = await GameDb.FindListAsync(state => true); - Assert.Equal(2, relations.Count); - Assert.Contains(relations, r => r.PlayerIdA == 11 && r.PlayerIdB == 22 && r.Status == 0); - Assert.Contains(relations, r => r.PlayerIdA == 33 && r.PlayerIdB == 44 && r.Status == 1); - var profiles = await GameDb.FindListAsync(state => state.Id >= 0); - var profile = Assert.Single(profiles); - Assert.True(profile.Profiles.TryGetValue(55, out var legacy)); - Assert.Equal(new List { 66 }, legacy.Outgoing); - }); - }); - } - - /// - /// 迁移幂等:重放不产生第二条关系、不重复计数失败(SaveIfAbsent / 幂等收敛);好友域桥视角关系唯一。 - /// - [Fact] - public async Task Migrate_Replay_IsIdempotent() - { - await WithSqliteFacadeAsync(async () => - { - await SeedLegacyDataAsync(); - await WithStartedSocialRuntimeAsync(async runtime => - { - var friends = runtime.Host.Services.GetService(); - - await OnlineFriendLegacyMigration.MigrateAsync(friends, ServerId); - var (established, pending, failed) = await OnlineFriendLegacyMigration.MigrateAsync(friends, ServerId); - - Assert.Equal(1, established); - Assert.Equal(1, pending); - Assert.Equal(0, failed); - - Assert.True(CapabilityBridge.TryAcquire(out var lease)); - var domain = lease.Contract; - var relations = await domain.ListRelationsAsync(PlayerScope(11)); - Assert.Single(relations.Data); - var outgoing = await domain.ListRelationsAsync(PlayerScope(55)); - var only = Assert.Single(outgoing.Data); - Assert.Equal(66, only.OtherPlayerId); - Assert.Equal(OnlineFriendRelationKind.OutgoingRequest, only.Kind); - }); - }); - } - - /// - /// 配置开关打开(online-social.Friend.MigrateLegacyFriendData = true):社交能力在 Activate 期自动执行迁移, - /// 启动完成即可观测到收敛后的关系。 - /// - [Fact] - public async Task Activate_WithMigrateLegacyFriendDataEnabled_MigratesAutomatically() - { - await WithSqliteFacadeAsync(async () => - { - await SeedLegacyDataAsync(); - await WithStartedSocialRuntimeAsync(async runtime => - { - var friends = runtime.Host.Services.GetService(); - await AssertConvergedRelationsAsync(friends); - }, "{\"online-social\":{\"Friend\":{\"MigrateLegacyFriendData\":true}}}"); - }); - } - - /// - /// 配置开关缺省关闭:启动不触发迁移(旧数据在场,Online 侧仍无关系)。 - /// - [Fact] - public async Task Activate_WithMigrateLegacyFriendDataDefault_DoesNotMigrate() - { - await WithSqliteFacadeAsync(async () => - { - await SeedLegacyDataAsync(); - await WithStartedSocialRuntimeAsync(async runtime => - { - var friends = runtime.Host.Services.GetService(); - var friendPair = await friends.FindAsync(PlayerScope(11), 22); - Assert.True(friendPair.IsSuccess); - Assert.Null(friendPair.Data); - }); - }); - } -} diff --git a/scripts/legacy/README.md b/scripts/legacy/README.md new file mode 100644 index 000000000..c05639992 --- /dev/null +++ b/scripts/legacy/README.md @@ -0,0 +1,10 @@ +# legacy 脚本存档 + +随包结构收敛移出能力包的旧迁移代码存档:不再参与任何工程编译,仅作历史参考与二次搬迁素材。 + +## OnlineFriendLegacyMigration.cs + +- 原位置:`Capability/GameFrameX.Capability.Online.Social/OnlineFriendLegacyMigration.cs`。 +- 原职责:社交能力激活期可选执行的一次性旧好友数据迁移(只读单向复制旧链域 120 `FriendRelationState` / 域 660 `FriendState`,幂等可重跑),经 `OnlineFriendOptions.MigrateLegacyFriendData` 开关触发(默认关闭)。 +- 移出原因:能力包禁止依赖玩法层(`GameFrameX.Apps`)与数据实现(`GameFrameX.DataBase`);旧好友状态已随旧链退役,无存量生产数据可迁。 +- 依赖形态:编译需 `GameFrameX.Apps.Player.Friend.Entity`、`GameFrameX.Apps.ServerRole.Friend.Entity` 与 `GameFrameX.DataBase.GameDb` 静态门面;如需复用,建议以独立迁移工具工程承载,不回能力包。 From 3adf31380040e87e45acf646f261cfa819d08279 Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 15:35:26 +0800 Subject: [PATCH 03/13] =?UTF-8?q?feat(online-match):=20=E6=8B=86=E9=99=A4?= =?UTF-8?q?=E4=BC=9A=E8=AF=9D=E4=B8=8E=E5=8D=8F=E8=AE=AE=E4=BE=9D=E8=B5=96?= =?UTF-8?q?=E5=B9=B6=E5=A4=B9=E5=85=B7=E5=8C=96=E6=A0=B7=E4=BE=8B=E7=8E=A9?= =?UTF-8?q?=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 撮合成立推送改经出站契约 IOnlineMatchAssignmentNotifier(协议无关 DTO + 包内空实现缺省,宿主注入真实投递),能力包不再引用旧链会话 (Core.Session)与协议产物(Proto);样例游戏 RPS 三文件移出能力包 至验收夹具工程 GameFrameX.Apps.Sample(test-fixture,不打包), 玩法经 OnlineMatchOptions.AddGame 由宿主注入(重复模式注册期 fail-fast),IOnlineMatchGame 增 BuildBridgeView 保密投影契约, 桥服务构造泛化并交由玩法裁决非法输入;零玩法形态不发布对局桥与 匹配域桥(最小宿主缺席态语义)。 Linear: GFX-1199 --- .../GameFrameX.Capability.Online.Match.csproj | 9 +- .../IOnlineMatchAssignmentNotifier.cs | 54 ++ .../IOnlineMatchGame.cs | 12 + ...s => NullOnlineMatchAssignmentNotifier.cs} | 44 +- ...s => OnlineMatchAssignmentNotification.cs} | 66 +- .../OnlineMatchCapabilityModule.cs | 80 +- .../OnlineMatchGameBridgeService.cs | 15 +- .../OnlineMatchOptions.cs | 38 + .../OnlineRockPaperScissorsGame.cs | 814 ------------------ .../GameFrameX.Apps.Sample.csproj | 15 + 10 files changed, 230 insertions(+), 917 deletions(-) create mode 100644 Capability/GameFrameX.Capability.Online.Match/IOnlineMatchAssignmentNotifier.cs rename Capability/GameFrameX.Capability.Online.Match/{OnlineRockPaperScissorsMove.cs => NullOnlineMatchAssignmentNotifier.cs} (66%) rename Capability/GameFrameX.Capability.Online.Match/{OnlineRockPaperScissorsState.cs => OnlineMatchAssignmentNotification.cs} (55%) delete mode 100644 Capability/GameFrameX.Capability.Online.Match/OnlineRockPaperScissorsGame.cs create mode 100644 GameFrameX.Apps.Sample/GameFrameX.Apps.Sample.csproj diff --git a/Capability/GameFrameX.Capability.Online.Match/GameFrameX.Capability.Online.Match.csproj b/Capability/GameFrameX.Capability.Online.Match/GameFrameX.Capability.Online.Match.csproj index 0b1b72c3e..f48d1bf1b 100644 --- a/Capability/GameFrameX.Capability.Online.Match/GameFrameX.Capability.Online.Match.csproj +++ b/Capability/GameFrameX.Capability.Online.Match/GameFrameX.Capability.Online.Match.csproj @@ -2,18 +2,15 @@ - GameFrameX.Capability.Online.Match,GFX Online 对局能力包:权威对局 Actor/同步协议/重连/幂等结算/样例玩法与撮合成功通知推送(InMemory 默认存储,描述符服务面 Override 替换)+ admin handlers(end_abnormal_match). Match capability package for the GFX Online family: authoritative match actor, sync protocol, reconnect, idempotent settlement, the sample game and the match-made notification push with in-memory default stores and admin handlers. Documentation: https://gameframex.doc.alianblank.com + GameFrameX.Capability.Online.Match,GFX Online 对局能力包:权威对局 Actor/同步协议/重连/幂等结算/样例玩法与撮合成立通知出站端口(InMemory 默认存储,描述符服务面 Override 替换)+ admin handlers(end_abnormal_match). Match capability package for the GFX Online family: authoritative match actor, sync protocol, reconnect, idempotent settlement, the sample game and the match-made notification outbound port with in-memory default stores and admin handlers. Documentation: https://gameframex.doc.alianblank.com GameFrameX,Capability,Online,Match,Authoritative,Settlement,Reconnect,GameServer - + - - diff --git a/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchAssignmentNotifier.cs b/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchAssignmentNotifier.cs new file mode 100644 index 000000000..9c1c72f12 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchAssignmentNotifier.cs @@ -0,0 +1,54 @@ +// ========================================================================================== +// 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 related 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 see 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 legitimate 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 System.Threading; +using System.Threading.Tasks; + +namespace GameFrameX.Capability.Online.Match; + +/// +/// 撮合成立通知的出站端口:把「撮合已成立、对局已就位」的事实交给宿主侧投递实现 +/// (会话通道与协议消息形态由宿主决定),能力包自身不依赖任何旧链会话设施与协议产物。 +/// +/// 维护约束:包内缺省为 (静默丢弃), +/// 宿主经运行时装配覆盖注入真实投递,覆盖恒胜出缺省;实现方对离线 / 无通道成员静默跳过 +/// (best-effort,等待方经状态轮询兜底),投递异常按调用方既有批次隔离路径外抛。 +/// +/// +public interface IOnlineMatchAssignmentNotifier +{ + /// + /// 向通知载荷内的全部成员投递撮合成立通知(best-effort;离线成员静默跳过)。 + /// + /// 撮合成立通知载荷(协议无关)。 + /// 停止取消令牌。 + /// 投递任务。 + Task NotifyAssignmentCreatedAsync(OnlineMatchAssignmentNotification notification, CancellationToken cancellationToken); +} diff --git a/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchGame.cs b/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchGame.cs index c2a7ad8ff..592839d93 100644 --- a/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchGame.cs +++ b/Capability/GameFrameX.Capability.Online.Match/IOnlineMatchGame.cs @@ -27,6 +27,8 @@ // Official documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== +using GameFrameX.Capability.Online.Abstractions.Contracts; + namespace GameFrameX.Capability.Online.Match; /// @@ -95,6 +97,16 @@ public interface IOnlineMatchGame /// 已分出结果返回 true。 bool IsCompleted(OnlineMatch match); + /// + /// 产出对局桥视图(保密投影:玩法私有字段由玩法自行裁剪,桥服务不拼装玩法字段; + /// 样例桥 IOnlineMatchGameBridge 的查询 / 提交 / 开局回执一律经本投影产出)。 + /// + /// 房间标识(对局标识派生源之一)。 + /// 对局快照。 + /// 增量事件(重连补发面)。 + /// 保密投影后的对局桥视图。 + OnlineMatchBridgeGameView BuildBridgeView(long roomId, OnlineMatchSnapshot snapshot, IReadOnlyList events); + /// /// 产出权威结算结果(仅在 为 true 时调用)。 /// diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineRockPaperScissorsMove.cs b/Capability/GameFrameX.Capability.Online.Match/NullOnlineMatchAssignmentNotifier.cs similarity index 66% rename from Capability/GameFrameX.Capability.Online.Match/OnlineRockPaperScissorsMove.cs rename to Capability/GameFrameX.Capability.Online.Match/NullOnlineMatchAssignmentNotifier.cs index 536bc9cc8..230fad986 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineRockPaperScissorsMove.cs +++ b/Capability/GameFrameX.Capability.Online.Match/NullOnlineMatchAssignmentNotifier.cs @@ -27,26 +27,38 @@ // Official documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== + +using System.Threading; +using System.Threading.Tasks; + namespace GameFrameX.Capability.Online.Match; /// -/// 石头剪刀布出拳(取值与现网客户端契约 RockPaperScissors_410.RockPaperScissorsGesture 一致)。 -/// -/// 维护约束(红线):客户端只提交**意图**(本枚举值),服务端负责判定胜负并产生结果—— -/// 客户端不得提交任何比分、胜负或奖励字段。 -/// +/// 撮合成立通知的空实现(包内缺省:不投递任何消息——等待方经状态轮询兜底; +/// 宿主经运行时装配覆盖注入真实投递实现,覆盖恒胜出本缺省)。 /// -public enum OnlineRockPaperScissorsMove +public sealed class NullOnlineMatchAssignmentNotifier : IOnlineMatchAssignmentNotifier { - /// 未出拳(未结算前对外一律呈现为该值)。 - None = 0, - - /// 石头。 - Rock = 1, + /// + /// 静态缺省实例(无状态)。 + /// + public static readonly NullOnlineMatchAssignmentNotifier Instance = new NullOnlineMatchAssignmentNotifier(); - /// 剪刀。 - Scissors = 2, + /// + /// 私有构造(单例)。 + /// + private NullOnlineMatchAssignmentNotifier() + { + } - /// 布。 - Paper = 3, -} \ No newline at end of file + /// + /// 静默丢弃撮合成立通知(不投递)。 + /// + /// 通知载荷(忽略)。 + /// 取消令牌(忽略)。 + /// 已完成的任务。 + public Task NotifyAssignmentCreatedAsync(OnlineMatchAssignmentNotification notification, CancellationToken cancellationToken) + { + return Task.CompletedTask; + } +} diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineRockPaperScissorsState.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchAssignmentNotification.cs similarity index 55% rename from Capability/GameFrameX.Capability.Online.Match/OnlineRockPaperScissorsState.cs rename to Capability/GameFrameX.Capability.Online.Match/OnlineMatchAssignmentNotification.cs index 4d32a0957..a6b1daeb6 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineRockPaperScissorsState.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchAssignmentNotification.cs @@ -27,64 +27,50 @@ // Official documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== +using System; using System.Collections.Generic; namespace GameFrameX.Capability.Online.Match; /// -/// 石头剪刀布玩法状态(序列化后存于 )。 +/// 撮合成立通知的出站契约载荷(协议无关 DTO):对局数值标识、玩法模式与成员表。 /// -/// 维护约束(红线): 持有**未结算**的出拳, -/// 因此本状态的序列化结果属于服务端内部数据——不得原样下发给客户端(否则对手可在结算前窥屏)。 -/// 客户端可见的出拳只出现在已结算的 RoundResolved 事件载荷中(未结算前对外为 None)。 +/// 维护约束:本类型只承载能力包已裁决的事实(解析成功的撮合结果),不携带任何具体协议形态—— +/// 协议消息(如 NotifyMatchMade)由宿主实现方按自身协议产物组装,能力包不依赖协议工程。 /// /// -public sealed class OnlineRockPaperScissorsState +public sealed class OnlineMatchAssignmentNotification { /// - /// 获取或设置当前局数(从 1 开始)。 + /// 初始化撮合成立通知载荷。 /// - public int Round { get; set; } + /// 对局数值标识(域服务解析所得)。 + /// 玩法模式标识。 + /// 本局成员表(至少一人)。 + public OnlineMatchAssignmentNotification(long matchId, int mode, IReadOnlyList playerIds) + { + if (playerIds == null || playerIds.Count == 0) + { + throw new ArgumentException("撮合成立通知必须携带至少一名成员。", nameof(playerIds)); + } - /// - /// 获取或设置上一局胜者(平局为 0)。 - /// - public long WinnerPlayerId { get; set; } + MatchId = matchId; + Mode = mode; + PlayerIds = playerIds; + } /// - /// 获取或设置本局截止时刻(UTC 毫秒;0 = 未布防,由 布防)。 + /// 获取对局数值标识。 /// - public long RoundDeadlineTime { get; set; } + public long MatchId { get; } /// - /// 获取或设置玩家状态集合。 + /// 获取玩法模式标识。 /// - public List Players { get; set; } + public int Mode { get; } /// - /// 单玩家玩法状态。 + /// 获取本局成员表。 /// - public sealed class OnlineRockPaperScissorsPlayerState - { - /// - /// 获取或设置玩家标识。 - /// - public long PlayerId { get; set; } - - /// - /// 获取或设置已胜局数。 - /// - public int Wins { get; set; } - - /// - /// 获取或设置本局出拳( = 未出拳)。 - /// - public OnlineRockPaperScissorsMove Gesture { get; set; } - - /// - /// 获取或设置累计有效出拳次数(跨局累计;参与奖资格判定依据——任意玩家为 0 时结算抑制全部参与奖)。 - /// 唯一写入点是 接受合法出拳;每局结算不清零。 - /// - public int ValidGestureCount { get; set; } - } -} \ No newline at end of file + public IReadOnlyList PlayerIds { get; } +} diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs index 103fe76af..ca3fea4f9 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs @@ -34,14 +34,12 @@ using GameFrameX.Capability.Online.Abstractions.Events; using GameFrameX.Capability.Online.Assets; using GameFrameX.Capability.Online.Match.AdminApi; -using GameFrameX.Core.Session; using GameFrameX.Localization; -using GameFrameX.Proto.Proto; namespace GameFrameX.Capability.Online.Match; /// -/// 对局能力(权威对局 Actor / 重连 / 幂等结算 / 样例玩法)的自装配模块(C232 P4 迁入,C294 改写三段生命周期)。 +/// 对局能力(权威对局 Actor / 重连 / 幂等结算 / 玩法注册面)的自装配模块(C232 P4 迁入,C294 改写三段生命周期)。 /// /// 维护约束(服务共享协议):模块无参构造(扫描可发现);Register 自装配本域——对局 Actor / 结果 /// 两个 store 走「懒默认注册 + 解析」替换缝(族 / 宿主 Override 恒胜出);Options 经 @@ -51,6 +49,8 @@ namespace GameFrameX.Capability.Online.Match; /// 撮合成功通知订阅迁 Register 期机制事件总线(域服务在场才订阅并持有退订句柄): /// 订阅体只入队不做异步 I/O,通知由 match-assignment-notification-tick 任务异步推送(C407); /// 停用收口 = 关闭入队 + 退订 + 清空待处理 + 等待在途,返回后旧模块零通知。 +/// 玩法经 由宿主 Configure 回调注入(能力包零具体玩法; +/// 零玩法形态 = 运行时与结算管线照常、桥与域服务不装配——最小宿主语义)。 /// /// /// @@ -86,7 +86,7 @@ public sealed class OnlineMatchCapabilityModule : ICapabilityModule, IAdminActio typeof(OnlineMatchOptions)); /// - /// 对局运行时(Register 期构造;样例玩法随迁移注册,与壳时代装配语句逐语句等价)。 + /// 对局运行时(Register 期构造;Options 注册的玩法逐个注册进运行时玩法表)。 /// private OnlineMatchRuntime _matchRuntime; @@ -106,6 +106,11 @@ public sealed class OnlineMatchCapabilityModule : ICapabilityModule, IAdminActio /// private IOnlineMatchDomain _matchDomain; + /// + /// 撮合成立通知出站端口(Register 期解析;包内缺省空实现,宿主 Override 注入真实投递恒胜出)。 + /// + private IOnlineMatchAssignmentNotifier _assignmentNotifier; + /// /// 撮合通知收口闸(保护 / / )。 /// @@ -174,30 +179,46 @@ public void Register(CapabilityRegistrationContext context) context.AddService(_ => settlementStoreInstance); var matchSettlementStore = context.GetService(); - var rpsGame = new OnlineRockPaperScissorsGame(); + // 玩法来自宿主 Configure 回调(能力包零具体玩法;样例游戏在验收夹具层): + // 逐个注册进运行时;首个注册游戏承载样例桥 / 匹配域入场(单玩法样例期口径, + // 泛化随匹配域收敛另行裁决);零玩法 = 运行时与结算管线照常装配、桥与域服务不装配。 + IOnlineMatchGame primaryGame = null; _matchRuntime = new OnlineMatchRuntime(matchActorStore, eventPublisher, options.Runtime); - _matchRuntime.RegisterGame(rpsGame); + foreach (var game in options.GetGames()) + { + _matchRuntime.RegisterGame(game); + primaryGame ??= game; + } + context.AddService(_matchRuntime); context.AddTickJob("match-tick", ct => _matchRuntime.TickAllAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct)); - // 结算编排:settlement + 可空 dispatcher(assets 缺席仅结算、不建待发奖记录)+ outbox tick 投递;桥服务注册回共享面。 + // 结算编排:settlement + 可空 dispatcher(assets 缺席仅结算、不建待发奖记录)+ outbox tick 投递。 var grantService = context.GetOptionalService(); var settlementService = new OnlineMatchSettlementService(_matchRuntime, matchSettlementStore, eventPublisher, grantService != null); var dispatcher = grantService == null ? null : new OnlineMatchResultDispatcher(grantService); _settlementPipeline = new OnlineMatchSettlementPipeline(_matchRuntime, settlementService, matchSettlementStore, dispatcher, options.Settlement); context.AddTickJob("match-settlement-tick", ct => _settlementPipeline.TickAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct)); - _bridgeService = new OnlineMatchGameBridgeService(_matchRuntime, rpsGame); - context.AddService(_bridgeService); + if (primaryGame != null) + { + _bridgeService = new OnlineMatchGameBridgeService(_matchRuntime, primaryGame); + context.AddService(_bridgeService); + } + + // 撮合成立通知出站端口:懒默认空实现(宿主 Override 恒胜出)——能力包不依赖旧链会话 / 协议产物。 + // 与玩法 / 撮合装配解耦注册:通知链只在匹配域装配后消费本端口,注册恒置不引入条件分叉。 + context.AddService(static _ => NullOnlineMatchAssignmentNotifier.Instance); + _assignmentNotifier = context.GetService(); // 匹配域桥接票据入队 / 取消 / 状态与对局入场;撮合由匹配能力的定时任务统一驱动。 // 票据服务与票据存储按可选依赖语义解析(manifest 已声明 online-matchmaking 可选); // 在场才装配域服务并订阅撮合分配通知;缺席 = 不装配不报错——420 协议面经桥得显式失败。 var domainTickets = context.GetOptionalService(); var domainTicketStore = context.GetOptionalService(); - if (domainTickets != null && domainTicketStore != null) + if (domainTickets != null && domainTicketStore != null && primaryGame != null) { - _matchDomain = new OnlineMatchDomainService(domainTicketStore, domainTickets, _matchRuntime, rpsGame, options.Registry); + _matchDomain = new OnlineMatchDomainService(domainTicketStore, domainTickets, _matchRuntime, primaryGame, options.Registry); context.AddService(_matchDomain); _assignmentSubscription = context.Subscribe(OnlineMatchEvents.AssignmentCreated, OnAssignmentCreated); context.AddTickJob("match-assignment-notification-tick", cancellationToken => ProcessAssignmentNotificationsAsync(cancellationToken)); @@ -205,18 +226,24 @@ public void Register(CapabilityRegistrationContext context) } /// - /// 激活对局能力:始终发布对局桥;仅当匹配域服务已在注册期装配时才发布匹配域桥。 + /// 激活对局能力:玩法在场时发布对局桥(零玩法形态不发布,缺席态由桥显式失败承载); + /// 仅当匹配域服务已在注册期装配时才发布匹配域桥。 /// /// - /// Always publishes the match game bridge; publishes the match domain bridge only when the domain service was assembled during registration. + /// Publishes the match game bridge when a game is registered (the zero-game shape publishes nothing and the + /// bridge face fails explicitly); publishes the match domain bridge only when the domain service was assembled. /// /// 能力激活上下文 / Capability activation context /// 取消令牌 / Cancellation token /// 已完成的任务,激活过程为同步操作 / A completed task, as activation is synchronous public Task ActivateAsync(CapabilityActivationContext context, CancellationToken cancellationToken) { - // 桥发布迁 Activate 期(C294):对局桥恒发布;匹配域桥仅在场发布(缺席态由桥显式失败承载)。 - context.Bridges.Publish(_bridgeService); + // 桥发布迁 Activate 期(C294):对局桥仅玩法在场发布(零玩法最小宿主语义);匹配域桥仅在场发布。 + if (_bridgeService != null) + { + context.Bridges.Publish(_bridgeService); + } + if (_matchDomain != null) { context.Bridges.Publish(_matchDomain); @@ -314,7 +341,7 @@ private void OnAssignmentCreated(OnlineEvent onlineEvent) /// /// 撮合通知处理 tick 任务(C407):单轮最多取 条待处理事件, - /// 逐条经域服务解析数值对局标识并向双方在线会话 best-effort 推送 ; + /// 逐条经域服务解析数值对局标识并经出站端口交付宿主投递实现(best-effort,等待方经状态轮询兜底); /// 停用后队列已清空且入队已关闭,本轮直接返回。 /// /// 维护约束:本方法在调度器 tick 上下文执行——条目级异常记录后继续当轮剩余条目, @@ -394,8 +421,9 @@ private async Task ProcessNotificationBatchAsync(List batch, Cancel /// /// 单条撮合通知的分发(原 HandleMatchAssignmentEvent 主体,C294 迁入;C407 移除同步阻塞): - /// 域服务解析数值对局标识 → 向双方在线会话 best-effort 推送 ; - /// 过滤 / 校验失败即静默返回;离线方无会话跳过(等待方经状态轮询兜底)。 + /// 域服务解析数值对局标识 → 经出站端口 交付宿主投递实现 + /// (协议消息与会话通道由宿主决定,能力包不依赖旧链会话 / 协议产物); + /// 过滤 / 校验失败即静默返回;离线方由宿主实现 best-effort 跳过(等待方经状态轮询兜底)。 /// /// 机制事件载荷。 /// 停止取消令牌。 @@ -413,22 +441,12 @@ private async Task DispatchAssignmentNotificationAsync(OnlineEvent onlineEvent, return; } - if (resolved.Data.PlayerIds == null) + if (resolved.Data.PlayerIds == null || resolved.Data.PlayerIds.Count == 0) { return; } - var notify = new NotifyMatchMade { MatchId = resolved.Data.MatchId, Mode = resolved.Data.Mode }; - foreach (var playerId in resolved.Data.PlayerIds) - { - var session = PlayerSessionManager.Instance.GetByPlayerId(playerId); - if (session == null) - { - // 离线方静默跳过:best-effort 推送,等待方经状态轮询兜底。 - continue; - } - - await session.WriteAsync(notify).ConfigureAwait(false); - } + var notification = new OnlineMatchAssignmentNotification(resolved.Data.MatchId, resolved.Data.Mode, resolved.Data.PlayerIds); + await _assignmentNotifier.NotifyAssignmentCreatedAsync(notification, cancellationToken).ConfigureAwait(false); } } diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchGameBridgeService.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchGameBridgeService.cs index 79441b393..6c7c1dffd 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchGameBridgeService.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchGameBridgeService.cs @@ -37,7 +37,7 @@ namespace GameFrameX.Capability.Online.Match; /// 维护约束(红线):① 对局标识确定性派生(rps-s{serverId}-r{roomId}-g{round})——同房间同局号 /// 重复开局幂等复用既有对局,重启 / 重开 = 新局号新对局,旧局终态不复活;② 请求者身份一律取 /// 作用域玩家位(会话主体),请求体字段不可影响;③ 出拳保密——视图只经 -/// 保密投影产出,本服务不拼装玩法字段; +/// 玩法 保密投影产出,本服务不拼装玩法字段; /// ④ Ack 拒绝一律映射为段化错误码返回,不抛未分类异常。 /// /// @@ -60,14 +60,14 @@ public sealed class OnlineMatchGameBridgeService : IOnlineMatchGameBridge private readonly OnlineMatchRuntime _runtime; /// 样例玩法(视图保密投影属主)。 - private readonly OnlineRockPaperScissorsGame _game; + private readonly IOnlineMatchGame _game; /// /// 初始化对局桥服务。 /// /// 对局运行时。 /// 样例玩法。 - public OnlineMatchGameBridgeService(OnlineMatchRuntime runtime, OnlineRockPaperScissorsGame game) + public OnlineMatchGameBridgeService(OnlineMatchRuntime runtime, IOnlineMatchGame game) { _runtime = runtime ?? throw new ArgumentNullException(nameof(runtime)); _game = game ?? throw new ArgumentNullException(nameof(game)); @@ -129,7 +129,7 @@ public async Task> StartRoomGameAsync(On } /// - /// 提交石头剪刀布出拳:作用域缺失或无玩家标识返回 ScopeMissing,出拳越界返回 ParameterInvalid,对局不存在返回 ResourceNotFound; + /// 提交出拳意图:作用域缺失或无玩家标识返回 ScopeMissing,非法出拳由玩法裁决拒绝(越界值经 ApplyInput 映射为段化拒绝码),对局不存在返回 ResourceNotFound; /// 客户端序号由服务端按快照中该成员的最后序号加一派生;提交失败透传失败码,未返回确认返回 InternalError,被拒绝时映射拒绝原因,成功返回对局视图。 /// /// @@ -149,11 +149,6 @@ public async Task> SubmitGestureAsync(On return Fail(OnlineErrorCode.ScopeMissing, "作用域缺失或缺少玩家标识"); } - if (gesture < (int)OnlineRockPaperScissorsMove.Rock || gesture > (int)OnlineRockPaperScissorsMove.Paper) - { - return Fail(OnlineErrorCode.ParameterInvalid, "非法出拳"); - } - var matchId = DeriveMatchId(scope.ServerId, roomId, round); var actor = await _runtime.ResolveActorAsync(matchId, cancellationToken).ConfigureAwait(false); if (actor == null) @@ -295,7 +290,7 @@ private async Task> ResolveOrCreateActorAsync(Onl ServerId = scope.ServerId, MatchId = matchId, AssignmentId = BuildAssignmentId(scope.ServerId, roomId), - Mode = OnlineRockPaperScissorsGame.MatchMode, + Mode = _game.Mode, Region = 1, CreatedAtTime = now, TicketIds = new List(), diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchOptions.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchOptions.cs index 793b4c9fe..fe41c860d 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchOptions.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchOptions.cs @@ -28,6 +28,7 @@ // ========================================================================================== using GameFrameX.Capability.Hosting.Abstractions; +using System.Collections.Generic; namespace GameFrameX.Capability.Online.Match; @@ -63,6 +64,43 @@ public sealed class OnlineMatchOptions : ICapabilityOptions /// public OnlineMatchRegistryOptions Registry { get; set; } = new OnlineMatchRegistryOptions(); + /// + /// 已注册玩法表(宿主经 在 Configure 回调注入——能力包自身不携带任何具体玩法, + /// 样例游戏在验收夹具层)。私有字段 + 方法面暴露:玩法实例不参与配置合并,也不进入 + /// list_capability_settings 观测面(玩法不是可配置参数)。 + /// + private readonly List _games = new List(); + + /// + /// 注册一个玩法(Configure 回调入口)。每个 至多一个实现—— + /// 重复模式在注册期 fail-fast(装配期暴露配置错误,不留静默覆盖窗口); + /// 零注册 = 对局能力以零玩法形态装配(运行时与结算管线在场,但无对局可开——最小宿主语义)。 + /// + /// 玩法实现。 + public void AddGame(IOnlineMatchGame game) + { + if (game == null) + { + throw new System.ArgumentNullException(nameof(game)); + } + + if (_games.Exists(registered => registered.Mode == game.Mode)) + { + throw new System.ArgumentException("同一玩法模式已注册(Mode=" + game.Mode + "):每个模式至多一个实现。", nameof(game)); + } + + _games.Add(game); + } + + /// + /// 获取已注册玩法的只读快照(模块 Register 期取用)。 + /// + /// 玩法只读列表。 + public System.Collections.Generic.IReadOnlyList GetGames() + { + return _games; + } + /// /// 校验合并后的运行时与结算阈值与登记表清扫参数:等待超时、进行中超时、重连窗口、结束留存时长、单局服务端事件上限、 /// 发奖投递尝试上限、分配登记生命周期与清扫节流间隔均须为正数。 diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineRockPaperScissorsGame.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineRockPaperScissorsGame.cs deleted file mode 100644 index 7e367c75f..000000000 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineRockPaperScissorsGame.cs +++ /dev/null @@ -1,814 +0,0 @@ -// ========================================================================================== -// 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 related 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 see 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 legitimate 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 System.Collections.Generic; -using System.Text.Json; -using GameFrameX.Capability.Online.Abstractions.Contracts; -using GameFrameX.Capability.Online.Assets; - -namespace GameFrameX.Capability.Online.Match; - -/// -/// 石头剪刀布样例玩法(使用石头剪刀布或小型回合制玩法作为第一版样例)。 -/// -/// 规则:两人对局,三局两胜(先得 局者胜,最多 局); -/// 每局双方各提交一次出拳,服务端判定胜负;单局无人出拳则本局作废。 -/// 单局超时()由服务端按规则推进:已出拳方判该局胜,双方均未出拳则本局作废—— -/// 这使「玩家不做操作」也收敛到确定结果,而非永久挂起。 -/// 参与奖资格红线:任意一方全程零有效出拳(挂机)时,结算抑制全部非胜方参与奖(胜方奖励不受影响)。 -/// -/// -/// 维护约束(红线):本类不做任何鉴权与身份判定(由 Actor 负责),也不产出 MatchResultId -/// (由结算服务统一分配)——玩法只回答「这一手合法吗、现在谁赢了」。 -/// -/// -public sealed class OnlineRockPaperScissorsGame : IOnlineMatchGame -{ - /// 模式标识(与现网客户端契约 _0410_RockPaperScissors 对齐)。 - public const int MatchMode = 410; - - /// 获胜所需局数。 - public const int WinTarget = 2; - - /// 最大局数(先胜 局即终局)。 - public const int MaxRounds = WinTarget * 2 - 1; - - /// 单局时限(毫秒)。 - public const long RoundTimeoutMilliseconds = 30000L; - - /// 样例奖励资产标识。 - public const string RewardAssetId = "sample-coin"; - - /// 胜方奖励数量。 - public const long WinnerRewardAmount = 100L; - - /// 参与奖数量(负方与平局发放;前提是双方均有有效出拳——任意一方零出拳时整场抑制,防挂机刷奖)。 - public const long ParticipantRewardAmount = 10L; - - /// 出拳提交事件。 - private const string GestureSubmittedEventType = "GestureSubmitted"; - - /// 单局结算事件。 - private const string RoundResolvedEventType = "RoundResolved"; - - /// - /// 获取模式标识。 - /// - public int Mode - { - get { return MatchMode; } - } - - /// - /// 获取最小玩家数。 - /// - public int MinPlayers - { - get { return 2; } - } - - /// - /// 获取最大玩家数。 - /// - public int MaxPlayers - { - get { return 2; } - } - - /// - /// 构造初始玩法状态:为全部在局成员建计分位,进入第 1 局。 - /// - /// 对局。 - /// 序列化后的初始状态。 - public byte[] CreateInitialState(OnlineMatch match) - { - var state = new OnlineRockPaperScissorsState - { - Round = 1, - WinnerPlayerId = 0, - RoundDeadlineTime = 0, - Players = new List(), - }; - - if (match.Members != null) - { - foreach (var member in match.Members) - { - if (member == null || member.State == OnlineMatchMemberState.Left || member.State == OnlineMatchMemberState.Kicked) - { - continue; - } - - state.Players.Add(new OnlineRockPaperScissorsState.OnlineRockPaperScissorsPlayerState - { - PlayerId = member.PlayerId, - Wins = 0, - Gesture = OnlineRockPaperScissorsMove.None, - ValidGestureCount = 0, - }); - } - } - - return Serialize(state); - } - - /// - /// 处理一次出拳意图(只接受本局未出拳的成员;出拳值非契约枚举一律拒绝)。 - /// - /// 对局。 - /// 提交成员(身份已由 Actor 校验)。 - /// 输入意图( = 出拳值)。 - /// 处理结果。 - public OnlineMatchGameStepResult ApplyInput(OnlineMatch match, OnlineMatchMember member, OnlineMatchInput input) - { - var state = Deserialize(match.GameState); - if (state == null || state.Players == null || state.Players.Count == 0) - { - return Reject(OnlineMatchInputRejection.IllegalAction, "对局状态不可用"); - } - - var me = FindPlayer(state, member.PlayerId); - if (me == null) - { - return Reject(OnlineMatchInputRejection.NotMember, "玩家不在本局计分表中"); - } - - if (!IsGestureValid(input.ActionId)) - { - return Reject(OnlineMatchInputRejection.IllegalAction, "非法出拳"); - } - - if (me.Gesture != OnlineRockPaperScissorsMove.None) - { - return Reject(OnlineMatchInputRejection.Duplicate, "本局已提交过出拳"); - } - - me.Gesture = (OnlineRockPaperScissorsMove)input.ActionId; - me.ValidGestureCount += 1; - - var submittedCount = 0; - foreach (var player in state.Players) - { - if (player.Gesture != OnlineRockPaperScissorsMove.None) - { - submittedCount++; - } - } - - var emittedEvents = new List - { - BuildEvent(GestureSubmittedEventType, new GestureSubmittedPayload - { - Round = state.Round, - PlayerId = member.PlayerId, - SubmittedCount = submittedCount, - PlayerCount = state.Players.Count, - }), - }; - - if (submittedCount >= state.Players.Count) - { - emittedEvents.Add(BuildEvent(RoundResolvedEventType, SettleRound(state, ResolveWinner(state), false))); - } - - return new OnlineMatchGameStepResult - { - Accepted = true, - Rejection = OnlineMatchInputRejection.None, - GameState = Serialize(state), - ServerEvents = emittedEvents, - Message = "已接受", - }; - } - - /// - /// 时间推进:布防回合时钟;到点按超时规则判定本局(已出拳方胜,双方未出拳则本局作废)。 - /// - /// 对局。 - /// 当前时刻(UTC 毫秒)。 - /// 本次推进要追加的服务器事件。 - /// 状态是否被改写。 - public bool Advance(OnlineMatch match, long nowUnixMilliseconds, List emittedEvents) - { - var state = Deserialize(match.GameState); - if (state == null || state.Players == null || state.Players.Count == 0) - { - return false; - } - - if (state.RoundDeadlineTime == 0) - { - state.RoundDeadlineTime = nowUnixMilliseconds + RoundTimeoutMilliseconds; - match.GameState = Serialize(state); - return true; - } - - if (nowUnixMilliseconds < state.RoundDeadlineTime) - { - return false; - } - - emittedEvents.Add(BuildEvent(RoundResolvedEventType, SettleRound(state, ResolveWinner(state), true))); - match.GameState = Serialize(state); - return true; - } - - /// - /// 判定是否已分出结果(有人达到胜局数,或局数已超过上限)。 - /// - /// 对局。 - /// 已分出结果返回 true。 - public bool IsCompleted(OnlineMatch match) - { - var state = Deserialize(match.GameState); - if (state == null || state.Players == null || state.Players.Count == 0) - { - return false; - } - - if (state.Round > MaxRounds) - { - return true; - } - - foreach (var player in state.Players) - { - if (player.Wins >= WinTarget) - { - return true; - } - } - - return false; - } - - /// - /// 产出结算结果:名次按胜局数,胜方得胜方奖励、负方与平局在双方均有有效出拳时得参与奖。 - /// - /// 反刷奖规则(红线):任意一方累计有效出拳数为 0(全程挂机)时,抑制全部非胜方参与奖—— - /// 胜方奖励不受影响(胜局只能由已出拳方取得,零出拳者不可能成为胜方); - /// 结果置 供风控消费。 - /// - /// - /// 对局。 - /// 结算结果;状态缺失返回 null。 - public OnlineMatchResult BuildResult(OnlineMatch match) - { - var state = Deserialize(match.GameState); - if (state == null || state.Players == null || state.Players.Count == 0) - { - return null; - } - - var winnerPlayerId = FindWinner(state); - var participationRewardSuppressed = HasPlayerWithoutValidGesture(state); - var result = new OnlineMatchResult - { - Mode = match.Mode, - Region = match.Region, - ParticipationRewardsSuppressed = participationRewardSuppressed, - Entries = new List(), - }; - - foreach (var player in state.Players) - { - var isWinner = winnerPlayerId != 0 && player.PlayerId == winnerPlayerId; - var rewards = new List(); - if (isWinner) - { - rewards.Add(new OnlineAssetChangeLine(OnlineAssetKind.Currency, RewardAssetId, WinnerRewardAmount)); - } - else if (!participationRewardSuppressed) - { - rewards.Add(new OnlineAssetChangeLine(OnlineAssetKind.Currency, RewardAssetId, ParticipantRewardAmount)); - } - - result.Entries.Add(new OnlineMatchResultEntry - { - PlayerId = player.PlayerId, - Rank = winnerPlayerId == 0 || isWinner ? 1 : 2, - IsWinner = isWinner, - Score = player.Wins, - Rewards = rewards, - }); - } - - return result; - } - - /// - /// 构造对局桥视图(保密投影):玩法属主自行决定对外可见性—— - /// 当前局未结算一律不回显真实出拳,已结算局回显最近一次 RoundResolved 事件载荷中的真实出拳; - /// 整局胜者仅终局非 0(平局为 0)。 - /// - /// 维护约束(红线):本投影只读快照与事件流,不改写任何对局状态; - /// 终局判定复用本类规则( / ),不引入第二套判定。 - /// - /// - /// 房间标识(回显请求侧关联键)。 - /// 对局快照(权威状态切片)。 - /// 事件流(取自 Actor 增量;用于回显最近一次已结算局的真实出拳)。 - /// 桥接视图;玩法状态缺失时返回仅含生命周期状态的空投影视图。 - public OnlineMatchBridgeGameView BuildBridgeView(long roomId, OnlineMatchSnapshot snapshot, IReadOnlyList events) - { - var state = Deserialize(snapshot == null ? null : snapshot.GameState); - var view = new OnlineMatchBridgeGameView - { - RoomId = roomId, - MatchId = snapshot == null ? string.Empty : snapshot.MatchId, - Mode = snapshot == null ? MatchMode : snapshot.Mode, - State = ProjectState(snapshot == null ? OnlineMatchState.Created : snapshot.State), - Round = 1, - WinnerPlayerId = 0, - Players = new List(), - }; - - if (state == null || state.Players == null || state.Players.Count == 0) - { - return view; - } - - view.Round = state.Round; - if (IsFinal(state)) - { - view.WinnerPlayerId = FindWinner(state); - } - - var revealed = FindLatestResolvedPlays(events, state.Round); - foreach (var player in state.Players) - { - if (player == null) - { - continue; - } - - view.Players.Add(new OnlineMatchBridgePlayerView - { - PlayerId = player.PlayerId, - HasGesture = player.Gesture != OnlineRockPaperScissorsMove.None, - Wins = player.Wins, - Gesture = revealed != null && revealed.TryGetValue(player.PlayerId, out var gesture) ? (int)gesture : 0, - }); - } - - return view; - } - - /// - /// 判定玩法是否已终局(复用本类规则:局数超上限或任一玩家达到胜局数)。 - /// - /// 玩法状态。 - /// 终局返回 true。 - private static bool IsFinal(OnlineRockPaperScissorsState state) - { - if (state.Round > MaxRounds) - { - return true; - } - - foreach (var player in state.Players) - { - if (player != null && player.Wins >= WinTarget) - { - return true; - } - } - - return false; - } - - /// - /// 回显最近一次已结算局的真实出拳(仅当该局正是当前局的上一局——当前局进行中不回显任何真实出拳)。 - /// - /// 事件流。 - /// 当前局数。 - /// 玩家 → 真实出拳映射;无可回显局返回 null。 - private static Dictionary FindLatestResolvedPlays(IReadOnlyList events, int currentRound) - { - var payload = FindLatestResolvedPayload(events, currentRound); - if (payload == null) - { - return null; - } - - return CollectPlays(payload); - } - - /// - /// 倒序定位最近一次已结算局载荷:仅当其局数恰为当前局的上一局才返回; - /// 载荷解析失败或校验不通过即返回 null 终止(不再回扫更早事件)。 - /// - /// 事件流。 - /// 当前局数。 - /// 可回显的单局结算载荷;无可回显局返回 null。 - private static RoundResolvedPayload FindLatestResolvedPayload(IReadOnlyList events, int currentRound) - { - if (events == null) - { - return null; - } - - for (var index = events.Count - 1; index >= 0; index--) - { - var item = events[index]; - if (item == null || !string.Equals(item.EventType, RoundResolvedEventType, System.StringComparison.Ordinal)) - { - continue; - } - - RoundResolvedPayload payload; - try - { - payload = item.Payload == null ? null : JsonSerializer.Deserialize(item.Payload); - } - catch (JsonException) - { - return null; - } - - if (payload == null || payload.Plays == null || payload.Round != currentRound - 1) - { - return null; - } - - return payload; - } - - return null; - } - - /// - /// 将已结算局载荷中的双方出拳收集为玩家 → 出拳映射(null 出拳条目跳过)。 - /// - /// 已通过局数校验的单局结算载荷。 - /// 玩家 → 真实出拳映射。 - private static Dictionary CollectPlays(RoundResolvedPayload payload) - { - var plays = new Dictionary(); - foreach (var play in payload.Plays) - { - if (play != null) - { - plays[play.PlayerId] = play.Gesture; - } - } - - return plays; - } - - /// - /// 平台对局状态 → 桥接生命周期状态投影。 - /// - /// 平台对局状态。 - /// 桥接状态。 - private static OnlineMatchBridgeGameState ProjectState(OnlineMatchState state) - { - switch (state) - { - case OnlineMatchState.Created: - case OnlineMatchState.Waiting: - return OnlineMatchBridgeGameState.Waiting; - case OnlineMatchState.Ready: - return OnlineMatchBridgeGameState.Ready; - case OnlineMatchState.Running: - return OnlineMatchBridgeGameState.Running; - case OnlineMatchState.Settling: - return OnlineMatchBridgeGameState.Settling; - case OnlineMatchState.Completed: - return OnlineMatchBridgeGameState.Completed; - case OnlineMatchState.SettlementFailed: - return OnlineMatchBridgeGameState.SettlementFailed; - default: - return OnlineMatchBridgeGameState.Terminated; - } - } - - /// - /// 解析本局胜负:仅出一拳者胜;两拳相同为平局;否则按克制关系判定。 - /// - /// 玩法状态。 - /// 胜者玩家标识;平局或无法判定返回 0。 - private static long ResolveWinner(OnlineRockPaperScissorsState state) - { - if (state.Players.Count < 2) - { - return 0; - } - - var first = state.Players[0]; - var second = state.Players[1]; - - if (first.Gesture == OnlineRockPaperScissorsMove.None && second.Gesture == OnlineRockPaperScissorsMove.None) - { - return 0; - } - - if (first.Gesture == OnlineRockPaperScissorsMove.None) - { - return second.PlayerId; - } - - if (second.Gesture == OnlineRockPaperScissorsMove.None) - { - return first.PlayerId; - } - - if (first.Gesture == second.Gesture) - { - return 0; - } - - return Beats(first.Gesture, second.Gesture) ? first.PlayerId : second.PlayerId; - } - - /// - /// 收束本局:计分、清空出拳、进入下一局(并解除回合时钟布防)。 - /// - /// 玩法状态。 - /// 本局胜者(0 = 平局)。 - /// 是否由超时触发。 - /// 本局结算事件载荷。 - private static RoundResolvedPayload SettleRound(OnlineRockPaperScissorsState state, long winnerPlayerId, bool timedOut) - { - var resolvedRound = state.Round; - var plays = new List(); - var scores = new List(); - foreach (var player in state.Players) - { - plays.Add(new RoundPlayPayload - { - PlayerId = player.PlayerId, - Gesture = player.Gesture, - }); - - if (winnerPlayerId != 0 && player.PlayerId == winnerPlayerId) - { - player.Wins++; - } - } - - state.WinnerPlayerId = winnerPlayerId; - state.Round = resolvedRound + 1; - state.RoundDeadlineTime = 0; - - foreach (var player in state.Players) - { - scores.Add(new RoundScorePayload - { - PlayerId = player.PlayerId, - Wins = player.Wins, - }); - - player.Gesture = OnlineRockPaperScissorsMove.None; - } - - return new RoundResolvedPayload - { - Round = resolvedRound, - WinnerPlayerId = winnerPlayerId, - TimedOut = timedOut, - Plays = plays, - Scores = scores, - }; - } - - /// - /// 判定是否存在零有效出拳玩家(全程挂机——参与奖抑制条件)。 - /// - /// 玩法状态。 - /// 存在零出拳玩家返回 true。 - private static bool HasPlayerWithoutValidGesture(OnlineRockPaperScissorsState state) - { - foreach (var player in state.Players) - { - if (player == null || player.ValidGestureCount == 0) - { - return true; - } - } - - return false; - } - - /// - /// 判定胜负并返回胜者标识(平局返回 0)。 - /// - /// 玩法状态。 - /// 胜者玩家标识;平局返回 0。 - private static long FindWinner(OnlineRockPaperScissorsState state) - { - long winnerPlayerId = 0; - var bestWins = -1; - var bestCount = 0; - foreach (var player in state.Players) - { - if (player.Wins > bestWins) - { - bestWins = player.Wins; - winnerPlayerId = player.PlayerId; - bestCount = 1; - } - else if (player.Wins == bestWins) - { - bestCount++; - } - } - - return bestCount > 1 || bestWins <= 0 ? 0 : winnerPlayerId; - } - - /// - /// 判定出拳值是否在契约枚举范围内。 - /// - /// 出拳值。 - /// 合法返回 true。 - private static bool IsGestureValid(int actionId) - { - return actionId >= (int)OnlineRockPaperScissorsMove.Rock && actionId <= (int)OnlineRockPaperScissorsMove.Paper; - } - - /// - /// 判定 是否克制 。 - /// - /// 左方出拳。 - /// 右方出拳。 - /// 左方胜返回 true。 - private static bool Beats(OnlineRockPaperScissorsMove left, OnlineRockPaperScissorsMove right) - { - return (left == OnlineRockPaperScissorsMove.Rock && right == OnlineRockPaperScissorsMove.Scissors) - || (left == OnlineRockPaperScissorsMove.Scissors && right == OnlineRockPaperScissorsMove.Paper) - || (left == OnlineRockPaperScissorsMove.Paper && right == OnlineRockPaperScissorsMove.Rock); - } - - /// - /// 在计分表中查找玩家。 - /// - /// 玩法状态。 - /// 玩家标识。 - /// 玩家状态;不存在返回 null。 - private static OnlineRockPaperScissorsState.OnlineRockPaperScissorsPlayerState FindPlayer(OnlineRockPaperScissorsState state, long playerId) - { - foreach (var player in state.Players) - { - if (player.PlayerId == playerId) - { - return player; - } - } - - return null; - } - - /// - /// 构造拒绝结果。 - /// - /// 拒绝原因。 - /// 说明。 - /// 处理结果。 - private static OnlineMatchGameStepResult Reject(OnlineMatchInputRejection rejection, string message) - { - return new OnlineMatchGameStepResult - { - Accepted = false, - Rejection = rejection, - Message = message, - }; - } - - /// - /// 构造服务器事件(序号与发生时刻由 Actor 统一分配)。 - /// - /// 载荷类型。 - /// 事件类型。 - /// 载荷。 - /// 服务器事件。 - private static OnlineMatchServerEvent BuildEvent(string eventType, TPayload payload) - { - return new OnlineMatchServerEvent - { - EventType = eventType, - Payload = JsonSerializer.SerializeToUtf8Bytes(payload), - }; - } - - /// - /// 序列化玩法状态。 - /// - /// 玩法状态。 - /// 字节数组。 - private static byte[] Serialize(OnlineRockPaperScissorsState state) - { - return JsonSerializer.SerializeToUtf8Bytes(state); - } - - /// - /// 反序列化玩法状态。 - /// - /// 字节数组。 - /// 玩法状态;为空或损坏返回 null。 - private static OnlineRockPaperScissorsState Deserialize(byte[] gameState) - { - if (gameState == null || gameState.Length == 0) - { - return null; - } - - try - { - return JsonSerializer.Deserialize(gameState); - } - catch (JsonException) - { - return null; - } - } - - /// - /// 出拳提交事件负载(不含出拳值——未结算前不得泄露,防窥屏)。 - /// - private sealed class GestureSubmittedPayload - { - /// 当前局数。 - public int Round { get; set; } - - /// 提交者玩家标识。 - public long PlayerId { get; set; } - - /// 本局已提交人数。 - public int SubmittedCount { get; set; } - - /// 本局参与人数。 - public int PlayerCount { get; set; } - } - - /// - /// 单局结算事件负载(已结算,故可携带真实出拳)。 - /// - private sealed class RoundResolvedPayload - { - /// 被结算的局数。 - public int Round { get; set; } - - /// 本局胜者(0 = 平局)。 - public long WinnerPlayerId { get; set; } - - /// 是否由超时触发。 - public bool TimedOut { get; set; } - - /// 本局双方出拳。 - public List Plays { get; set; } - - /// 结算后的累计胜局。 - public List Scores { get; set; } - } - - /// - /// 单局出拳负载。 - /// - private sealed class RoundPlayPayload - { - /// 玩家标识。 - public long PlayerId { get; set; } - - /// 出拳。 - public OnlineRockPaperScissorsMove Gesture { get; set; } - } - - /// - /// 结算后计分负载。 - /// - private sealed class RoundScorePayload - { - /// 玩家标识。 - public long PlayerId { get; set; } - - /// 累计胜局。 - public int Wins { get; set; } - } -} \ No newline at end of file diff --git a/GameFrameX.Apps.Sample/GameFrameX.Apps.Sample.csproj b/GameFrameX.Apps.Sample/GameFrameX.Apps.Sample.csproj new file mode 100644 index 000000000..747fdf17a --- /dev/null +++ b/GameFrameX.Apps.Sample/GameFrameX.Apps.Sample.csproj @@ -0,0 +1,15 @@ + + + + + false + GameFrameX.Apps.Sample,RPS(石头剪刀布)验收夹具玩法:对局能力的样例游戏实现(协议裁决/回合推进/保密投影),供宿主组合根与测试装配(test-fixture,非产品示例)。 The rock-paper-scissors acceptance-fixture game for the online match capability: server-side adjudication, round advancement and secrecy projection wired by host composition roots and tests. Documentation: https://gameframex.doc.alianblank.com + GameFrameX,Sample,Fixture,Match,Game,GameServer + + + + + + + From 54ae7dcb3ee7ea507b3b1104b2877db7f874f800 Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 15:35:36 +0800 Subject: [PATCH 04/13] =?UTF-8?q?feat(online-leaderboard):=20=E6=8B=86?= =?UTF-8?q?=E6=8E=92=E8=A1=8C=E6=A6=9C=E7=8B=AC=E7=AB=8B=E5=8C=85=E5=B9=B6?= =?UTF-8?q?=E5=86=BB=E7=BB=93=E7=AB=9E=E6=8A=80=E4=B8=8E=E8=BF=90=E8=90=A5?= =?UTF-8?q?=E5=88=86=E6=9E=90=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 排行榜域 28 文件、admin 查询 handler 与 OnlineCompetitionOptions 自竞技包拆出独立能力包(新模块 online-leaderboard,query_leaderboard 随迁,Match.Settled 投影与默认榜预建随模块迁移,配置段改 Online.Settings.online-leaderboard);竞技包保留冻结的赛季/锦标赛 (必选依赖 online-leaderboard,manifest 剔除 LiveOps 七 action); LiveOps 运营面五文件拆离存档 scripts/detached-liveops/ 移交 Admin 仓;运营包分析面(游戏事件/总览/时间线)原地冻结标注。宿主接线: Launcher 直引新包并注入 RPS 夹具玩法与撮合成立通知投递实现;模板 新增 Leaderboard 开关、Competition 隐含其必选引用并显式引 Hosting.AdminApi;slnx 分组 Standard/Frozen/Experimental 与 Fixture。 BREAKING CHANGE: Online.Settings.online-competition.* 配置段废止(改 online-leaderboard 或删除,绑定器严格 fail-fast);admin 业务 action 37→30。 Linear: GFX-1199 --- .../OnlineAdminLeaderboardHandlers.cs | 183 ------ .../AdminApi/OnlineAdminLiveOpsHandlers.cs | 403 ------------ ...rameX.Capability.Online.Competition.csproj | 12 +- .../Leaderboard/IOnlineLeaderboardStore.cs | 110 ---- .../InMemoryOnlineLeaderboardStore.cs | 401 ------------ .../Leaderboard/OnlineLeaderboard.cs | 82 --- .../OnlineLeaderboardApplyResult.cs | 55 -- .../OnlineLeaderboardAroundQuery.cs | 67 -- .../OnlineLeaderboardAroundView.cs | 62 -- .../OnlineLeaderboardCreateRequest.cs | 60 -- .../Leaderboard/OnlineLeaderboardEntry.cs | 88 --- .../Leaderboard/OnlineLeaderboardEntryView.cs | 65 -- .../Leaderboard/OnlineLeaderboardEvents.cs | 187 ------ .../Leaderboard/OnlineLeaderboardOptions.cs | 71 --- .../Leaderboard/OnlineLeaderboardOrdering.cs | 114 ---- .../Leaderboard/OnlineLeaderboardPage.cs | 58 -- .../OnlineLeaderboardProjectionFailure.cs | 54 -- .../OnlineLeaderboardProjectionOptions.cs | 49 -- .../OnlineLeaderboardProjectionOutcome.cs | 69 --- .../OnlineLeaderboardProjectionRetryStatus.cs | 57 -- .../OnlineLeaderboardRateLimiter.cs | 186 ------ .../OnlineLeaderboardResultProjector.cs | 244 -------- .../OnlineLeaderboardScoreSource.cs | 45 -- .../OnlineLeaderboardScoreSubmission.cs | 66 -- .../OnlineLeaderboardScoreUpdatePolicy.cs | 56 -- .../Leaderboard/OnlineLeaderboardService.cs | 577 ------------------ .../Leaderboard/OnlineLeaderboardSortOrder.cs | 50 -- .../OnlineLeaderboardWriteOutcome.cs | 65 -- .../OnlineMatchSettledLeaderboardProjector.cs | 371 ----------- .../LiveOps/OnlineLiveOpsCommand.cs | 78 --- .../LiveOps/OnlineLiveOpsEntry.cs | 60 -- .../LiveOps/OnlineLiveOpsOperation.cs | 42 -- .../LiveOps/OnlineLiveOpsRegistry.cs | 160 ----- .../OnlineCompetitionCapabilityModule.cs | 188 ++---- .../OnlineCompetitionOptions.cs | 104 ---- .../OnlineAdminLeaderboardHandlers.cs | 2 +- ...rameX.Capability.Online.Leaderboard.csproj | 19 + .../IOnlineLeaderboardStore.cs | 18 +- .../InMemoryOnlineLeaderboardStore.cs | 49 +- .../OnlineCompetitionOptions.cs | 43 +- .../OnlineLeaderboard.cs | 19 +- .../OnlineLeaderboardCapabilityModule.cs | 215 +++++++ .../OnlineLeaderboardCreateRequest.cs | 6 +- .../OnlineLeaderboardEvents.cs | 12 +- .../OnlineLeaderboardProjectionOptions.cs | 14 +- .../OnlineLeaderboardRateLimiter.cs | 10 +- .../OnlineLeaderboardResultProjector.cs | 8 +- .../OnlineLeaderboardService.cs | 24 +- .../OnlineMatchSettledLeaderboardProjector.cs | 16 +- ...FrameX.Capability.Online.Operations.csproj | 2 +- .../OnlineOperationsCapabilityModule.cs | 4 +- .../Composition/RuntimeCompositionRoot.cs | 4 + .../GameFrameX.Launcher.csproj | 2 + .../OnlineMatchAssignmentSessionNotifier.cs | 61 +- GameFrameX.Localization/Keys.Capability.cs | 14 +- .../Localization/Messages/Resources.resx | 2 +- .../Messages/Resources.zh-CN.resx | 2 +- .../gfx-online/.template.config/template.json | 10 +- .../gfx-online/{{Name}}/{{Name}}.csproj | 11 +- Server.slnx | 12 +- scripts/detached-liveops/README.md | 18 + 61 files changed, 492 insertions(+), 4644 deletions(-) delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLeaderboardHandlers.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLiveOpsHandlers.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/IOnlineLeaderboardStore.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/InMemoryOnlineLeaderboardStore.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboard.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardApplyResult.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardAroundQuery.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardAroundView.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardCreateRequest.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEntry.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEntryView.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEvents.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardOptions.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardOrdering.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardPage.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionFailure.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOutcome.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionRetryStatus.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardRateLimiter.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardResultProjector.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreSource.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreSubmission.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreUpdatePolicy.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardService.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardSortOrder.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardWriteOutcome.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineMatchSettledLeaderboardProjector.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsCommand.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsEntry.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsOperation.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsRegistry.cs delete mode 100644 Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/GameFrameX.Capability.Online.Leaderboard.csproj create mode 100644 Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCapabilityModule.cs rename Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardTopQuery.cs => GameFrameX.Launcher/Online/OnlineMatchAssignmentSessionNotifier.cs (54%) create mode 100644 scripts/detached-liveops/README.md diff --git a/Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLeaderboardHandlers.cs b/Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLeaderboardHandlers.cs deleted file mode 100644 index c4eea3308..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLeaderboardHandlers.cs +++ /dev/null @@ -1,183 +0,0 @@ -// ========================================================================================== -// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 -// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights -// 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the PRC and relevant 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.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using GameFrameX.Capability.Hosting.AdminApi; -using GameFrameX.Capability.Online.Abstractions.Contracts; -using GameFrameX.Capability.Online.Abstractions.Scope; -using GameFrameX.Capability.Online.Competition.Leaderboard; - -namespace GameFrameX.Capability.Online.Competition.AdminApi; - -/// -/// 排行榜域 admin 命令(query_leaderboard——只读榜单查询:单元信息 + Top 条目 + 可选玩家附近窗口)。 -/// -/// 维护约束:只读幂等包裹 false(无状态变更,与 query_match_settlement 同族);作用域校验失败与 -/// 榜单不存在同构 ResourceNotFound(排行榜服务反预言红线);玩家附近窗口为尽力投影(玩家未上榜时省略)。 -/// -/// -public static class OnlineAdminLeaderboardHandlers -{ - /// - /// 注册排行榜查询 action(只读)。 - /// - /// 动作注册表。 - /// 排行榜服务(Register 期构造)。 - public static void RegisterLeaderboardQuery(AdminActionRegistry registry, OnlineLeaderboardService leaderboards) - { - registry.Register("query_leaderboard", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => QueryLeaderboardAsync(request, scope, cancellationToken, leaderboards)), false); - } - - /// - /// query_leaderboard:榜单单元信息 + Top N 条目(Rank/PlayerId/Score)+ 可选 AroundPlayer 窗口。 - /// - /// 请求。 - /// 作用域。 - /// 取消令牌。 - /// 排行榜服务。 - /// 查询响应。 - private static async Task QueryLeaderboardAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLeaderboardService leaderboards) - { - var leaderboardId = OnlineAdminApiContract.RequireString(request, "LeaderboardId"); - var count = request.ReadNullableInt32("Count") ?? 10; - var playerId = request.ReadNullableInt64("PlayerId") ?? 0; - - var boardResult = await leaderboards.ResolveBoardAsync(scope, leaderboardId, cancellationToken).ConfigureAwait(false); - if (!boardResult.IsSuccess) - { - throw new OnlineServiceException(boardResult.Code, boardResult.Message); - } - - var board = boardResult.Data; - var response = new LeaderboardQueryResponse - { - LeaderboardId = board.LeaderboardId, - SortOrder = board.SortOrder.ToString(), - ScoreUpdatePolicy = board.ScoreUpdatePolicy.ToString(), - Top = new List(), - }; - - var topResult = await leaderboards.GetTopAsync(scope, new OnlineLeaderboardTopQuery { LeaderboardId = leaderboardId, Count = count }, cancellationToken).ConfigureAwait(false); - if (topResult.IsSuccess) - { - foreach (var view in topResult.Data.Entries) - { - response.Top.Add(new LeaderboardEntryResponse - { - Rank = view.Rank, - PlayerId = view.Entry.PlayerId, - Score = view.Entry.Score, - }); - } - } - - if (playerId > 0) - { - // 附近窗口为尽力投影:玩家未上榜 / 榜单异常时省略,不阻断整体查询。 - var aroundResult = await leaderboards.GetAroundPlayerAsync(scope, new OnlineLeaderboardAroundQuery { LeaderboardId = leaderboardId, PlayerId = playerId, Before = 2, After = 2 }, cancellationToken).ConfigureAwait(false); - if (aroundResult.IsSuccess) - { - response.AroundPlayer = new LeaderboardAroundResponse - { - PlayerId = aroundResult.Data.PlayerId, - Rank = aroundResult.Data.Rank, - TotalCount = (int)aroundResult.Data.TotalCount, - Around = new List(), - }; - foreach (var view in aroundResult.Data.Around) - { - response.AroundPlayer.Around.Add(new LeaderboardEntryResponse - { - Rank = view.Rank, - PlayerId = view.Entry.PlayerId, - Score = view.Entry.Score, - }); - } - } - } - - return response; - } - - /// - /// 排行榜查询响应(JSON 投影)。 - /// - public sealed class LeaderboardQueryResponse - { - /// 获取或设置榜单标识。 - public string LeaderboardId { get; set; } - - /// 获取或设置排序方向名(Descending/Ascending)。 - public string SortOrder { get; set; } - - /// 获取或设置累计策略名(Best/Sum/Latest)。 - public string ScoreUpdatePolicy { get; set; } - - /// 获取或设置 Top 条目。 - public List Top { get; set; } = new List(); - - /// 获取或设置玩家附近窗口(未请求或玩家未上榜为 null)。 - public LeaderboardAroundResponse AroundPlayer { get; set; } - } - - /// - /// 榜单条目响应(JSON 投影)。 - /// - public sealed class LeaderboardEntryResponse - { - /// 获取或设置名次。 - public int Rank { get; set; } - - /// 获取或设置玩家标识。 - public long PlayerId { get; set; } - - /// 获取或设置分数。 - public long Score { get; set; } - } - - /// - /// 玩家附近窗口响应(JSON 投影)。 - /// - public sealed class LeaderboardAroundResponse - { - /// 获取或设置玩家标识。 - public long PlayerId { get; set; } - - /// 获取或设置玩家名次。 - public int Rank { get; set; } - - /// 获取或设置榜单总条数。 - public int TotalCount { get; set; } - - /// 获取或设置窗口条目(含玩家本人)。 - public List Around { get; set; } = new List(); - } -} diff --git a/Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLiveOpsHandlers.cs b/Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLiveOpsHandlers.cs deleted file mode 100644 index 1b6bed42d..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/AdminApi/OnlineAdminLiveOpsHandlers.cs +++ /dev/null @@ -1,403 +0,0 @@ -// ========================================================================================== -// 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 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, -// 侵犯他人合法权益等法律法规所禁止的行为! -// 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://cnb.cool/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.Foundation.Json; -using GameFrameX.Foundation.Localization.Core; -using GameFrameX.Capability.Hosting.AdminApi; -using GameFrameX.Capability.Online.Abstractions.Contracts; -using GameFrameX.Capability.Online.Competition.LiveOps; -using GameFrameX.Capability.Online.Abstractions.Scope; - -namespace GameFrameX.Capability.Online.Competition.AdminApi; - -/// -/// LiveOps 域 admin 命令(publishRemoteConfig / syncDeviceGroup / syncScheduledTask / pushAnnouncement / -/// syncPlayerSegment / publishConfigRollout / rollbackConfigRollout)。 -/// -/// 维护约束:InMemory 追加式注册表为最小承载(admin 面下发留痕与最新态查询), -/// 生产级配置分发管道(存储 / 灰度计算 / 客户端推送)另行演进;七个 action 均为 Admin 无幂等键族, -/// 不做调度器层幂等包裹;ConfigKind 线缆数字 1~4 固定映射 RemoteConfig / Announcement / DeviceGroup / ScheduledTask。 -/// -/// -public static class OnlineAdminLiveOpsHandlers -{ - - /// - /// 注册 LiveOps 域 action:LiveOps 注册表经模块 Register 装配后传入。 - /// - /// 动作注册表。 - /// LiveOps 注册表。 - public static void RegisterLiveOps(AdminActionRegistry registry, OnlineLiveOpsRegistry liveOps) - { - registry.Register("publishRemoteConfig", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => PublishRemoteConfigAsync(request, scope, cancellationToken, liveOps)), false); - registry.Register("syncDeviceGroup", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => SyncDeviceGroupAsync(request, scope, cancellationToken, liveOps)), false); - registry.Register("syncScheduledTask", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => SyncScheduledTaskAsync(request, scope, cancellationToken, liveOps)), false); - registry.Register("pushAnnouncement", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => PushAnnouncementAsync(request, scope, cancellationToken, liveOps)), false); - registry.Register("syncPlayerSegment", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => SyncPlayerSegmentAsync(request, scope, cancellationToken, liveOps)), false); - registry.Register("publishConfigRollout", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => PublishConfigRolloutAsync(request, scope, cancellationToken, liveOps)), false); - registry.Register("rollbackConfigRollout", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => RollbackConfigRolloutAsync(request, scope, cancellationToken, liveOps)), false); - } - - /// - /// publishRemoteConfig:远程配置发布留痕。 - /// - /// 请求。 - /// 作用域。 - /// 取消令牌。 - /// LiveOps 注册表。 - /// LiveOps 回执。 - private static Task PublishRemoteConfigAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) - { - var configId = RequireId(request, "ConfigId"); - var reason = OnlineAdminApiContract.RequireString(request, "Reason"); - var entry = liveOps.Publish(new OnlineLiveOpsCommand - { - Kind = "RemoteConfig", - Key = configId.ToString(System.Globalization.CultureInfo.InvariantCulture), - Version = string.Empty, - PayloadText = reason, - OperatorId = "admin", - CorrelationId = request.ReadRequestId(), - }); - return Task.FromResult(BuildResponse(entry, 0)); - } - - /// - /// syncDeviceGroup:设备分组同步留痕。 - /// - /// 请求。 - /// 作用域。 - /// 取消令牌。 - /// LiveOps 注册表。 - /// LiveOps 回执。 - private static Task SyncDeviceGroupAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) - { - var deviceGroupId = RequireId(request, "DeviceGroupId"); - var reason = OnlineAdminApiContract.RequireString(request, "Reason"); - var entry = liveOps.Sync(new OnlineLiveOpsCommand - { - Kind = "DeviceGroup", - Key = deviceGroupId.ToString(System.Globalization.CultureInfo.InvariantCulture), - PayloadText = reason, - OperatorId = "admin", - CorrelationId = request.ReadRequestId(), - }); - return Task.FromResult(BuildResponse(entry, 0)); - } - - /// - /// syncScheduledTask:定时任务同步留痕。 - /// - /// 请求。 - /// 作用域。 - /// 取消令牌。 - /// LiveOps 注册表。 - /// LiveOps 回执。 - private static Task SyncScheduledTaskAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) - { - var jobId = RequireId(request, "JobId"); - var reason = OnlineAdminApiContract.RequireString(request, "Reason"); - var entry = liveOps.Sync(new OnlineLiveOpsCommand - { - Kind = "ScheduledTask", - Key = jobId.ToString(System.Globalization.CultureInfo.InvariantCulture), - PayloadText = reason, - OperatorId = "admin", - CorrelationId = request.ReadRequestId(), - }); - return Task.FromResult(BuildResponse(entry, 0)); - } - - /// - /// pushAnnouncement:公告推送留痕。 - /// - /// 请求。 - /// 作用域。 - /// 取消令牌。 - /// LiveOps 注册表。 - /// LiveOps 回执。 - private static Task PushAnnouncementAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) - { - var announcementId = RequireId(request, "AnnouncementId"); - var reason = OnlineAdminApiContract.RequireString(request, "Reason"); - var entry = liveOps.Publish(new OnlineLiveOpsCommand - { - Kind = "Announcement", - Key = announcementId.ToString(System.Globalization.CultureInfo.InvariantCulture), - Version = string.Empty, - PayloadText = reason, - OperatorId = "admin", - CorrelationId = request.ReadRequestId(), - }); - return Task.FromResult(BuildResponse(entry, 0)); - } - - /// - /// syncPlayerSegment:玩家分群同步留痕(载荷 = 名称 + 条件原文)。 - /// - /// 请求。 - /// 作用域。 - /// 取消令牌。 - /// LiveOps 注册表。 - /// LiveOps 回执。 - private static Task SyncPlayerSegmentAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) - { - var segmentId = RequireId(request, "SegmentId"); - var name = OnlineAdminApiContract.RequireString(request, "Name"); - var conditions = OnlineAdminApiContract.ReadOptionalString(request, "Conditions") ?? string.Empty; - var reason = OnlineAdminApiContract.RequireString(request, "Reason"); - var payload = JsonHelper.Serialize(new SegmentPayload { Name = name, Conditions = conditions, Reason = reason, }); - var entry = liveOps.Sync(new OnlineLiveOpsCommand - { - Kind = "PlayerSegment", - Key = segmentId.ToString(System.Globalization.CultureInfo.InvariantCulture), - PayloadText = payload, - OperatorId = "admin", - CorrelationId = request.ReadRequestId(), - }); - return Task.FromResult(BuildResponse(entry, segmentId)); - } - - /// - /// publishConfigRollout:配置灰度发布留痕(ConfigKind 1~4 + 键 + 版本 + 分群 + 百分比)。 - /// - /// 请求。 - /// 作用域。 - /// 取消令牌。 - /// LiveOps 注册表。 - /// LiveOps 回执。 - private static Task PublishConfigRolloutAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) - { - var configKind = ReadConfigKind(request); - var configKey = OnlineAdminApiContract.RequireString(request, "ConfigKey"); - var configVersion = RequireVersion(request, "ConfigVersion"); - var segmentId = request.ReadNullableInt64("SegmentId") ?? 0; - var percent = ReadRolloutPercent(request); - var reason = OnlineAdminApiContract.RequireString(request, "Reason"); - var payload = JsonHelper.Serialize(new RolloutPayload - { - ConfigKind = configKind, - SegmentId = segmentId, - Percent = percent, - Reason = reason, - }); - var entry = liveOps.Publish(new OnlineLiveOpsCommand - { - Kind = RolloutKind(configKind), - Key = configKey, - Version = configVersion.ToString(System.Globalization.CultureInfo.InvariantCulture), - PayloadText = payload, - OperatorId = "admin", - CorrelationId = request.ReadRequestId(), - }); - return Task.FromResult(BuildResponse(entry, segmentId)); - } - - /// - /// rollbackConfigRollout:配置灰度回滚留痕(目标版本即回滚后生效版本)。 - /// - /// 请求。 - /// 作用域。 - /// 取消令牌。 - /// LiveOps 注册表。 - /// LiveOps 回执。 - private static Task RollbackConfigRolloutAsync(AdminApiRequest request, OnlineScope scope, CancellationToken cancellationToken, OnlineLiveOpsRegistry liveOps) - { - var configKind = ReadConfigKind(request); - var configKey = OnlineAdminApiContract.RequireString(request, "ConfigKey"); - var targetVersion = RequireVersion(request, "TargetVersion"); - var reason = OnlineAdminApiContract.RequireString(request, "Reason"); - var entry = liveOps.Rollback(new OnlineLiveOpsCommand - { - Kind = RolloutKind(configKind), - Key = configKey, - Version = targetVersion.ToString(System.Globalization.CultureInfo.InvariantCulture), - PayloadText = reason, - OperatorId = "admin", - CorrelationId = request.ReadRequestId(), - }); - return Task.FromResult(BuildResponse(entry, 0)); - } - - /// - /// 读取必填正整数标识。 - /// - /// 请求。 - /// 字段名。 - /// 标识。 - private static long RequireId(AdminApiRequest request, string name) - { - var value = request.ReadNullableInt64(name); - if (value.HasValue && value.Value > 0) - { - return value.Value; - } - - // Localization: Online.AdminApi.PositiveNumberRequired - {0} 必须为正数。 - throw new OnlineServiceException(OnlineErrorCode.ParameterInvalid, LocalizationService.GetString(Localization.Keys.Online.AdminApi.PositiveNumberRequired, name)); - } - - /// - /// 读取必填正版本号。 - /// - /// 请求。 - /// 字段名。 - /// 版本号。 - private static int RequireVersion(AdminApiRequest request, string name) - { - var value = request.ReadNullableInt32(name); - if (value.HasValue && value.Value > 0) - { - return value.Value; - } - - // Localization: Online.AdminApi.PositiveNumberRequired - {0} 必须为正数。 - throw new OnlineServiceException(OnlineErrorCode.ParameterInvalid, LocalizationService.GetString(Localization.Keys.Online.AdminApi.PositiveNumberRequired, name)); - } - - /// - /// 读取 ConfigKind(线缆数字 1~4)。 - /// - /// 请求。 - /// ConfigKind 数字。 - private static int ReadConfigKind(AdminApiRequest request) - { - var value = request.ReadNullableInt32("ConfigKind"); - if (value.HasValue && value.Value >= 1 && value.Value <= 4) - { - return value.Value; - } - - // Localization: Online.AdminApi.ConfigKindInvalid - ConfigKind 必须是 [1,4] 范围内的数字(RemoteConfig/Announcement/DeviceGroup/ScheduledTask)。 - throw new OnlineServiceException(OnlineErrorCode.ParameterInvalid, LocalizationService.GetString(Localization.Keys.Online.AdminApi.ConfigKindInvalid)); - } - - /// - /// 读取灰度百分比(0~100,缺省 100)。 - /// - /// 请求。 - /// 灰度百分比。 - private static int ReadRolloutPercent(AdminApiRequest request) - { - var value = request.ReadNullableInt32("Percent") ?? 100; - if (value >= 0 && value <= 100) - { - return value; - } - - // Localization: Online.AdminApi.RolloutPercentInvalid - Percent 必须是 [0,100] 范围内的灰度百分比。 - throw new OnlineServiceException(OnlineErrorCode.ParameterInvalid, LocalizationService.GetString(Localization.Keys.Online.AdminApi.RolloutPercentInvalid)); - } - - /// - /// ConfigKind 数字 → 灰度注册表 kind 前缀。 - /// - /// ConfigKind 数字。 - /// 注册表 kind。 - private static string RolloutKind(int configKind) - { - switch (configKind) - { - case 1: - return "ConfigRollout:RemoteConfig"; - case 2: - return "ConfigRollout:Announcement"; - case 3: - return "ConfigRollout:DeviceGroup"; - default: - return "ConfigRollout:ScheduledTask"; - } - } - - /// - /// 构造 LiveOps 回执(ConfirmVersion = 版本号,缺省回退注册表序号)。 - /// - /// 注册表条目。 - /// 分群标识(无关命令传 0)。 - /// LiveOps 回执。 - private static OnlineLiveOpsResponse BuildResponse(OnlineLiveOpsEntry entry, long segmentId) - { - return new OnlineLiveOpsResponse - { - ConfirmVersion = string.IsNullOrEmpty(entry.Version) - ? entry.Sequence.ToString(System.Globalization.CultureInfo.InvariantCulture) - : entry.Version, - SegmentId = segmentId, - ServerTime = OnlineAdminApiContract.NowSeconds() * 1000, - }; - } - - /// - /// 分群载荷。 - /// - public sealed class SegmentPayload - { - /// 获取或设置分群名称。 - public string Name { get; set; } - - /// 获取或设置条件原文。 - public string Conditions { get; set; } - - /// 获取或设置原因。 - public string Reason { get; set; } - } - - /// - /// 灰度载荷。 - /// - public sealed class RolloutPayload - { - /// 获取或设置 ConfigKind(1=RemoteConfig/2=Announcement/3=DeviceGroup/4=ScheduledTask)。 - public int ConfigKind { get; set; } - - /// 获取或设置分群标识。 - public long SegmentId { get; set; } - - /// 获取或设置灰度百分比(0~100)。 - public int Percent { get; set; } - - /// 获取或设置原因。 - public string Reason { get; set; } - } - - /// - /// LiveOps 回执(对齐 Admin OnlineLiveOpsResponse)。 - /// - public sealed class OnlineLiveOpsResponse - { - /// 获取或设置确认版本。 - public string ConfirmVersion { get; set; } - - /// 获取或设置分群标识(未返回为 0)。 - public long SegmentId { get; set; } - - /// 获取或设置消息(未返回为 null)。 - public string Message { get; set; } - - /// 获取或设置服务端时刻(UTC 毫秒)。 - public long ServerTime { get; set; } - } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/GameFrameX.Capability.Online.Competition.csproj b/Capability/GameFrameX.Capability.Online.Competition/GameFrameX.Capability.Online.Competition.csproj index 4079ad48f..c2f08c7b3 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/GameFrameX.Capability.Online.Competition.csproj +++ b/Capability/GameFrameX.Capability.Online.Competition/GameFrameX.Capability.Online.Competition.csproj @@ -2,18 +2,16 @@ - GameFrameX.Capability.Online.Competition,GFX Online 竞技能力包:排行榜/赛季/锦标赛/LiveOps 承载(InMemory 默认存储,懒默认描述符,族/宿主覆盖恒胜出)+ 自装配模块(OnlineCompetitionCapabilityModule,Options=OnlineCompetitionOptions)+ admin handlers(LiveOps 七 action). Competition capability package for the GFX Online family: leaderboards, seasons, tournaments and the LiveOps registry with in-memory default stores, the self-assembling capability module and admin handlers. Documentation: https://gameframex.doc.alianblank.com - GameFrameX,Capability,Online,Competition,Leaderboard,Season,Tournament,LiveOps,GameServer - + GameFrameX.Capability.Online.Competition,GFX Online 竞技能力包(冻结面:不删除、不演进):赛季/锦标赛承载(InMemory 默认存储,懒默认描述符,族/宿主覆盖恒胜出)+ 自装配模块(OnlineCompetitionCapabilityModule,必选依赖 online-leaderboard);榜单能力已拆至 GameFrameX.Capability.Online.Leaderboard 独立包,LiveOps 运营面移交 Admin 仓. Frozen competition capability package for the GFX Online family: seasons and tournaments with in-memory default stores and the self-assembling module requiring online-leaderboard; leaderboards moved to the dedicated leaderboard package and LiveOps handed over to the admin console. Documentation: https://gameframex.doc.alianblank.com + GameFrameX,Capability,Online,Competition,Season,Tournament,Frozen,GameServer + - - + diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/IOnlineLeaderboardStore.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/IOnlineLeaderboardStore.cs deleted file mode 100644 index aca5e7d49..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/IOnlineLeaderboardStore.cs +++ /dev/null @@ -1,110 +0,0 @@ -// ========================================================================================== -// 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 see 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 System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜存储契约(榜单定义 + 条目;InMemory 为单进程默认实现,生产持久化归 Server 仓运行时装配)。 -/// -/// 维护约束(红线): -/// (1) 榜单为全局域投影目标——字典键即 LeaderboardId(无区服隔离位,同键即同榜); -/// (2) 是唯一条目写入入口,**累计策略裁决与条目落档必须在同一临界区**, -/// 并发投递不得交错撕裂(形态对齐票据 / 通知存储的临界区约定); -/// (3) 出入参一律防御性拷贝——返回对象与内部状态无别名,调用方改写不影响存储。 -/// -/// -public interface IOnlineLeaderboardStore -{ - /// - /// 创建榜单(同名榜单已存在时拒绝,返回 null,不覆盖)。 - /// - /// 榜单定义。 - /// 取消令牌。 - /// 创建后的榜单副本;已存在返回 null。 - Task CreateAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default); - - /// - /// 按榜单标识查找榜单定义。 - /// - /// 榜单标识。 - /// 取消令牌。 - /// 榜单副本;不存在返回 null。 - Task FindAsync(string leaderboardId, CancellationToken cancellationToken = default); - - /// - /// 查找单玩家条目。 - /// - /// 榜单标识。 - /// 玩家标识。 - /// 取消令牌。 - /// 条目副本;未上榜或榜单不存在返回 null。 - Task FindEntryAsync(string leaderboardId, long playerId, CancellationToken cancellationToken = default); - - /// - /// 应用一笔分数提交(原子:累计策略裁决 + 条目落档在同一临界区)。 - /// - /// - /// 红线:Sum 策略累加溢出(checked)时拒绝本笔写入并返回 null——条目零状态变更, - /// 不做饱和截断(不把异常数据悄悄写成 long.MaxValue)。未来持久化排行榜存储落地时, - /// 同样的溢出判断必须放进存储层的原子更新里。 - /// - /// 目标榜单定义(调用方先经 取得)。 - /// 分数提交。 - /// 取消令牌。 - /// 写入结果(聚合后条目 + 临界区内事实的前值);Sum 累加溢出拒绝时为 null。 - Task ApplySubmissionAsync(OnlineLeaderboard leaderboard, OnlineLeaderboardScoreSubmission submission, CancellationToken cancellationToken = default); - - /// - /// 列出榜单全序条目(按 排序的条目副本列表)。 - /// - /// 目标榜单定义。 - /// 取消令牌。 - /// 全序条目副本;空榜返回空列表。 - Task> ListOrderedEntriesAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default); - - /// - /// 清空榜上条目(**赛季重置的唯一移除入口**;CAS 语义——只有榜上条目集合与 - /// 逐项一致时才清空,否则拒绝且不改变任何状态)。 - /// - /// 维护约束(红线):「条目一经产生不从榜单移除」的规则在赛季维度由此方法开例外——重置作用于整榜, - /// 不做单条移除。CAS 比对是**榜首快照与清空之间的写入保护**:调用方(赛季服务)以「先持久化快照、 - /// 再按同一份快照清空」的次序执行,比对不一致即说明期间有写入落地,此时必须拒绝清空而不是把 - /// 这条已结算的真实成绩一并抹掉(赛季重置不得丢分)。 - /// - /// - /// 目标榜单定义(调用方先经 取得)。 - /// 调用方持有的全序条目快照(须来自 )。 - /// 取消令牌。 - /// 清空成功返回 true;榜上条目已变化而拒绝清空返回 false。 - Task TryResetAsync(OnlineLeaderboard leaderboard, IReadOnlyList expectedEntries, CancellationToken cancellationToken = default); -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/InMemoryOnlineLeaderboardStore.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/InMemoryOnlineLeaderboardStore.cs deleted file mode 100644 index 787dd0166..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/InMemoryOnlineLeaderboardStore.cs +++ /dev/null @@ -1,401 +0,0 @@ -// ========================================================================================== -// 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 see 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 System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using GameFrameX.Foundation.Localization.Core; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜内存存储(单进程默认实现;生产持久化 / 多实例分片归 Server 仓运行时装配)。 -/// -/// 维护约束(红线):榜单定义与条目同锁(单锁粒度:本实现以整体锁保证「策略裁决 + 落档」原子性与 -/// 查询快照一致性;热点写入的分片 / 批量优化属吞吐优化项,归运行时装配,不在此实现)。 -/// 出入参防御性拷贝,存储内对象与外界无别名。 -/// -/// -public sealed class InMemoryOnlineLeaderboardStore : IOnlineLeaderboardStore -{ - /// 全局读写锁(榜单与条目共用,保证快照一致性)。 - private readonly object _syncRoot = new(); - - /// 榜单定义表:键 = LeaderboardId(全局域投影,无区服隔离位)。 - private readonly Dictionary _boards = new(); - - /// 条目表:键 = 榜单键 → (PlayerId → 条目)。 - private readonly Dictionary> _entries = new(); - - /// - /// 初始化 。 - /// - public InMemoryOnlineLeaderboardStore() - { - } - - /// - /// 在全局锁内创建榜单:同标识已存在时拒绝返回 null,否则落档定义副本并初始化空条目表。 - /// - /// - /// Creates the leaderboard under the global lock: refuses with null when the same id already exists, otherwise stores a defensive copy of the definition and initializes an empty entry table. - /// - /// 榜单定义 / The leaderboard definition - /// 取消令牌 / Cancellation token - /// 创建后的榜单副本;已存在返回 null / A copy of the created leaderboard; null when it already exists - /// 当 为 null 时抛出 / Thrown when is null - public Task CreateAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default) - { - if (leaderboard == null) - { - throw new ArgumentNullException(nameof(leaderboard)); - } - - lock (_syncRoot) - { - var key = BuildKey(leaderboard.LeaderboardId); - if (_boards.ContainsKey(key)) - { - return Task.FromResult(null); - } - - _boards[key] = leaderboard.Copy(); - _entries[key] = new Dictionary(); - return Task.FromResult(leaderboard.Copy()); - } - } - - /// - /// 在全局锁内按榜单标识查找榜单定义,返回防御性副本。 - /// - /// - /// Finds the leaderboard definition by leaderboard id under the global lock, returning a defensive copy. - /// - /// 榜单标识 / The leaderboard id - /// 取消令牌 / Cancellation token - /// 榜单副本;不存在返回 null / A copy of the leaderboard; null when not found - public Task FindAsync(string leaderboardId, CancellationToken cancellationToken = default) - { - lock (_syncRoot) - { - return Task.FromResult(TryFindBoard(leaderboardId, out var board) ? board.Copy() : null); - } - } - - /// - /// 在全局锁内查找指定玩家的榜上条目,返回防御性副本。 - /// - /// - /// Finds a single player's entry on the board under the global lock, returning a defensive copy. - /// - /// 榜单标识 / The leaderboard id - /// 玩家标识 / The player id - /// 取消令牌 / Cancellation token - /// 条目副本;未上榜或榜单不存在返回 null / A copy of the entry; null when the player is unranked or the board does not exist - public Task FindEntryAsync(string leaderboardId, long playerId, CancellationToken cancellationToken = default) - { - lock (_syncRoot) - { - if (!TryFindBoard(leaderboardId, out _) || !_entries.TryGetValue(BuildKey(leaderboardId), out var boardEntries) || !boardEntries.TryGetValue(playerId, out var entry)) - { - return Task.FromResult(null); - } - - return Task.FromResult(entry.Copy()); - } - } - - /// - /// 在全局锁内的同一临界区按累计策略裁决分数并落档条目,不存在则新建条目。 - /// - /// - /// Resolves the score by the accumulation policy and archives the entry within the same critical section under the global lock, creating the entry when absent. - /// - /// Sum 策略累加溢出(checked)时拒绝本笔写入并返回 null:条目零状态变更—— - /// 已有条目保持原分数与提交计数;本次新建的条目会被回滚移除,不留半截档。 - /// - /// - /// 目标榜单定义(调用方先经 取得)/ The target leaderboard definition (obtained by the caller via first) - /// 分数提交 / The score submission - /// 取消令牌 / The cancellation token - /// 写入结果(聚合后条目副本与临界区内事实的前值);Sum 累加溢出拒绝时为 null / The apply result (the merged entry copy and the pre-update facts observed inside the critical section); null when the Sum accumulation overflows and the write is refused - /// 当 或 为 null 时抛出 / Thrown when or is null - /// 当目标榜单未创建或已失效(未经 解析)时抛出 / Thrown when the target leaderboard is not created or has expired (not resolved via ) - public Task ApplySubmissionAsync(OnlineLeaderboard leaderboard, OnlineLeaderboardScoreSubmission submission, CancellationToken cancellationToken = default) - { - if (leaderboard == null) - { - throw new ArgumentNullException(nameof(leaderboard)); - } - - if (submission == null) - { - throw new ArgumentNullException(nameof(submission)); - } - - lock (_syncRoot) - { - var key = BuildKey(leaderboard.LeaderboardId); - if (!_boards.ContainsKey(key) || !_entries.TryGetValue(key, out var boardEntries)) - { - // Localization: Online.Leaderboard.NotFoundOnWrite - 榜单不存在或已失效,写入前必须先经 FindAsync 解析 - throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Online.Leaderboard.NotFoundOnWrite)); - } - - if (!boardEntries.TryGetValue(submission.PlayerId, out var entry)) - { - entry = new OnlineLeaderboardEntry { PlayerId = submission.PlayerId, }; - boardEntries[submission.PlayerId] = entry; - } - - if (!TryResolveScore(leaderboard, entry, submission.IncomingScore, out var resolvedScore)) - { - // Sum 累加溢出:拒绝本笔写入,零状态变更(新建条目回滚移除,不递增提交计数)。 - if (entry.SubmissionCount == 0) - { - boardEntries.Remove(submission.PlayerId); - } - - return Task.FromResult(null); - } - - var oldScore = entry.Score; - var isNewEntry = entry.SubmissionCount == 0; - entry.Score = resolvedScore; - entry.SourceKind = submission.SourceKind; - entry.SourceMatchResultId = submission.SourceMatchResultId; - entry.LastUpdateTime = submission.SubmittedTime; - entry.SubmissionCount++; - - return Task.FromResult(new OnlineLeaderboardApplyResult - { - Entry = entry.Copy(), - OldScore = oldScore, - IsNewEntry = isNewEntry, - }); - } - } - - /// - /// 在全局锁内拷贝全榜条目,再按榜单排序规则排出全序返回。 - /// - /// - /// Copies every entry of the board under the global lock, then sorts the copies into the full order defined by the board's sort rule. - /// - /// 目标榜单定义 / The target leaderboard definition - /// 取消令牌 / Cancellation token - /// 全序条目副本;空榜返回空列表 / The ordered entry copies; an empty list for an empty board - /// 当 为 null 时抛出 / Thrown when is null - /// 当目标榜单未创建或已失效(未经 解析)时抛出 / Thrown when the target leaderboard is not created or has expired (not resolved via ) - public Task> ListOrderedEntriesAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default) - { - if (leaderboard == null) - { - throw new ArgumentNullException(nameof(leaderboard)); - } - - List copies; - lock (_syncRoot) - { - var key = BuildKey(leaderboard.LeaderboardId); - if (!_entries.TryGetValue(key, out var boardEntries)) - { - // Localization: Online.Leaderboard.NotFoundOnQuery - 榜单不存在或已失效,查询前必须先经 FindAsync 解析 - throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Online.Leaderboard.NotFoundOnQuery)); - } - - copies = new List(boardEntries.Count); - foreach (var entry in boardEntries.Values) - { - copies.Add(entry.Copy()); - } - } - - OnlineLeaderboardOrdering.Sort(leaderboard.SortOrder, copies); - return Task.FromResult(copies); - } - - /// - /// 在全局锁内将榜上条目与期望快照做 CAS 比对,完全一致才清空整榜,否则拒绝且不改变状态。 - /// - /// - /// Compares the board entries against the expected snapshot as a CAS check under the global lock, clearing the whole board only on an exact match and otherwise refusing without any state change. - /// - /// 目标榜单定义 / The target leaderboard definition - /// 调用方持有的全序条目快照 / The ordered entry snapshot held by the caller - /// 取消令牌 / Cancellation token - /// 清空成功返回 true;榜上条目已变化而拒绝清空返回 false / True when the board is cleared; false when the entries changed and the reset is refused - /// 当 或 为 null 时抛出 / Thrown when or is null - /// 当目标榜单未创建或已失效(未经 解析)时抛出 / Thrown when the target leaderboard is not created or has expired (not resolved via ) - public Task TryResetAsync(OnlineLeaderboard leaderboard, IReadOnlyList expectedEntries, CancellationToken cancellationToken = default) - { - if (leaderboard == null) - { - throw new ArgumentNullException(nameof(leaderboard)); - } - - if (expectedEntries == null) - { - throw new ArgumentNullException(nameof(expectedEntries)); - } - - lock (_syncRoot) - { - var key = BuildKey(leaderboard.LeaderboardId); - if (!_entries.TryGetValue(key, out var boardEntries)) - { - // Localization: Online.Leaderboard.NotFoundOnReset - 榜单不存在或已失效,重置前必须先经 FindAsync 解析 - throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Online.Leaderboard.NotFoundOnReset)); - } - - if (!MatchesExpectedOrdered(leaderboard, boardEntries, expectedEntries)) - { - return Task.FromResult(false); - } - - boardEntries.Clear(); - return Task.FromResult(true); - } - } - - /// - /// 在临界区内比对榜上条目与调用方持有的快照是否逐项一致(CAS 判据)。 - /// - /// 榜单定义(取排序方向重建全序)。 - /// 临界区内的条目表。 - /// 调用方持有的全序条目快照。 - /// 完全一致返回 true。 - private static bool MatchesExpectedOrdered(OnlineLeaderboard leaderboard, Dictionary boardEntries, IReadOnlyList expectedEntries) - { - if (boardEntries.Count != expectedEntries.Count) - { - return false; - } - - var current = new List(boardEntries.Values); - OnlineLeaderboardOrdering.Sort(leaderboard.SortOrder, current); - for (var index = 0; index < current.Count; index++) - { - if (!MatchesExpectedEntry(current[index], expectedEntries[index])) - { - return false; - } - } - - return true; - } - - /// - /// 比对单个条目是否与快照一致(玩家、分数、更新时间、提交计数四要素全等)。 - /// - /// 临界区内的条目。 - /// 快照中的条目。 - /// 一致返回 true。 - private static bool MatchesExpectedEntry(OnlineLeaderboardEntry current, OnlineLeaderboardEntry expected) - { - return expected != null - && current.PlayerId == expected.PlayerId - && current.Score == expected.Score - && current.LastUpdateTime == expected.LastUpdateTime - && current.SubmissionCount == expected.SubmissionCount; - } - - /// - /// 在锁内解析榜单定义(调用方已持锁)。 - /// - /// 榜单标识。 - /// 解析到的榜单定义。 - /// 存在返回 true。 - private bool TryFindBoard(string leaderboardId, out OnlineLeaderboard board) - { - board = null; - if (string.IsNullOrEmpty(leaderboardId)) - { - return false; - } - - if (!_boards.TryGetValue(BuildKey(leaderboardId), out var stored)) - { - return false; - } - - board = stored; - return true; - } - - /// - /// 在临界区内按累计策略裁决新分数(首笔直接生效;Best 以榜向判优,Sum 累加(checked,溢出拒绝),Latest 覆盖)。 - /// - /// 榜单定义。 - /// 临界区内当前条目。 - /// 本笔分数。 - /// 裁决后的分数(失败时为条目原分数,不落档)。 - /// 裁决成功返回 true;Sum 累加溢出返回 false(本笔写入被拒绝,不做饱和截断)。 - private static bool TryResolveScore(OnlineLeaderboard leaderboard, OnlineLeaderboardEntry entry, long incomingScore, out long resolvedScore) - { - if (entry.SubmissionCount == 0) - { - resolvedScore = incomingScore; - return true; - } - - switch (leaderboard.ScoreUpdatePolicy) - { - case OnlineLeaderboardScoreUpdatePolicy.Sum: - try - { - resolvedScore = checked(entry.Score + incomingScore); - return true; - } - catch (OverflowException) - { - resolvedScore = entry.Score; - return false; - } - case OnlineLeaderboardScoreUpdatePolicy.Latest: - resolvedScore = incomingScore; - return true; - case OnlineLeaderboardScoreUpdatePolicy.Best: - default: - resolvedScore = OnlineLeaderboardOrdering.IsBetter(leaderboard.SortOrder, incomingScore, entry.Score) ? incomingScore : entry.Score; - return true; - } - } - - /// - /// 构造存储键(榜单标识即键——全局域投影目标,同键即同榜)。 - /// - /// 榜单标识。 - /// 存储键。 - private static string BuildKey(string leaderboardId) - { - return leaderboardId ?? string.Empty; - } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboard.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboard.cs deleted file mode 100644 index 93fe0723e..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboard.cs +++ /dev/null @@ -1,82 +0,0 @@ -// ========================================================================================== -// 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 see 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜榜单定义(第一版个人榜;全局域投影目标,无区服隔离位——同 LeaderboardId 即同榜)。 -/// -/// 维护约束(红线):榜单为全局域数据——同键读写天然成立,无跨区服隔离维度; -/// 队伍榜 / 公会榜 / 复杂跨服排名延后(超出首版范围)。排序方向与累计策略创建后固化,运行期不可变更; -/// 赛季维度的生命周期(重置 / 快照)归赛季域,本类型不承载赛季字段。 -/// -/// -public sealed class OnlineLeaderboard -{ - /// - /// 获取或设置榜单标识(全局唯一,创建方提供)。 - /// - public string LeaderboardId { get; set; } - - /// - /// 获取或设置排序方向(创建后固化)。 - /// - public OnlineLeaderboardSortOrder SortOrder { get; set; } - - /// - /// 获取或设置分数累计策略(创建后固化)。 - /// - public OnlineLeaderboardScoreUpdatePolicy ScoreUpdatePolicy { get; set; } - - /// - /// 获取或设置单次提交分数合理上限(防刷校验上界;0 = 使用 全局默认值)。 - /// - public long MaxScorePerSubmission { get; set; } - - /// - /// 获取或设置创建时刻(UTC 毫秒)。 - /// - public long CreatedTime { get; set; } - - /// - /// 复制榜单定义(存储出入参防御性拷贝)。 - /// - /// 榜单定义副本。 - public OnlineLeaderboard Copy() - { - return new OnlineLeaderboard - { - LeaderboardId = LeaderboardId, - SortOrder = SortOrder, - ScoreUpdatePolicy = ScoreUpdatePolicy, - MaxScorePerSubmission = MaxScorePerSubmission, - CreatedTime = CreatedTime, - }; - } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardApplyResult.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardApplyResult.cs deleted file mode 100644 index cea4cead1..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardApplyResult.cs +++ /dev/null @@ -1,55 +0,0 @@ -// ========================================================================================== -// 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 see 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 存储临界区内的单笔写入结果(新条目 / 聚合后条目 + 临界区内事实的前值,供事件载荷使用)。 -/// -/// 维护约束: 与 均取自同一临界区快照——并发写入下 -/// 事件载荷的前后值也是真实前后值,不得由服务层先读后写拼装(会被并发交错撕裂)。 -/// -/// -public sealed class OnlineLeaderboardApplyResult -{ - /// - /// 获取或设置写入后的条目副本(含聚合分数与提交计数)。 - /// - public OnlineLeaderboardEntry Entry { get; set; } - - /// - /// 获取或设置写入前分数(首笔为 0;临界区内事实)。 - /// - public long OldScore { get; set; } - - /// - /// 获取或设置是否为本玩家首笔写入(此前未上榜)。 - /// - public bool IsNewEntry { get; set; } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardAroundQuery.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardAroundQuery.cs deleted file mode 100644 index 86da7c613..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardAroundQuery.cs +++ /dev/null @@ -1,67 +0,0 @@ -// ========================================================================================== -// 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 related 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 see the LICENSE file in the root directory of the source code. -// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 -// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, -// 侵犯他人合法权益等法律法规所禁止的行为! -// or infringe upon the legitimate 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 玩家附近排名窗口查询载荷( 除作用域外的全部查询维度; -/// 窗口含玩家本人,边界处截断)。 -/// -public sealed class OnlineLeaderboardAroundQuery -{ - /// - /// 获取或设置榜单标识。 - /// - /// Gets or sets the leaderboard id. - public string LeaderboardId { get; init; } - - /// - /// 获取或设置玩家标识(未上榜返回 ResourceNotFound)。 - /// - /// Gets or sets the player id (an unranked player yields ResourceNotFound). - public long PlayerId { get; init; } - - /// - /// 获取或设置前向窗口条数(缺省 0 = 不含前向邻居;Before / After 均缺省时窗口仅含本人)。 - /// - /// Gets or sets the number of entries before the player (default 0 = no preceding neighbors; when both Before and After are left at 0 the window contains only the player). - public int Before { get; init; } - - /// - /// 获取或设置后向窗口条数(缺省 0 = 不含后向邻居;Before / After 均缺省时窗口仅含本人)。 - /// - /// Gets or sets the number of entries after the player (default 0 = no following neighbors; when both Before and After are left at 0 the window contains only the player). - public int After { get; init; } - - /// - /// 获取或设置当前时刻(UTC 毫秒;传 0 取系统时钟)。 - /// - /// Gets or sets the current time (UTC milliseconds; 0 = system clock). - public long NowUnixMilliseconds { get; init; } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardAroundView.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardAroundView.cs deleted file mode 100644 index 6bbbd9c23..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardAroundView.cs +++ /dev/null @@ -1,62 +0,0 @@ -// ========================================================================================== -// 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 see 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 System.Collections.Generic; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 玩家附近排名视图(以目标玩家为中心的连续名次窗口,窗口含目标玩家本人)。 -/// -/// 维护约束:窗口在榜单边界处截断——榜首请求的前向窗口与榜尾请求的后向窗口返回实际存在的条目, -/// 不以占位条目填充(附近排名边界);窗口内名次连续(rank 单调 +1),供客户端直接渲染。 -/// -/// -public sealed class OnlineLeaderboardAroundView -{ - /// - /// 获取或设置目标玩家标识。 - /// - public long PlayerId { get; set; } - - /// - /// 获取或设置目标玩家名次(从 1 开始)。 - /// - public int Rank { get; set; } - - /// - /// 获取或设置榜单条目总数(当前快照口径)。 - /// - public long TotalCount { get; set; } - - /// - /// 获取或设置附近窗口条目(含目标玩家,按名次升序;窗口边界处截断)。 - /// - public List Around { get; set; } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardCreateRequest.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardCreateRequest.cs deleted file mode 100644 index 69b643a0c..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardCreateRequest.cs +++ /dev/null @@ -1,60 +0,0 @@ -// ========================================================================================== -// 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 see 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜创建请求(服务端运营 / 运行时装配入口;客户端无此入口)。 -/// -/// 维护约束:作用域取鉴权上下文的 ,请求体不携带作用域键位(服务端不信任请求体作用域); -/// 同名榜单已存在时创建被拒绝(ParameterInvalid),不覆盖既有榜单。 -/// -/// -public sealed class OnlineLeaderboardCreateRequest -{ - /// - /// 获取或设置榜单标识(全局唯一,非空)。 - /// - public string LeaderboardId { get; set; } - - /// - /// 获取或设置排序方向(默认高分优先)。 - /// - public OnlineLeaderboardSortOrder SortOrder { get; set; } - - /// - /// 获取或设置分数累计策略(默认保留最优)。 - /// - public OnlineLeaderboardScoreUpdatePolicy ScoreUpdatePolicy { get; set; } - - /// - /// 获取或设置单次提交分数合理上限(0 = 使用全局默认值)。 - /// - public long MaxScorePerSubmission { get; set; } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEntry.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEntry.cs deleted file mode 100644 index ef58b64ae..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEntry.cs +++ /dev/null @@ -1,88 +0,0 @@ -// ========================================================================================== -// 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 see 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜条目(单玩家在单榜单上的聚合状态;名次不在条目上,查询时按全序计算)。 -/// -/// 维护约束(红线):分数只经可信写入链路产生( 即来源白名单), -/// 使每笔分数可追溯到结算结果——争议判定的审计依据; -/// 条目一经产生不从榜单移除(第一版无移除语义,赛季重置归赛季域)。 -/// -/// -public sealed class OnlineLeaderboardEntry -{ - /// - /// 获取或设置玩家标识。 - /// - public long PlayerId { get; set; } - - /// - /// 获取或设置榜上分数(按榜单累计策略聚合后的当前值)。 - /// - public long Score { get; set; } - - /// - /// 获取或设置最近一次写入的分数来源。 - /// - public OnlineLeaderboardScoreSource SourceKind { get; set; } - - /// - /// 获取或设置最近一次写入的来源结算结果标识(追溯键)。 - /// - public string SourceMatchResultId { get; set; } - - /// - /// 获取或设置最近一次写入时刻(UTC 毫秒;并列分数的次级排序键,先写入者靠前)。 - /// - public long LastUpdateTime { get; set; } - - /// - /// 获取或设置累计提交次数(含未改变分数的提交,如 Best 策略下的非更优分数)。 - /// - public int SubmissionCount { get; set; } - - /// - /// 复制条目(存储出入参防御性拷贝)。 - /// - /// 条目副本。 - public OnlineLeaderboardEntry Copy() - { - return new OnlineLeaderboardEntry - { - PlayerId = PlayerId, - Score = Score, - SourceKind = SourceKind, - SourceMatchResultId = SourceMatchResultId, - LastUpdateTime = LastUpdateTime, - SubmissionCount = SubmissionCount, - }; - } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEntryView.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEntryView.cs deleted file mode 100644 index b7de387cd..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEntryView.cs +++ /dev/null @@ -1,65 +0,0 @@ -// ========================================================================================== -// 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 see 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 System.Collections.Generic; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜查询条目视图(条目 + 按全序计算的名次;名次是查询时事实,不落存储)。 -/// -/// 维护约束:名次必须由 全序计算(并列时以更新时间与玩家标识稳定消解, -/// 不产生同名次空洞)——Top N / 附近排名 / 分页三个查询口径共用同一全序,保证结果可复算。 -/// -/// -public sealed class OnlineLeaderboardEntryView -{ - /// - /// 获取或设置名次(从 1 开始;全序唯一,无并列名次)。 - /// - public int Rank { get; set; } - - /// - /// 获取或设置榜上条目。 - /// - public OnlineLeaderboardEntry Entry { get; set; } - - /// - /// 复制视图(条目深拷贝)。 - /// - /// 视图副本。 - public OnlineLeaderboardEntryView Copy() - { - return new OnlineLeaderboardEntryView - { - Rank = Rank, - Entry = Entry == null ? null : Entry.Copy(), - }; - } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEvents.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEvents.cs deleted file mode 100644 index 286b8b092..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardEvents.cs +++ /dev/null @@ -1,187 +0,0 @@ -// ========================================================================================== -// 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 see 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 System; -using System.Collections.Generic; -using System.Globalization; -using System.Text.Json; -using GameFrameX.Capability.Online.Abstractions.Events; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行域事件工厂(统一信封事件,Source = "online-leaderboard")。 -/// -/// 维护约束(红线):事件是**事实不是状态**—— 只陈述「某玩家分数已由某结算结果 -/// 变更为某值」,榜上名次不进事件(名次是查询时事实,快照口径随读变化);载荷与审计字段都不含 -/// 玩家私有数据。分数变更事件只可能由可信写入链路产生(分数写入唯一入口即投影器)。 -/// -/// -public static class OnlineLeaderboardEvents -{ - /// 榜单创建。 - public const string LeaderboardCreated = "online.leaderboard.created"; - - /// 榜上分数更新(可信写入)。 - public const string ScoreUpdated = "online.leaderboard.scoreupdated"; - - /// 事件来源标识。 - public const string Source = "online-leaderboard"; - - /// - /// 构造榜单创建事件。 - /// - /// 榜单标识(可空;载荷落空字符串)。 - /// 排序方向名。 - /// 累计策略名。 - /// 创建时刻(UTC 毫秒)。 - /// 事件信封实例。 - public static OnlineEvent CreateLeaderboardCreated(string leaderboardId, string sortOrder, string scoreUpdatePolicy, long createdTime) - { - var payload = new LeaderboardCreatedPayload - { - LeaderboardId = leaderboardId ?? string.Empty, - SortOrder = sortOrder, - ScoreUpdatePolicy = scoreUpdatePolicy, - CreatedTime = createdTime, - }; - var auditFields = new Dictionary - { - { "LeaderboardId", leaderboardId ?? string.Empty }, - { "SortOrder", sortOrder }, - { "ScoreUpdatePolicy", scoreUpdatePolicy }, - { "CreatedTime", createdTime.ToString(CultureInfo.InvariantCulture) }, - }; - return new OnlineEvent - { - EventId = "evt-" + Guid.NewGuid().ToString("N"), - EventType = LeaderboardCreated, - OccurredTime = createdTime > 0 ? createdTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), - SchemaVersion = 1, - ServerId = 0, - PlayerId = 0, - Source = Source, - CorrelationId = string.Empty, - Payload = JsonSerializer.SerializeToUtf8Bytes(payload), - PayloadAuditFields = auditFields, - }; - } - - /// - /// 构造榜上分数更新事件。 - /// - /// 榜单标识(可空;载荷落空字符串)。 - /// 玩家标识。 - /// 变更前分数。 - /// 变更后分数。 - /// 来源结算结果标识(追溯键,兼作 CorrelationId)。 - /// 变更时刻(UTC 毫秒)。 - /// 事件信封实例。 - public static OnlineEvent CreateScoreUpdated(string leaderboardId, long playerId, long oldScore, long newScore, string sourceMatchResultId, long updatedTime) - { - var payload = new ScoreUpdatedPayload - { - LeaderboardId = leaderboardId ?? string.Empty, - PlayerId = playerId, - OldScore = oldScore, - NewScore = newScore, - SourceKind = OnlineLeaderboardScoreSource.MatchResult.ToString(), - SourceMatchResultId = sourceMatchResultId ?? string.Empty, - UpdatedTime = updatedTime, - }; - var auditFields = new Dictionary - { - { "LeaderboardId", leaderboardId ?? string.Empty }, - { "PlayerId", playerId.ToString(CultureInfo.InvariantCulture) }, - { "OldScore", oldScore.ToString(CultureInfo.InvariantCulture) }, - { "NewScore", newScore.ToString(CultureInfo.InvariantCulture) }, - { "SourceKind", OnlineLeaderboardScoreSource.MatchResult.ToString() }, - { "SourceMatchResultId", sourceMatchResultId ?? string.Empty }, - { "UpdatedTime", updatedTime.ToString(CultureInfo.InvariantCulture) }, - }; - return new OnlineEvent - { - EventId = "evt-" + Guid.NewGuid().ToString("N"), - EventType = ScoreUpdated, - OccurredTime = updatedTime > 0 ? updatedTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), - SchemaVersion = 1, - ServerId = 0, - PlayerId = playerId, - Source = Source, - CorrelationId = sourceMatchResultId ?? string.Empty, - Payload = JsonSerializer.SerializeToUtf8Bytes(payload), - PayloadAuditFields = auditFields, - }; - } - - /// - /// 榜单创建事件负载(SchemaVersion=1)。 - /// - private sealed class LeaderboardCreatedPayload - { - /// 榜单标识。 - public string LeaderboardId { get; set; } - - /// 排序方向名。 - public string SortOrder { get; set; } - - /// 累计策略名。 - public string ScoreUpdatePolicy { get; set; } - - /// 创建时刻(UTC 毫秒)。 - public long CreatedTime { get; set; } - } - - /// - /// 榜上分数更新事件负载(SchemaVersion=1)。 - /// - private sealed class ScoreUpdatedPayload - { - /// 榜单标识。 - public string LeaderboardId { get; set; } - - /// 玩家标识。 - public long PlayerId { get; set; } - - /// 变更前分数。 - public long OldScore { get; set; } - - /// 变更后分数。 - public long NewScore { get; set; } - - /// 分数来源名。 - public string SourceKind { get; set; } - - /// 来源结算结果标识。 - public string SourceMatchResultId { get; set; } - - /// 变更时刻(UTC 毫秒)。 - public long UpdatedTime { get; set; } - } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardOptions.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardOptions.cs deleted file mode 100644 index 0ab14baeb..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardOptions.cs +++ /dev/null @@ -1,71 +0,0 @@ -// ========================================================================================== -// 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 see 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜组件选项(防刷阈值 / 限流窗口 / 读缓存;运行时装配注入,缺省值即安全默认)。 -/// -/// 维护约束:阈值调整只影响「拦多拦少」,不得改变拦截语义(越界 → 风控拒绝、高频 → 限流拒绝); -/// 压测需同时验证「高频被拦」与「正常节奏不受影响」两半。 -/// 缓存 TTL 只影响读延迟不影响正确性——任何写榜立即失效对应榜单缓存。 -/// -/// -public sealed class OnlineLeaderboardOptions -{ - /// - /// 获取或设置单次提交分数合理上限的全局默认值(榜单未显式配置时生效;取绝对值比较,正负同界)。 - /// - public long DefaultMaxScorePerSubmission { get; set; } = 1_000_000; - - /// - /// 获取或设置限流窗口内允许的提交次数(按 玩家 分桶;仅首次执行分支计数,幂等重放不烧配额)。 - /// - public int RateLimitMaxSubmissions { get; set; } = 120; - - /// - /// 获取或设置限流滑动窗口时长(秒)。 - /// - public int RateLimitWindowSeconds { get; set; } = 60; - - /// - /// 获取或设置是否启用 Top N 读缓存。 - /// - public bool CacheEnabled { get; set; } = true; - - /// - /// 获取或设置读缓存 TTL(秒;过期后下次查询重建快照,写榜立即失效不受 TTL 约束)。 - /// - public int CacheTtlSeconds { get; set; } = 5; - - /// - /// 获取或设置单页条目数上限(防一次拉全榜;请求超出按上限截断)。 - /// - public int MaxPageSize { get; set; } = 200; -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardOrdering.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardOrdering.cs deleted file mode 100644 index 2e32dc8ef..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardOrdering.cs +++ /dev/null @@ -1,114 +0,0 @@ -// ========================================================================================== -// 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 see 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 System; -using System.Collections.Generic; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜全序比较器(唯一名次口径:分数按榜向 → 更新时间升序 → 玩家标识升序)。 -/// -/// 维护约束(红线):这是 Top N / 附近排名 / 分页 / keyset 游标共用的**唯一**排序事实来源, -/// 禁止在服务或存储里另写一份比较逻辑;次级键保证同分玩家也有确定全序(先写入者靠前,再按玩家标识消解), -/// 名次无并列空洞、结果可复算。修改比较语义 = 修改全部查询口径,须先经设计评审。 -/// -/// -public static class OnlineLeaderboardOrdering -{ - /// - /// 按榜单方向比较两个条目的名次先后。 - /// - /// 榜单排序方向。 - /// 左条目。 - /// 右条目。 - /// 左条目名次靠前返回负数;靠后返回正数;同一玩家返回 0。 - public static int Compare(OnlineLeaderboardSortOrder sortOrder, OnlineLeaderboardEntry left, OnlineLeaderboardEntry right) - { - if (ReferenceEquals(left, right)) - { - return 0; - } - - if (left == null) - { - return 1; - } - - if (right == null) - { - return -1; - } - - var scoreComparison = sortOrder == OnlineLeaderboardSortOrder.Ascending - ? left.Score.CompareTo(right.Score) - : right.Score.CompareTo(left.Score); - if (scoreComparison != 0) - { - return scoreComparison; - } - - var timeComparison = left.LastUpdateTime.CompareTo(right.LastUpdateTime); - if (timeComparison != 0) - { - return timeComparison; - } - - return left.PlayerId.CompareTo(right.PlayerId); - } - - /// - /// 判定候选分数是否优于既有分数(Best 策略裁决口径,与名次方向同源)。 - /// - /// 榜单排序方向。 - /// 候选分数。 - /// 当前分数。 - /// 候选更优返回 true;持平或更差返回 false。 - public static bool IsBetter(OnlineLeaderboardSortOrder sortOrder, long candidateScore, long currentScore) - { - return sortOrder == OnlineLeaderboardSortOrder.Ascending - ? candidateScore < currentScore - : candidateScore > currentScore; - } - - /// - /// 以榜单方向对条目列表做全序排序(原位排序;调用方保证传入副本)。 - /// - /// 榜单排序方向。 - /// 待排序列表。 - public static void Sort(OnlineLeaderboardSortOrder sortOrder, List entries) - { - if (entries == null) - { - throw new ArgumentNullException(nameof(entries)); - } - - entries.Sort((left, right) => Compare(sortOrder, left, right)); - } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardPage.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardPage.cs deleted file mode 100644 index c698c3ea5..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardPage.cs +++ /dev/null @@ -1,58 +0,0 @@ -// ========================================================================================== -// 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 see 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 System.Collections.Generic; -using GameFrameX.Capability.Online.Abstractions.Contracts; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜分页结果(Top N / 翻页共用;keyset 游标,翻页期间新增数据不重复不漏项)。 -/// -/// 维护约束:游标由服务端按全序稳定键编码,客户端视为不透明令牌只回传不解释(稳定性约定沿用); -/// 翻页期间插入更高名次条目不会使后续页漏项或重复(keyset 语义,区别于偏移量分页)。 -/// -/// -public sealed class OnlineLeaderboardPage -{ - /// - /// 获取或设置本页条目(按榜单全序升序名次排列)。 - /// - public List Entries { get; set; } - - /// - /// 获取或设置分页游标(末页游标为空字符串)。 - /// - public OnlinePageCursor Cursor { get; set; } - - /// - /// 获取或设置榜单条目总数(当前快照口径)。 - /// - public long TotalCount { get; set; } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionFailure.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionFailure.cs deleted file mode 100644 index 7756441d6..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionFailure.cs +++ /dev/null @@ -1,54 +0,0 @@ -// ========================================================================================== -// 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 see 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 System.Collections.Generic; -using GameFrameX.Capability.Online.Abstractions.Contracts; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 单玩家投影失败明细(错误码 + 拒绝原因;逐玩家隔离,不阻塞其余玩家)。 -/// -public sealed class OnlineLeaderboardProjectionFailure -{ - /// - /// 获取或设置玩家标识。 - /// - public long PlayerId { get; set; } - - /// - /// 获取或设置失败错误码(防刷拒绝 / 限流 / 幂等冲突 / 占位繁忙等)。 - /// - public OnlineErrorCode Code { get; set; } - - /// - /// 获取或设置失败原因(脱敏后的可读描述,供日志与排查)。 - /// - public string Message { get; set; } -} diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs deleted file mode 100644 index 3084bc100..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOptions.cs +++ /dev/null @@ -1,49 +0,0 @@ -// ========================================================================================== -// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 -// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights -// 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the PRC and relevant 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜投影选项( 的子对象; -/// 默认投影到默认榜(C460:默认值服务黄金路径开箱即通—— -/// 零 JSON 配置起服即装配 Match.Settled 投影并在激活期预建默认榜);显式置空白 / null -/// 或经配置段覆盖为空白 = 关闭投影(不装配、不预建,不报错)。 -/// -public sealed class OnlineLeaderboardProjectionOptions -{ - /// - /// 默认投影目标榜单标识(Match.Settled 投影的默认榜;装配期由 Leaderboard 能力预建)。 - /// - public const string DefaultMatchSettledBoardId = "match-settled"; - - /// - /// 获取或设置 Match.Settled 事件的目标榜单标识(默认 = ;空白 = 不投影)。 - /// - public string MatchSettledBoardId { get; set; } = DefaultMatchSettledBoardId; -} diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOutcome.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOutcome.cs deleted file mode 100644 index b43a60e01..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionOutcome.cs +++ /dev/null @@ -1,69 +0,0 @@ -// ========================================================================================== -// 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 see 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 System.Collections.Generic; -using GameFrameX.Capability.Online.Abstractions.Contracts; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 可信结果投影回执(一次投递对一榜的逐玩家执行汇总)。 -/// -/// 维护约束:同结果事件重复投递时,首次 计入、后续全部计入 -/// (分数不重复累计); 是逐玩家隔离结果—— -/// 一个玩家被防刷 / 限流拒绝不影响同结果其余玩家落榜(「正常玩家不受影响」)。 -/// -/// -public sealed class OnlineLeaderboardProjectionOutcome -{ - /// - /// 获取或设置投影的结算结果标识。 - /// - public string MatchResultId { get; set; } - - /// - /// 获取或设置目标榜单标识。 - /// - public string LeaderboardId { get; set; } - - /// - /// 获取或设置本次首次落榜的玩家数。 - /// - public int AppliedCount { get; set; } - - /// - /// 获取或设置本次命中幂等回放(此前已落榜)的玩家数。 - /// - public int ReplayCount { get; set; } - - /// - /// 获取或设置被拒绝玩家的失败明细列表。 - /// - public List FailedPlayers { get; set; } = new(); -} diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionRetryStatus.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionRetryStatus.cs deleted file mode 100644 index b4b66f3f9..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardProjectionRetryStatus.cs +++ /dev/null @@ -1,57 +0,0 @@ -// ========================================================================================== -// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 -// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights -// 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the PRC and relevant 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.Online.Abstractions.Contracts; -using GameFrameX.Capability.Online.Abstractions.Events; -using GameFrameX.Capability.Online.Abstractions.Idempotency; -using GameFrameX.Capability.Online.Abstractions.Scope; -using GameFrameX.Capability.Online.Match; -using GameFrameX.Foundation.Idempotency; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜投影待重试条目状态(QueryStatus 投影形态)。 -/// -public sealed class OnlineLeaderboardProjectionRetryStatus -{ - /// 获取结算结果标识。 - public string MatchResultId { get; set; } - - /// 获取对局标识。 - public string MatchId { get; set; } - - /// 获取累计投递尝试次数。 - public int Attempts { get; set; } -} diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardRateLimiter.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardRateLimiter.cs deleted file mode 100644 index 49301c31c..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardRateLimiter.cs +++ /dev/null @@ -1,186 +0,0 @@ -// ========================================================================================== -// 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 see 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 System; -using System.Collections.Generic; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜提交限流器(防刷校验的高频半边:高频提交被拒、正常玩家不受影响)。 -/// -/// 维护约束(天花板):滑动窗口计数,按 PlayerId 分桶——阈值与窗口由 -/// 覆盖;只在幂等 Execute 分支计数(重放不烧配额)。 -/// 形态对齐 OnlineMatchRateLimiter / OnlineChatRateLimiter(滑动窗口,不新增依赖); -/// 桶在窗口过期后整桶重置,进程重启即清零——限流是速率保护不是配额,可接受;多实例共享存储归运行时装配。 -/// -/// -public sealed class OnlineLeaderboardRateLimiter -{ - /// 全局读写锁。 - private readonly object _syncRoot = new(); - - /// 窗口计数桶:键 = PlayerId。 - private readonly Dictionary _windows = new(); - - /// 上一次全量清扫时刻(UTC 毫秒)。 - private long _lastSweepAtTime; - - /// 窗口内允许的提交次数。 - private readonly int _maxSubmissions; - - /// 窗口时长(毫秒)。 - private readonly long _windowMilliseconds; - - /// - /// 初始化 。 - /// - /// 窗口内允许的提交次数(必须为正)。 - /// 窗口时长(秒;必须为正)。 - public OnlineLeaderboardRateLimiter(int maxSubmissions, int windowSeconds) - { - _maxSubmissions = maxSubmissions > 0 ? maxSubmissions : 1; - _windowMilliseconds = (windowSeconds > 0 ? windowSeconds : 1) * 1000L; - } - - /// - /// 清扫间隔(毫秒):取窗口时长与 60 秒的较大值,保证任何流量都会周期性推进过期桶回收。 - /// - private long SweepIntervalMilliseconds => _windowMilliseconds > 60000L ? _windowMilliseconds : 60000L; - - /// - /// 尝试为玩家获取一次提交配额(滑动窗口限流)。 - /// - /// - /// Tries to acquire one submission slot for the player within the sliding window. - /// - /// 玩家 ID / The player id - /// 当前 Unix 毫秒时间戳(0 表示取当前时间)/ The current Unix time in milliseconds (0 for now) - /// 窗口未满获取成功返回 true;已满返回 false / true if acquired within the window; false when the window is full - public bool TryAcquire(long playerId, long nowUnixMilliseconds = 0) - { - var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var key = playerId.ToString(System.Globalization.CultureInfo.InvariantCulture); - - lock (_syncRoot) - { - if (now - _lastSweepAtTime >= SweepIntervalMilliseconds) - { - SweepExpiredCore(now); - } - - if (!_windows.TryGetValue(key, out var window) || now - window.StartedAtTime >= _windowMilliseconds) - { - _windows[key] = new Window - { - StartedAtTime = now, - Count = 1, - }; - return true; - } - - if (window.Count >= _maxSubmissions) - { - return false; - } - - window.Count++; - return true; - } - } - - /// - /// 删除全部已过期的窗口桶(运维/测试可显式触发;TryAcquire 亦按清扫间隔自动触发)。 - /// - /// 当前 Unix 毫秒时间戳(0 表示取当前时间)/ The current Unix time in milliseconds (0 for now) - /// 本次删除的桶数量 / The number of expired buckets removed - public int SweepExpired(long nowUnixMilliseconds = 0) - { - var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - - lock (_syncRoot) - { - return SweepExpiredCore(now); - } - } - - /// - /// 锁内全量清扫过期桶(调用方必须已持有 )。 - /// - /// 当前时刻(UTC 毫秒)。 - /// 本次删除的桶数量。 - private int SweepExpiredCore(long now) - { - _lastSweepAtTime = now; - List expiredKeys = null; - foreach (var pair in _windows) - { - if (now - pair.Value.StartedAtTime >= _windowMilliseconds) - { - (expiredKeys ?? (expiredKeys = new List())).Add(pair.Key); - } - } - - if (expiredKeys == null) - { - return 0; - } - - for (var index = 0; index < expiredKeys.Count; index++) - { - _windows.Remove(expiredKeys[index]); - } - - return expiredKeys.Count; - } - - /// - /// 清空全部窗口(测试与运维重置用)。 - /// - public void Reset() - { - lock (_syncRoot) - { - _windows.Clear(); - } - } - - - /// - /// 滑动窗口计数桶。 - /// - private sealed class Window - { - /// 获取或设置窗口起始时刻(UTC 毫秒)。 - public long StartedAtTime { get; set; } - - /// 获取或设置窗口内已计数。 - public int Count { get; set; } - } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardResultProjector.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardResultProjector.cs deleted file mode 100644 index 120dfb553..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardResultProjector.cs +++ /dev/null @@ -1,244 +0,0 @@ -// ========================================================================================== -// 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 see 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 System; -using System.Globalization; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using GameFrameX.Capability.Online.Abstractions.Contracts; -using GameFrameX.Capability.Online.Abstractions.Idempotency; -using GameFrameX.Capability.Online.Match; -using GameFrameX.Capability.Online.Abstractions.Scope; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 可信结果写榜投影器(排行榜只接受服务端可信事件,客户端分数提交被拒绝)。 -/// -/// 维护约束(红线): -/// (1) **载荷零信任**——结算结果只从 (结算唯一落定点)按 -/// MatchId 读取,且核对调用方传入的 MatchResultId 与存储值一致;本类型不接受 -/// 任何调用方直接携带分数 / 结果载荷的入口(伪造标识 → ResourceNotFound,篡改载荷 → RiskControlRejected); -/// (2) **写入幂等**——复用 ,键确定性派生 -/// lb-{MatchResultId}-{LeaderboardId}-{PlayerId}(沿用「业务单号由结果标识派生」的既有约定), -/// 同结果事件重复投递只计一次;幂等记录过期后的重投残留与资产域同款; -/// (3) 逐玩家失败隔离——防刷 / 限流 / 幂等冲突只影响该玩家,不阻塞同结果其余玩家。 -/// -/// -public sealed class OnlineLeaderboardResultProjector -{ - /// 对局结算结果存储(可信事实唯一来源)。 - private readonly IOnlineMatchResultStore _matchResultStore; - - /// 排行榜服务(榜单解析 + 可信写入)。 - private readonly OnlineLeaderboardService _leaderboardService; - - /// 幂等服务。 - private readonly OnlineIdempotencyService _idempotencyService; - - /// - /// 初始化 。 - /// - /// 对局结算结果存储。 - /// 排行榜服务。 - /// 幂等服务。 - public OnlineLeaderboardResultProjector(IOnlineMatchResultStore matchResultStore, OnlineLeaderboardService leaderboardService, OnlineIdempotencyService idempotencyService) - { - _matchResultStore = matchResultStore ?? throw new ArgumentNullException(nameof(matchResultStore)); - _leaderboardService = leaderboardService ?? throw new ArgumentNullException(nameof(leaderboardService)); - _idempotencyService = idempotencyService ?? throw new ArgumentNullException(nameof(idempotencyService)); - } - - /// - /// 将一局已结算结果投影到目标榜单(幂等;逐玩家失败隔离)。 - /// - /// 生效作用域。 - /// 目标榜单标识。 - /// 对局标识(据此从结算存储读取结果)。 - /// 调用方持有的结果标识(与存储值核对,防伪造载荷)。 - /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 - /// 取消令牌。 - /// 投影回执(首次落榜数 / 回放数 / 逐玩家失败明细);失败返回对应错误码。 - public async Task> ProjectAsync(OnlineScope scope, string leaderboardId, string matchId, string expectedMatchResultId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) - { - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - - if (string.IsNullOrEmpty(leaderboardId)) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识不能为空"); - } - - if (string.IsNullOrEmpty(matchId)) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "对局标识不能为空"); - } - - if (string.IsNullOrEmpty(expectedMatchResultId)) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "结果标识不能为空"); - } - - var boardResult = await _leaderboardService.ResolveBoardAsync(scope, leaderboardId, cancellationToken).ConfigureAwait(false); - if (!boardResult.IsSuccess) - { - return OnlineResult.Fail(boardResult.Code, boardResult.Message); - } - - var board = boardResult.Data; - var stored = await _matchResultStore.FindByMatchAsync(matchId, cancellationToken).ConfigureAwait(false); - if (stored == null) - { - return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "对局结果不存在或未结算"); - } - - if (!string.Equals(stored.MatchResultId, expectedMatchResultId, StringComparison.Ordinal)) - { - return OnlineResult.Fail(OnlineErrorCode.RiskControlRejected, "结果标识与结算事实不一致"); - } - - var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var outcome = new OnlineLeaderboardProjectionOutcome - { - MatchResultId = stored.MatchResultId, - LeaderboardId = leaderboardId, - }; - - if (stored.Entries == null) - { - return OnlineResult.Ok(outcome); - } - - foreach (var entry in stored.Entries) - { - if (entry == null) - { - continue; - } - - await ProjectEntryAsync(board, stored, entry, now, outcome, cancellationToken).ConfigureAwait(false); - } - - return OnlineResult.Ok(outcome); - } - - /// - /// 投影单玩家条目:幂等判定 → 首次执行写入 → 落定幂等记录;失败逐玩家隔离。 - /// - /// 目标榜单。 - /// 可信结算结果。 - /// 结果条目。 - /// 当前时刻(UTC 毫秒)。 - /// 累计回执。 - /// 取消令牌。 - /// 完成通知。 - private async Task ProjectEntryAsync(OnlineLeaderboard board, OnlineMatchResult result, OnlineMatchResultEntry entry, long now, OnlineLeaderboardProjectionOutcome outcome, CancellationToken cancellationToken) - { - var playerScope = new OnlineScope(result.ServerId, entry.PlayerId); - var idempotencyKey = BuildIdempotencyKey(result.MatchResultId, board.LeaderboardId, entry.PlayerId); - var decision = await _idempotencyService.BeginAsync(playerScope, idempotencyKey, BuildCanonicalRequestText(result.MatchResultId, board.LeaderboardId, entry.PlayerId, entry.Score), true, cancellationToken).ConfigureAwait(false); - - if (decision.Kind == OnlineIdempotencyOutcomeKind.Replay) - { - outcome.ReplayCount++; - return; - } - - if (!decision.CanExecute) - { - outcome.FailedPlayers.Add(new OnlineLeaderboardProjectionFailure - { - PlayerId = entry.PlayerId, - Code = decision.ErrorCode, - Message = "幂等判定未放行:" + decision.Kind, - }); - return; - } - - var write = await _leaderboardService.ApplyTrustedScoreAsync(board, new OnlineLeaderboardScoreSubmission - { - PlayerId = entry.PlayerId, - IncomingScore = entry.Score, - SourceKind = OnlineLeaderboardScoreSource.MatchResult, - SourceMatchResultId = result.MatchResultId, - SubmittedTime = now, - }, now, cancellationToken).ConfigureAwait(false); - - if (write.IsSuccess) - { - await _idempotencyService.CompleteAsync(playerScope, idempotencyKey, Encoding.UTF8.GetBytes(write.Entry.Score.ToString(CultureInfo.InvariantCulture)), true, cancellationToken).ConfigureAwait(false); - outcome.AppliedCount++; - return; - } - - await _idempotencyService.FailAsync(playerScope, idempotencyKey, true, cancellationToken).ConfigureAwait(false); - outcome.FailedPlayers.Add(new OnlineLeaderboardProjectionFailure - { - PlayerId = entry.PlayerId, - Code = write.Code, - Message = write.Message, - }); - } - - /// - /// 构造确定性幂等键(同结果同榜同玩家重投同值)。 - /// - /// 结算结果标识。 - /// 榜单标识。 - /// 玩家标识。 - /// 幂等键。 - private static string BuildIdempotencyKey(string matchResultId, string leaderboardId, long playerId) - { - return string.Concat("lb-", matchResultId, "-", leaderboardId, "-", playerId.ToString(CultureInfo.InvariantCulture)); - } - - /// - /// 构造规范化请求文本(同一业务意图的重复投递必须产生相同文本,幂等摘要据此判定冲突)。 - /// - /// 结算结果标识。 - /// 榜单标识。 - /// 玩家标识。 - /// 本笔分数。 - /// 规范化请求文本。 - private static string BuildCanonicalRequestText(string matchResultId, string leaderboardId, long playerId, long score) - { - return string.Concat( - "leaderboard-score|", - matchResultId, - "|", - leaderboardId, - "|", - playerId.ToString(CultureInfo.InvariantCulture), - "|", - score.ToString(CultureInfo.InvariantCulture)); - } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreSource.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreSource.cs deleted file mode 100644 index e006e5dc3..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreSource.cs +++ /dev/null @@ -1,45 +0,0 @@ -// ========================================================================================== -// 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 see 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜分数来源(「分数来源」约束:每笔榜上分数必须可追溯到可信产生方)。 -/// -/// 维护约束(红线):第一版唯一合法来源是对局结算结果(Online.Match.Settled 可信事件链路); -/// 客户端直接提交的分数没有任何来源枚举值可承载——枚举即白名单,新增来源(如运营调整)必须先扩枚举并评审。 -/// -/// -public enum OnlineLeaderboardScoreSource -{ - /// - /// 权威对局结算结果(分数来自 OnlineMatchResultEntry.Score,经可信写入链路落榜)。 - /// - MatchResult = 1, -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreSubmission.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreSubmission.cs deleted file mode 100644 index 0f4d53bef..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreSubmission.cs +++ /dev/null @@ -1,66 +0,0 @@ -// ========================================================================================== -// 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 see 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜分数提交(单玩家单笔;只由可信写入链路构造,不暴露给客户端)。 -/// -/// 维护约束(红线):本类型是存储临界区的唯一写入载体——分数与来源由投影器从结算结果逐字段抄录, -/// 调用链上任何一层都不接受外部传入的「裸分数」; 仍须过防刷上限校验 -/// (可信链路也可能被上游缺陷 / 被攻陷结点灌入异常分数,防线不能省)。 -/// -/// -public sealed class OnlineLeaderboardScoreSubmission -{ - /// - /// 获取或设置玩家标识。 - /// - public long PlayerId { get; set; } - - /// - /// 获取或设置本笔提交分数(进入累计策略裁决前的原始值)。 - /// - public long IncomingScore { get; set; } - - /// - /// 获取或设置分数来源。 - /// - public OnlineLeaderboardScoreSource SourceKind { get; set; } - - /// - /// 获取或设置来源结算结果标识(追溯键)。 - /// - public string SourceMatchResultId { get; set; } - - /// - /// 获取或设置提交时刻(UTC 毫秒;写入条目的 LastUpdateTime)。 - /// - public long SubmittedTime { get; set; } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreUpdatePolicy.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreUpdatePolicy.cs deleted file mode 100644 index 2d8f926ea..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardScoreUpdatePolicy.cs +++ /dev/null @@ -1,56 +0,0 @@ -// ========================================================================================== -// 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 see 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜分数累计策略(「分数来源」语义的一部分:同玩家多次可信写入如何合并为榜上分数)。 -/// -/// 维护约束(红线):策略裁决必须发生在存储临界区内(InMemoryOnlineLeaderboardStore.ApplySubmissionAsync), -/// 与条目落档同一临界区,保证并发投递下「读旧值 → 算新值 → 写入」不被交错撕裂; -/// 服务层不得先读后写绕开该临界区。 -/// -/// -public enum OnlineLeaderboardScoreUpdatePolicy -{ - /// - /// 保留按榜向更优的分数(Descending 榜取更大值,Ascending 榜取更小值;首笔写入直接生效)。 - /// - Best = 0, - - /// - /// 累加全部写入分数(赛季积分类榜单;幂等重放不计入——重放在幂等层被拦截,不进入本策略)。 - /// - Sum = 1, - - /// - /// 以最近一次写入覆盖(连胜 / 当前段位类榜单)。 - /// - Latest = 2, -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardService.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardService.cs deleted file mode 100644 index 1d3bd44b8..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardService.cs +++ /dev/null @@ -1,577 +0,0 @@ -// ========================================================================================== -// 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 see 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 System; -using System.Collections.Generic; -using System.Globalization; -using System.Threading; -using System.Threading.Tasks; -using GameFrameX.Capability.Online.Abstractions.Contracts; -using GameFrameX.Capability.Online.Abstractions.Events; -using GameFrameX.Capability.Online.Abstractions.Scope; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜服务(创建 / Top N / 玩家附近排名 / 游标分页 / 读缓存;查询侧作用域反预言)。 -/// -/// 维护约束(红线): -/// (1) **本服务没有任何接受「裸分数」的公开提交 API**——分数写入只经内部 -/// (由可信写入链路 调用), -/// 客户端无入口可刷分; -/// (2) 作用域校验失败与「榜单不存在」同构返回 ResourceNotFound(反预言,不泄露榜单存在性); -/// (3) Top N 读缓存 TTL + 写失效——任何成功写榜立即失效该榜缓存,缓存只影响读延迟不影响正确性。 -/// -/// -public sealed class OnlineLeaderboardService -{ - /// 排行榜存储。 - private readonly IOnlineLeaderboardStore _store; - - /// 组件选项。 - private readonly OnlineLeaderboardOptions _options; - - /// 事件发布器(可空)。 - private readonly IOnlineEventPublisher _eventPublisher; - - /// 提交限流器(防刷高频半边)。 - private readonly OnlineLeaderboardRateLimiter _rateLimiter; - - /// 读缓存与缓存锁。 - private readonly object _cacheSyncRoot = new(); - - /// Top N 快照读缓存:键 = 榜单存储键。 - private readonly Dictionary _snapshotCache = new(); - - /// - /// 初始化 。 - /// - /// 排行榜存储。 - /// 组件选项(必填;默认值唯一来源 = 字段初始值)。 - /// 事件发布器(可空;未接线时不发事件)。 - public OnlineLeaderboardService(IOnlineLeaderboardStore store, OnlineLeaderboardOptions options, IOnlineEventPublisher eventPublisher = null) - { - _store = store ?? throw new ArgumentNullException(nameof(store)); - _options = options ?? throw new ArgumentNullException(nameof(options)); - _eventPublisher = eventPublisher; - _rateLimiter = new OnlineLeaderboardRateLimiter(_options.RateLimitMaxSubmissions, _options.RateLimitWindowSeconds); - } - - /// - /// 创建榜单(同名榜单已存在时拒绝;创建成功发布 Online.Leaderboard.Created 事件)。 - /// - /// 生效作用域(鉴权上下文产物)。 - /// 创建请求。 - /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 - /// 取消令牌。 - /// 创建后的榜单定义;失败返回对应错误码。 - public async Task> CreateAsync(OnlineScope scope, OnlineLeaderboardCreateRequest request, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) - { - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - - if (request == null) - { - throw new ArgumentNullException(nameof(request)); - } - - if (string.IsNullOrEmpty(request.LeaderboardId)) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识不能为空"); - } - - if (request.SortOrder != OnlineLeaderboardSortOrder.Descending && request.SortOrder != OnlineLeaderboardSortOrder.Ascending) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "排序方向取值非法"); - } - - if (request.ScoreUpdatePolicy != OnlineLeaderboardScoreUpdatePolicy.Best && request.ScoreUpdatePolicy != OnlineLeaderboardScoreUpdatePolicy.Sum && request.ScoreUpdatePolicy != OnlineLeaderboardScoreUpdatePolicy.Latest) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "累计策略取值非法"); - } - - if (request.MaxScorePerSubmission < 0) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "单次分数上限不得为负"); - } - - var board = new OnlineLeaderboard - { - LeaderboardId = request.LeaderboardId, - SortOrder = request.SortOrder, - ScoreUpdatePolicy = request.ScoreUpdatePolicy, - MaxScorePerSubmission = request.MaxScorePerSubmission, - CreatedTime = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), - }; - - var created = await _store.CreateAsync(board, cancellationToken).ConfigureAwait(false); - if (created == null) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识已存在"); - } - - await PublishAsync(OnlineLeaderboardEvents.CreateLeaderboardCreated(created.LeaderboardId, created.SortOrder.ToString(), created.ScoreUpdatePolicy.ToString(), created.CreatedTime), cancellationToken).ConfigureAwait(false); - return OnlineResult.Ok(created); - } - - /// - /// 查询 Top N(带 keyset 游标分页;游标由本服务编码,客户端不透明)。 - /// - /// 生效作用域。 - /// Top N 查询载荷。 - /// 取消令牌。 - /// 本页条目与后继游标;失败返回对应错误码。 - public async Task> GetTopAsync(OnlineScope scope, OnlineLeaderboardTopQuery query, CancellationToken cancellationToken = default) - { - if (query == null) - { - throw new ArgumentNullException(nameof(query)); - } - - var leaderboardId = query.LeaderboardId; - var count = query.Count; - var cursor = query.Cursor; - var nowUnixMilliseconds = query.NowUnixMilliseconds; - if (count <= 0) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "条目数必须为正"); - } - - var boardResult = await ResolveBoardAsync(scope, leaderboardId, cancellationToken).ConfigureAwait(false); - if (!boardResult.IsSuccess) - { - return OnlineResult.Fail(boardResult.Code, boardResult.Message); - } - - var board = boardResult.Data; - OnlineLeaderboardEntry cursorKey = null; - if (!string.IsNullOrEmpty(cursor)) - { - cursorKey = DecodeCursor(cursor); - if (cursorKey == null) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "分页游标非法"); - } - } - - var snapshot = await GetSnapshotAsync(board, nowUnixMilliseconds, cancellationToken).ConfigureAwait(false); - var pageSize = _options.MaxPageSize > 0 ? Math.Min(count, _options.MaxPageSize) : count; - var startIndex = cursorKey == null ? 0 : FindIndexAfter(snapshot, board.SortOrder, cursorKey); - var page = new OnlineLeaderboardPage - { - Entries = new List(), - TotalCount = snapshot.Count, - }; - - var index = startIndex; - while (index < snapshot.Count && page.Entries.Count < pageSize) - { - page.Entries.Add(new OnlineLeaderboardEntryView - { - Rank = index + 1, - Entry = snapshot[index].Copy(), - }); - index++; - } - - var hasMore = index < snapshot.Count; - page.Cursor = hasMore && page.Entries.Count > 0 - ? new OnlinePageCursor(EncodeCursor(page.Entries[page.Entries.Count - 1].Entry), true) - : new OnlinePageCursor(string.Empty, false); - return OnlineResult.Ok(page); - } - - /// - /// 查询玩家名次(未上榜返回 ResourceNotFound)。 - /// - /// 生效作用域。 - /// 榜单标识。 - /// 玩家标识。 - /// 当前时刻(UTC 毫秒;传 0 取系统时钟)。 - /// 取消令牌。 - /// 条目与名次视图;失败返回对应错误码。 - public async Task> GetPlayerRankAsync(OnlineScope scope, string leaderboardId, long playerId, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) - { - var boardResult = await ResolveBoardAsync(scope, leaderboardId, cancellationToken).ConfigureAwait(false); - if (!boardResult.IsSuccess) - { - return OnlineResult.Fail(boardResult.Code, boardResult.Message); - } - - var snapshot = await GetSnapshotAsync(boardResult.Data, nowUnixMilliseconds, cancellationToken).ConfigureAwait(false); - var index = snapshot.FindIndex(entry => entry.PlayerId == playerId); - if (index < 0) - { - return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "玩家未上榜"); - } - - return OnlineResult.Ok(new OnlineLeaderboardEntryView - { - Rank = index + 1, - Entry = snapshot[index].Copy(), - }); - } - - /// - /// 查询玩家附近排名(窗口含玩家本人,边界处截断)。 - /// - /// 生效作用域。 - /// 附近排名窗口查询载荷。 - /// 取消令牌。 - /// 附近排名窗口;失败返回对应错误码。 - public async Task> GetAroundPlayerAsync(OnlineScope scope, OnlineLeaderboardAroundQuery query, CancellationToken cancellationToken = default) - { - if (query == null) - { - throw new ArgumentNullException(nameof(query)); - } - - var leaderboardId = query.LeaderboardId; - var playerId = query.PlayerId; - var before = query.Before; - var after = query.After; - var nowUnixMilliseconds = query.NowUnixMilliseconds; - if (before < 0 || after < 0) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "附近排名窗口不得为负"); - } - - var boardResult = await ResolveBoardAsync(scope, leaderboardId, cancellationToken).ConfigureAwait(false); - if (!boardResult.IsSuccess) - { - return OnlineResult.Fail(boardResult.Code, boardResult.Message); - } - - var snapshot = await GetSnapshotAsync(boardResult.Data, nowUnixMilliseconds, cancellationToken).ConfigureAwait(false); - var index = snapshot.FindIndex(entry => entry.PlayerId == playerId); - if (index < 0) - { - return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "玩家未上榜"); - } - - var view = new OnlineLeaderboardAroundView - { - PlayerId = playerId, - Rank = index + 1, - TotalCount = snapshot.Count, - Around = new List(), - }; - - var startIndex = Math.Max(0, index - before); - var endIndex = Math.Min(snapshot.Count - 1, index + after); - for (var windowIndex = startIndex; windowIndex <= endIndex; windowIndex++) - { - view.Around.Add(new OnlineLeaderboardEntryView - { - Rank = windowIndex + 1, - Entry = snapshot[windowIndex].Copy(), - }); - } - - return OnlineResult.Ok(view); - } - - /// - /// 内部:解析榜单定义(不存在同构返回失败 ResourceNotFound)。 - /// - /// 生效作用域。 - /// 榜单标识。 - /// 取消令牌。 - /// 榜单定义;不存在返回失败。 - internal async Task> ResolveBoardAsync(OnlineScope scope, string leaderboardId, CancellationToken cancellationToken = default) - { - if (scope == null) - { - throw new ArgumentNullException(nameof(scope)); - } - - if (string.IsNullOrEmpty(leaderboardId)) - { - return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识不能为空"); - } - - var board = await _store.FindAsync(leaderboardId, cancellationToken).ConfigureAwait(false); - if (board == null) - { - return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "排行榜不存在"); - } - - return OnlineResult.Ok(board); - } - - /// - /// 内部:可信分数写入(防刷上限 + 限流 + 原子落榜 + 缓存失效 + 事件;幂等由投影器承载,本方法不重复判定)。 - /// - /// 目标榜单(调用方已解析)。 - /// 分数提交。 - /// 当前时刻(UTC 毫秒;传 0 取系统时钟)。 - /// 取消令牌。 - /// 写入回执(成功含条目与旧分数,失败含错误码)。 - internal async Task ApplyTrustedScoreAsync(OnlineLeaderboard leaderboard, OnlineLeaderboardScoreSubmission submission, long nowUnixMilliseconds = 0, CancellationToken cancellationToken = default) - { - if (leaderboard == null) - { - throw new ArgumentNullException(nameof(leaderboard)); - } - - if (submission == null) - { - throw new ArgumentNullException(nameof(submission)); - } - - if (string.IsNullOrEmpty(submission.SourceMatchResultId)) - { - return Failed(OnlineErrorCode.ParameterInvalid, "分数来源结算结果标识缺失"); - } - - var maxScore = leaderboard.MaxScorePerSubmission > 0 ? leaderboard.MaxScorePerSubmission : _options.DefaultMaxScorePerSubmission; - if (maxScore > 0 && Math.Abs(submission.IncomingScore) > maxScore) - { - return Failed(OnlineErrorCode.RiskControlRejected, "分数超出合理范围,已风控拒绝"); - } - - var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - if (!_rateLimiter.TryAcquire(submission.PlayerId, now)) - { - return Failed(OnlineErrorCode.RateLimitExceeded, "提交过于频繁,已限流"); - } - - var applied = await _store.ApplySubmissionAsync(leaderboard, submission, cancellationToken).ConfigureAwait(false); - if (applied == null) - { - // Sum 累加溢出被存储层拒绝:条目保持原值,不发事件、不失效缓存(消息承载榜单/玩家/本笔分数供观测定位;原分数以榜上条目为准)。 - return Failed(OnlineErrorCode.ParameterInvalid, string.Format(CultureInfo.InvariantCulture, "累计分数超出范围,已拒绝写入:leaderboardId={0}, playerId={1}, incomingScore={2}", leaderboard.LeaderboardId, submission.PlayerId, submission.IncomingScore)); - } - - InvalidateCache(leaderboard); - await PublishAsync(OnlineLeaderboardEvents.CreateScoreUpdated(leaderboard.LeaderboardId, submission.PlayerId, applied.OldScore, applied.Entry.Score, submission.SourceMatchResultId, applied.Entry.LastUpdateTime), cancellationToken).ConfigureAwait(false); - - return new OnlineLeaderboardWriteOutcome - { - IsSuccess = true, - Entry = applied.Entry, - OldScore = applied.OldScore, - }; - } - - /// - /// 内部:读取榜单全序条目(赛季结束取快照专用;**绕过读缓存直读存储**——快照必须是重置前的最新事实, - /// 取到缓存旧值会漏掉刚刚落榜的成绩)。 - /// - /// 目标榜单(调用方已解析)。 - /// 取消令牌。 - /// 全序条目副本。 - internal Task> ListOrderedEntriesForSeasonAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default) - { - if (leaderboard == null) - { - throw new ArgumentNullException(nameof(leaderboard)); - } - - return _store.ListOrderedEntriesAsync(leaderboard, cancellationToken); - } - - /// - /// 内部:赛季重置清空榜单条目(CAS;成功后**立即失效读缓存**——否则重置后 TTL 内仍会返回旧榜)。 - /// - /// 目标榜单(调用方已解析)。 - /// 调用方持有的全序条目快照(CAS 判据)。 - /// 取消令牌。 - /// 清空成功返回 true;榜上条目已变化返回 false。 - internal async Task TryResetForSeasonAsync(OnlineLeaderboard leaderboard, IReadOnlyList expectedEntries, CancellationToken cancellationToken = default) - { - if (leaderboard == null) - { - throw new ArgumentNullException(nameof(leaderboard)); - } - - var reset = await _store.TryResetAsync(leaderboard, expectedEntries, cancellationToken).ConfigureAwait(false); - if (reset) - { - InvalidateCache(leaderboard); - } - - return reset; - } - - /// - /// 构造失败回执。 - /// - /// 错误码。 - /// 原因。 - /// 失败回执。 - private static OnlineLeaderboardWriteOutcome Failed(OnlineErrorCode code, string message) - { - return new OnlineLeaderboardWriteOutcome - { - IsSuccess = false, - Code = code, - Message = message, - }; - } - - /// - /// 读取榜单全序快照(缓存命中直接返回;未启用缓存或过期时从存储重建并回填缓存)。 - /// - /// 榜单定义。 - /// 当前时刻(UTC 毫秒;缓存 TTL 判定)。 - /// 取消令牌。 - /// 全序快照(服务私有,调用方不得改写)。 - private async Task> GetSnapshotAsync(OnlineLeaderboard leaderboard, long nowUnixMilliseconds, CancellationToken cancellationToken) - { - var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var cacheKey = leaderboard.LeaderboardId ?? string.Empty; - if (_options.CacheEnabled) - { - lock (_cacheSyncRoot) - { - if (_snapshotCache.TryGetValue(cacheKey, out var slot) && slot.ExpiresAtTime > now) - { - return slot.Snapshot; - } - } - } - - var snapshot = await _store.ListOrderedEntriesAsync(leaderboard, cancellationToken).ConfigureAwait(false); - if (_options.CacheEnabled && _options.CacheTtlSeconds > 0) - { - lock (_cacheSyncRoot) - { - _snapshotCache[cacheKey] = new CacheSlot - { - Snapshot = snapshot, - ExpiresAtTime = now + _options.CacheTtlSeconds * 1000L, - }; - } - } - - return snapshot; - } - - /// - /// 失效榜单读缓存(任何成功写榜后调用)。 - /// - /// 榜单定义。 - private void InvalidateCache(OnlineLeaderboard leaderboard) - { - var cacheKey = leaderboard.LeaderboardId ?? string.Empty; - lock (_cacheSyncRoot) - { - _snapshotCache.Remove(cacheKey); - } - } - - /// - /// 编码 keyset 游标(稳定排序键三元组;客户端视为不透明令牌)。 - /// - /// 游标锚点条目。 - /// 游标字符串。 - private static string EncodeCursor(OnlineLeaderboardEntry entry) - { - return string.Concat( - entry.Score.ToString(CultureInfo.InvariantCulture), - ":", - entry.LastUpdateTime.ToString(CultureInfo.InvariantCulture), - ":", - entry.PlayerId.ToString(CultureInfo.InvariantCulture)); - } - - /// - /// 解码 keyset 游标为伪条目(仅稳定排序键三字段有效)。 - /// - /// 游标字符串。 - /// 伪条目;无法解析返回 null。 - private static OnlineLeaderboardEntry DecodeCursor(string cursor) - { - var parts = cursor.Split(':'); - if (parts.Length != 3) - { - return null; - } - - if (!long.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var score) - || !long.TryParse(parts[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var time) - || !long.TryParse(parts[2], NumberStyles.Integer, CultureInfo.InvariantCulture, out var playerId)) - { - return null; - } - - return new OnlineLeaderboardEntry { PlayerId = playerId, Score = score, LastUpdateTime = time, }; - } - - /// - /// 在全序快照中定位「严格晚于游标键」的首个下标(keyset 语义:翻页期间新增不重不漏)。 - /// - /// 全序快照。 - /// 排序方向。 - /// 游标伪条目。 - /// 起始下标;游标键晚于全部条目时为快照长度。 - private static int FindIndexAfter(List snapshot, OnlineLeaderboardSortOrder sortOrder, OnlineLeaderboardEntry cursorKey) - { - for (var index = 0; index < snapshot.Count; index++) - { - if (OnlineLeaderboardOrdering.Compare(sortOrder, snapshot[index], cursorKey) > 0) - { - return index; - } - } - - return snapshot.Count; - } - - /// - /// 发布事件(发布器可空;发布失败不改变已落定的写入事实)。 - /// - /// 待发布事件。 - /// 取消令牌。 - /// 完成通知。 - private async Task PublishAsync(OnlineEvent onlineEvent, CancellationToken cancellationToken) - { - if (_eventPublisher == null) - { - return; - } - - await _eventPublisher.PublishAsync(onlineEvent, cancellationToken).ConfigureAwait(false); - } - - /// - /// 读缓存槽(榜单全序快照 + 绝对过期时刻)。 - /// - private sealed class CacheSlot - { - /// 获取或设置全序条目快照。 - public List Snapshot { get; set; } - - /// 获取或设置过期时刻(UTC 毫秒)。 - public long ExpiresAtTime { get; set; } - } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardSortOrder.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardSortOrder.cs deleted file mode 100644 index e800554ff..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardSortOrder.cs +++ /dev/null @@ -1,50 +0,0 @@ -// ========================================================================================== -// 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 see 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 排行榜排序方向(第一版个人榜支持高分优先与低分优先两种方向)。 -/// -/// 维护约束:方向在榜单创建时固化,写入侧(「更好分数」的判定)与查询侧(Top N / 附近排名 / 分页) -/// 必须使用同一方向语义(统一经 比较),禁止两处各写一份判定。 -/// -/// -public enum OnlineLeaderboardSortOrder -{ - /// - /// 分数高者排名靠前(竞技得分榜默认)。 - /// - Descending = 0, - - /// - /// 分数低者排名靠前(用时榜 / 步数榜等「越小越好」语义)。 - /// - Ascending = 1, -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardWriteOutcome.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardWriteOutcome.cs deleted file mode 100644 index d94f36c0c..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineLeaderboardWriteOutcome.cs +++ /dev/null @@ -1,65 +0,0 @@ -// ========================================================================================== -// 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 see 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! -// 本项目组织与贡献者概不承担。 -// 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.Capability.Online.Abstractions.Contracts; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// 可信写入单玩家执行回执(服务内部类型:投影器在幂等 Execute 分支内调用写入,承载成功条目或拒绝码)。 -/// -/// 维护约束:失败语义与错误码段位固定(分数越界 → RiskControlRejected;高频 → RateLimitExceeded), -/// 调用方(投影器)据此决定幂等记录落 Fail 并逐玩家隔离;本类型不进公共 API 面。 -/// -/// -internal sealed class OnlineLeaderboardWriteOutcome -{ - /// - /// 获取或设置是否成功落榜。 - /// - public bool IsSuccess { get; set; } - - /// - /// 获取或设置失败错误码(失败时有效)。 - /// - public OnlineErrorCode Code { get; set; } - - /// - /// 获取或设置失败原因(失败时有效)。 - /// - public string Message { get; set; } - - /// - /// 获取或设置落榜后的条目副本(成功时有效)。 - /// - public OnlineLeaderboardEntry Entry { get; set; } - - /// - /// 获取或设置落榜前分数(成功时有效;事件载荷的 OldScore)。 - /// - public long OldScore { get; set; } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineMatchSettledLeaderboardProjector.cs b/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineMatchSettledLeaderboardProjector.cs deleted file mode 100644 index 723f6d7f5..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/Leaderboard/OnlineMatchSettledLeaderboardProjector.cs +++ /dev/null @@ -1,371 +0,0 @@ -// ========================================================================================== -// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 -// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights -// 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the PRC and relevant 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.Online.Abstractions.Contracts; -using GameFrameX.Capability.Online.Abstractions.Events; -using GameFrameX.Capability.Online.Abstractions.Idempotency; -using GameFrameX.Capability.Online.Abstractions.Scope; -using GameFrameX.Capability.Online.Match; -using GameFrameX.Foundation.Idempotency; - -namespace GameFrameX.Capability.Online.Competition.Leaderboard; - -/// -/// Match.Settled → 排行榜投影订阅体:消费对局结算完成事件,经 -/// (可信源 result store + MatchResultId 核对 + 幂等键) -/// 投影到预置榜单;失败进待重试表,由 tick job leaderboard-projection-retry 逐轮重投。 -/// -/// 维护约束(红线): -/// (1) **双层去重**——(EventId 去重,Operations 审计桥先例)挡同事件重投, -/// 投影器幂等键(lb-{MatchResultId}-{LeaderboardId}-{PlayerId})挡不同 EventId 同结果的重复投递; -/// (2) **异常不外抛**——订阅体异常吞掉记录(先例:Operations 审计桥「投影异常不得阻断业务事件分发」), -/// 失败只进待重试表经 可观测;不可解析载荷无从重投,直接丢弃; -/// (3) **终态裁决**——重投时结果事实已不存在(store 清理)视作不可投影终态,移除待重试条目。 -/// -/// -public sealed class OnlineMatchSettledLeaderboardProjector -{ - /// 可信结果写榜投影器(真实投影执行体)。 - private readonly OnlineLeaderboardResultProjector _projector; - - /// 对局结算结果存储(终态裁决用)。 - private readonly IOnlineMatchResultStore _matchResultStore; - - /// 目标榜单标识。 - private readonly string _leaderboardId; - - /// EventId 去重消费者(同事件重投短路)。 - private readonly OnlineEventConsumer _consumer; - - /// 待重试表与并发锁。 - private readonly object _pendingLock = new(); - - /// 待重试条目(键 = MatchResultId,去重)。 - private readonly Dictionary _pending = new(StringComparer.Ordinal); - - /// - /// 初始化 。 - /// - /// 对局结算结果存储(可信事实唯一来源)。 - /// 排行榜服务。 - /// 幂等服务。 - /// 目标榜单标识。 - public OnlineMatchSettledLeaderboardProjector(IOnlineMatchResultStore matchResultStore, OnlineLeaderboardService leaderboardService, OnlineIdempotencyService idempotencyService, string leaderboardId) - { - _matchResultStore = matchResultStore ?? throw new ArgumentNullException(nameof(matchResultStore)); - _projector = new OnlineLeaderboardResultProjector(matchResultStore, leaderboardService, idempotencyService); - _leaderboardId = leaderboardId ?? throw new ArgumentNullException(nameof(leaderboardId)); - _consumer = new OnlineEventConsumer(new InMemoryEventDeduplicator()); - } - - /// - /// 订阅体入口:解析 Match.Settled 载荷并投影到目标榜单;失败(榜单缺失 / 结果缺失 / 异常)记待重试, - /// 异常不向订阅方抛(吞掉记录)。 - /// - /// Online 事件(应为 Match.Settled)。 - /// 完成通知。 - public async Task HandleEventAsync(OnlineEvent onlineEvent) - { - MatchSettledPayload payload; - OnlineEvent sourceEvent = onlineEvent; - try - { - if (onlineEvent == null || onlineEvent.EventType != OnlineMatchRuntimeEvents.MatchSettled) - { - return; - } - - if (!_consumer.TryConsume(onlineEvent)) - { - return; - } - - payload = DeserializePayload(onlineEvent.Payload); - if (payload == null || string.IsNullOrEmpty(payload.MatchResultId) || string.IsNullOrEmpty(payload.MatchId)) - { - // 载荷不可解析 / 缺标识:无从重投,直接丢弃(不记待重试)。 - return; - } - } - catch (Exception) - { - // 去重 / 解析段异常无从定位业务标识,吞掉不外抛、不记待重试。 - return; - } - - try - { - // 榜单级作用域(PlayerId=0):投影器内部逐玩家以结算事实重建 scope。 - var scope = new OnlineScope(sourceEvent.ServerId, 0); - var projected = await _projector.ProjectAsync(scope, _leaderboardId, payload.MatchId, payload.MatchResultId).ConfigureAwait(false); - if (!projected.IsSuccess) - { - RecordPending(sourceEvent, payload); - } - } - catch (Exception) - { - // 投影段异常同样记待重试(重投幂等键保证不双计);不向订阅方抛。 - RecordPending(sourceEvent, payload); - } - } - - /// - /// 重投待重试条目(幂等键保证不双计):成功或结果事实已不存在(不可投影终态)移除;失败 Attempts++ 保留。 - /// - /// 取消令牌。 - /// 完成通知。 - - public async Task RetryPendingAsync(CancellationToken cancellationToken) - { - PendingProjection[] snapshot; - lock (_pendingLock) - { - if (_pending.Count == 0) - { - return; - } - - snapshot = new PendingProjection[_pending.Count]; - _pending.Values.CopyTo(snapshot, 0); - } - - foreach (var entry in snapshot) - { - var stored = await _matchResultStore.FindByMatchAsync(entry.MatchId, cancellationToken).ConfigureAwait(false); - if (stored == null) - { - // 结果已被清理:不可投影终态,移除。 - RemovePending(entry.MatchResultId); - continue; - } - - var scope = new OnlineScope(entry.ServerId, 0); - var projected = await _projector.ProjectAsync(scope, _leaderboardId, entry.MatchId, entry.MatchResultId, 0, cancellationToken).ConfigureAwait(false); - if (projected.IsSuccess) - { - RemovePending(entry.MatchResultId); - } - else - { - BumpPending(entry.MatchResultId); - } - } - } - - /// - /// 查询待重试条目快照(admin 可观测面;条目 = MatchResultId / MatchId / Attempts)。 - /// - /// 待重试条目副本。 - public IReadOnlyList QueryStatus() - { - lock (_pendingLock) - { - var items = new List(_pending.Count); - foreach (var entry in _pending.Values) - { - items.Add(new OnlineLeaderboardProjectionRetryStatus - { - MatchResultId = entry.MatchResultId, - MatchId = entry.MatchId, - Attempts = entry.Attempts, - }); - } - - return items; - } - } - - /// - /// 反序列化结算事件载荷(字段名与 MatchSettledPayload 线缆形态一致)。 - /// - /// UTF8 JSON 载荷。 - /// 载荷;不可解析返回 null。 - private static MatchSettledPayload DeserializePayload(ReadOnlyMemory payload) - { - if (payload.IsEmpty) - { - return null; - } - - try - { - return JsonSerializer.Deserialize(payload.Span); - } - catch (JsonException) - { - return null; - } - } - - /// - /// 记录待重试条目(按 MatchResultId 去重;重复失败 Attempts 不衰减)。 - /// - /// 来源事件(区服键)。 - /// 已解析载荷。 - private void RecordPending(OnlineEvent onlineEvent, MatchSettledPayload payload) - { - lock (_pendingLock) - { - if (_pending.TryGetValue(payload.MatchResultId, out var existing)) - { - existing.Attempts++; - return; - } - - _pending[payload.MatchResultId] = new PendingProjection - { - MatchResultId = payload.MatchResultId, - MatchId = payload.MatchId, - ServerId = onlineEvent.ServerId, - Attempts = 1, - }; - } - } - - /// - /// 移除待重试条目。 - /// - /// 结果标识。 - private void RemovePending(string matchResultId) - { - lock (_pendingLock) - { - _pending.Remove(matchResultId); - } - } - - /// - /// 重投失败:Attempts++ 保留。 - /// - /// 结果标识。 - private void BumpPending(string matchResultId) - { - lock (_pendingLock) - { - if (_pending.TryGetValue(matchResultId, out var existing)) - { - existing.Attempts++; - } - } - } - - /// - /// 反序列化结算事件载荷(字段名与 MatchSettledPayload 线缆形态一致)。 - /// - /// UTF8 JSON 载荷。 - /// 载荷;不可解析返回 null。 - private static MatchSettledPayload DeserializePayload(byte[] payload) - { - if (payload == null || payload.Length == 0) - { - return null; - } - - try - { - return JsonSerializer.Deserialize(payload); - } - catch (JsonException) - { - return null; - } - } - - /// - /// 结算事件负载(私有 DTO,字段名与 OnlineMatchRuntimeEvents 的 MatchSettledPayload 一致)。 - /// - private sealed class MatchSettledPayload - { - /// 结果标识(幂等边界)。 - public string MatchResultId { get; set; } - - /// 对局标识。 - public string MatchId { get; set; } - - /// 玩法模式。 - public int Mode { get; set; } - - /// 区域。 - public int Region { get; set; } - - /// 结束方式名。 - public string Outcome { get; set; } - - /// 结算时刻(UTC 毫秒)。 - public long SettledTime { get; set; } - - /// 玩家条目集合。 - public List Entries { get; set; } - } - - /// - /// 结算事件单玩家条目负载。 - /// - private sealed class MatchSettledEntryPayload - { - /// 玩家标识。 - public long PlayerId { get; set; } - - /// 名次。 - public int Rank { get; set; } - - /// 是否胜方。 - public bool IsWinner { get; set; } - - /// 玩法得分。 - public long Score { get; set; } - - /// 奖励条目数。 - public int RewardCount { get; set; } - } - - /// - /// 待重试条目(进程内易失,重启即失效)。 - /// - private sealed class PendingProjection - { - /// 结果标识。 - public string MatchResultId { get; set; } - - /// 对局标识。 - public string MatchId { get; set; } - - /// 区服标识。 - public long ServerId { get; set; } - - /// 累计投递尝试次数(首发失败 = 1)。 - public int Attempts { get; set; } - } -} diff --git a/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsCommand.cs b/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsCommand.cs deleted file mode 100644 index 72c5917bc..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsCommand.cs +++ /dev/null @@ -1,78 +0,0 @@ -// ========================================================================================== -// 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 related 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 see the LICENSE file in the root directory of the source code. -// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 -// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, -// 侵犯其他合法权益等法律法规所禁止的行为! -// or infringe upon the legitimate 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/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.LiveOps; - -/// -/// LiveOps 登记命令载荷(// -/// 的唯一提交形态;操作语义由 枚举承载)。 -/// -/// 维护约束:载荷原样登记(供查询端点回读),登记表 append-only——命令只追加不修改; -/// 六个字段历史上以相邻 string 摊排(位置互换零编译告警),收敛为命名字段后该风险消除。 -/// 语义下 不消费(实体 upsert 无版本概念)。 -/// -/// -public sealed class OnlineLiveOpsCommand -{ - /// - /// 获取或设置配置/实体种类(如 RemoteConfig / DeviceGroup / ScheduledTask / PlayerSegment / Announcement)。 - /// - /// Gets or sets the kind (e.g. RemoteConfig / DeviceGroup / ScheduledTask / PlayerSegment / Announcement). - public string Kind { get; init; } - - /// - /// 获取或设置种类内唯一键。 - /// - /// Gets or sets the kind-unique key. - public string Key { get; init; } - - /// - /// 获取或设置版本号(Publish/Rollback 使用;Sync 不消费)。 - /// - /// Gets or sets the version (used by Publish/Rollback; not consumed by Sync). - public string Version { get; init; } - - /// - /// 获取或设置载荷原文(原样登记,供查询端点回读)。 - /// - /// Gets or sets the raw payload text (registered as-is for read-back). - public string PayloadText { get; init; } - - /// - /// 获取或设置操作者。 - /// - /// Gets or sets the operator id. - public string OperatorId { get; init; } - - /// - /// 获取或设置关联标识。 - /// - /// Gets or sets the correlation id. - public string CorrelationId { get; init; } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsEntry.cs b/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsEntry.cs deleted file mode 100644 index bd8cfb6ad..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsEntry.cs +++ /dev/null @@ -1,60 +0,0 @@ -// ========================================================================================== -// 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, -// 侵犯他人合法权益等法律法规所禁止的行为! -// 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://cnb.cool/GameFrameX -// CNB 仓库:https://cnb.cool/GameFrameX -// CNB Repository: https://cnb.cool/GameFrameX -// 官方文档:https://gameframex.doc.alianblank.com/ -// Official Documentation: https://gameframex.doc.alianblank.com/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.LiveOps; - -/// -/// LiveOps 登记条目(append-only;载荷原样登记不解释,见 )。 -/// -public sealed class OnlineLiveOpsEntry -{ - /// 获取登记序号(进程内单调递增)。 - public long Sequence { get; set; } - - /// 获取登记操作。 - public OnlineLiveOpsOperation Operation { get; set; } - - /// 获取配置种类。 - public string Kind { get; set; } = string.Empty; - - /// 获取配置键。 - public string Key { get; set; } = string.Empty; - - /// 获取版本号(Sync 操作为空串)。 - public string Version { get; set; } = string.Empty; - - /// 获取载荷原文。 - public string PayloadText { get; set; } = string.Empty; - - /// 获取操作者。 - public string OperatorId { get; set; } = string.Empty; - - /// 获取关联标识。 - public string CorrelationId { get; set; } = string.Empty; - - /// 获取登记时刻(UTC 毫秒)。 - public long CreatedAtTime { get; set; } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsOperation.cs b/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsOperation.cs deleted file mode 100644 index 666519a49..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsOperation.cs +++ /dev/null @@ -1,42 +0,0 @@ -// ========================================================================================== -// 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, -// 侵犯他人合法权益等法律法规所禁止的行为! -// 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://cnb.cool/GameFrameX -// CNB 仓库:https://cnb.cool/GameFrameX -// CNB Repository: https://cnb.cool/GameFrameX -// 官方文档:https://gameframex.doc.alianblank.com/ -// Official Documentation: https://gameframex.doc.alianblank.com/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.LiveOps; - -/// -/// LiveOps 登记操作( append-only 登记表的条目操作语义)。 -/// -public enum OnlineLiveOpsOperation -{ - /// 发布版本。 - Publish = 0, - - /// 回滚版本。 - Rollback = 1, - - /// 同步实体(upsert)。 - Sync = 2, -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsRegistry.cs b/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsRegistry.cs deleted file mode 100644 index edf3252b6..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/LiveOps/OnlineLiveOpsRegistry.cs +++ /dev/null @@ -1,160 +0,0 @@ -// ========================================================================================== -// 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, -// 侵犯他人合法权益等法律法规所禁止的行为! -// 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://cnb.cool/GameFrameX -// CNB 仓库:https://cnb.cool/GameFrameX -// CNB Repository: https://cnb.cool/GameFrameX -// 官方文档:https://gameframex.doc.alianblank.com/ -// Official Documentation: https://gameframex.doc.alianblank.com/ -// ========================================================================================== - -namespace GameFrameX.Capability.Online.Competition.LiveOps; - -/// -/// LiveOps 最小承载(InMemory 版本登记表 + publish/rollback 语义)。 -/// -/// 维护约束:这是装配层对 Admin LiveOps 同步命令的**最小**承接(远端下发 / 灰度引擎不存在, -/// 只承担服务端半边)——只做 append-only 登记与最新版本视图,不实现灰度分流、设备分群计算、 -/// 定时触发等引擎语义(全量引擎另行演进);登记表不持久化(进程内,随宿主生命周期)。 -/// -/// -public sealed class OnlineLiveOpsRegistry -{ - /// - /// 同步锁(登记表为普通列表 + 字典,全部操作临界区内完成)。 - /// - private readonly object _sync = new(); - - /// - /// 登记表(append-only)。 - /// - private readonly List _entries = new(); - - /// - /// 最新条目索引(kind:key → 条目;回滚后指向回滚条目)。 - /// - private readonly Dictionary _latest = new(StringComparer.Ordinal); - - /// - /// 登记序号分配器。 - /// - private long _sequence; - - /// - /// 发布配置版本(同 kind+key 重复发布即追加新条目并接管最新视图)。 - /// - /// 登记命令载荷(Publish 语义:版本号参与登记)。 - /// 登记条目。 - public OnlineLiveOpsEntry Publish(OnlineLiveOpsCommand command) - { - return Append(OnlineLiveOpsOperation.Publish, command); - } - - /// - /// 回滚配置版本(登记回滚条目并接管最新视图;不删除历史条目)。 - /// - /// 登记命令载荷(Rollback 语义:版本号为被回滚到的目标版本)。 - /// 登记条目。 - public OnlineLiveOpsEntry Rollback(OnlineLiveOpsCommand command) - { - return Append(OnlineLiveOpsOperation.Rollback, command); - } - - /// - /// 同步实体(设备分群 / 定时任务 / 玩家分群等 upsert 语义:追加条目并接管最新视图)。 - /// - /// 登记命令载荷(Sync 语义:版本号不消费)。 - /// 登记条目。 - public OnlineLiveOpsEntry Sync(OnlineLiveOpsCommand command) - { - return Append(OnlineLiveOpsOperation.Sync, command); - } - - /// - /// 查询最新条目。 - /// - /// 配置种类。 - /// 配置键。 - /// 最新条目;无登记返回 null。 - public OnlineLiveOpsEntry FindLatest(string kind, string key) - { - lock (_sync) - { - _latest.TryGetValue(BuildKey(kind, key), out var entry); - return entry; - } - } - - /// - /// 按种类列出登记条目(时间倒序,最新在前)。 - /// - /// 配置种类(空串表示不限种类)。 - /// 最多返回条数。 - /// 条目列表。 - public IReadOnlyList List(string kind, int maxCount) - { - lock (_sync) - { - var source = string.IsNullOrEmpty(kind) - ? _entries - : _entries.Where(entry => string.Equals(entry.Kind, kind, StringComparison.Ordinal)).ToList(); - return source.OrderByDescending(entry => entry.Sequence).Take(Math.Max(1, maxCount)).ToList(); - } - } - - /// - /// 追加条目并接管最新视图。 - /// - /// 登记操作。 - /// 登记命令载荷。 - /// 登记条目。 - private OnlineLiveOpsEntry Append(OnlineLiveOpsOperation operation, OnlineLiveOpsCommand command) - { - var entry = new OnlineLiveOpsEntry - { - Sequence = Interlocked.Increment(ref _sequence), - Operation = operation, - Kind = command.Kind ?? string.Empty, - Key = command.Key ?? string.Empty, - Version = operation == OnlineLiveOpsOperation.Sync ? string.Empty : command.Version ?? string.Empty, - PayloadText = command.PayloadText ?? string.Empty, - OperatorId = command.OperatorId ?? string.Empty, - CorrelationId = command.CorrelationId ?? string.Empty, - CreatedAtTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), - }; - lock (_sync) - { - _entries.Add(entry); - _latest[BuildKey(entry.Kind, entry.Key)] = entry; - } - - return entry; - } - - /// - /// 构造最新视图索引键。 - /// - /// 配置种类。 - /// 配置键。 - /// 索引键。 - private static string BuildKey(string kind, string key) - { - return (kind ?? string.Empty) + ":" + (key ?? string.Empty); - } -} \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs index e68b61919..75ef289d1 100644 --- a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionCapabilityModule.cs @@ -1,101 +1,72 @@ -// ========================================================================================== +// ========================================================================================== // GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 // GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights // 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the PRC and relevant international regulations. -// 使用本项目须严格遵守相关法律法规与开源许可证之规定。 -// Usage of this project must strictly comply with relevant laws, regulations, and open-source licenses. +// are protected by the laws of the People's Republic of China and related 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 at the root of the source code for the full license text. +// please see 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! +// or infringe upon the legitimate 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 +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX // 官方文档:https://gameframex.doc.alianblank.com/ // Official documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== -using System; using System.Threading; using System.Threading.Tasks; using GameFrameX.Capability.Hosting.Abstractions; -using GameFrameX.Capability.Hosting.AdminApi; +using GameFrameX.Capability.Online.Abstractions.Events; using GameFrameX.Capability.Online.Assets; -using GameFrameX.Capability.Online.Competition.AdminApi; using GameFrameX.Capability.Online.Competition.Leaderboard; -using GameFrameX.Capability.Online.Competition.LiveOps; using GameFrameX.Capability.Online.Competition.Season; using GameFrameX.Capability.Online.Competition.Tournament; -using GameFrameX.Capability.Online.Abstractions.Contracts; -using GameFrameX.Capability.Online.Abstractions.Events; -using GameFrameX.Capability.Online.Abstractions.Idempotency; -using GameFrameX.Capability.Online.Abstractions.Scope; -using GameFrameX.Capability.Online.Match; +using GameFrameX.Localization; namespace GameFrameX.Capability.Online.Competition; /// -/// 竞技能力(榜单 / 赛季 / 锦标赛 / LiveOps 承载)的自装配模块(C294 迁入新机制三段生命周期)。 +/// 竞技能力(赛季 / 锦标赛)的自装配模块——冻结面:两部分均无消费方接线,按包结构收敛裁决标注 +/// frozen(不删除、不演进;榜单能力已拆至 online-leaderboard 独立包,LiveOps 运营面移交 Admin 仓)。 /// -/// 维护约束(服务共享协议):模块无参构造(扫描可发现);Register 自装配本域——榜单 / 赛季 / -/// 锦标赛三个 store 以懒默认描述符注册(族 / 宿主覆盖恒胜出,模块不感知);赛季 / 锦标赛对发放服务 -/// (,assets 域产物)的依赖经 manifest 可选声明 + GetOptionalService, -/// 缺席(assets 能力被过滤)时不装配两者;对外产物(榜单 / 赛季 / 锦标赛服务与 LiveOps 注册表)注册回 -/// 为唯一参数面(含榜单组件参数与 Match.Settled 投影配置, -/// 后者收编族级键 MatchBridgeLeaderboardId):投影榜 id 非空白(C460 起默认投影到默认榜 -/// ,显式空白可关闭)且对局结果存储 -/// (online-match 可选产物)在场时装配 Match.Settled 排行榜投影(机制总线订阅 + 失败重投 tick); -/// ActivateAsync 在投影榜 id 非空白时经榜单服务预建目标榜(查询-创建,见方法注释)。 +/// 维护约束(服务共享协议):模块无参构造(扫描可发现);Register 自装配本域——赛季 / 锦标赛两个 +/// store 以懒默认描述符注册(族 / 宿主覆盖恒胜出,模块不感知);对排行榜服务 +/// (,online-leaderboard 必选产物)与发放服务 +/// (,assets 域可选产物)的依赖经 manifest 声明 + Get 解析, +/// 任一缺席时不装配两者(必选缺席 = 装配失败 fail-fast);对外产物(赛季 / 锦标赛服务)注册回共享面。 /// /// -public sealed class OnlineCompetitionCapabilityModule : ICapabilityModule, IAdminActionContributor +public sealed class OnlineCompetitionCapabilityModule : ICapabilityModule { /// - /// 竞技能力清单(Id 冻结 = 终态包名;action 集合逐字迁移自壳过渡模块;可选依赖 online-assets / online-match - /// 经 声明,缺席时披露对应缺失功能名)。 + /// 竞技能力清单(Id 冻结 = 终态包名;必选依赖 online-leaderboard(赛季 / 锦标赛的榜单写路径), + /// 可选依赖 online-assets(奖励发放),缺席时披露对应缺失功能名;无 admin action—— + /// 榜单查询随榜单能力迁移,运营编排随 LiveOps 移交 Admin 仓)。 /// public static readonly CapabilityManifest ManifestInstance = new( "online-competition", "1.0.0", - new[] { "publishRemoteConfig", "syncDeviceGroup", "syncScheduledTask", "pushAnnouncement", "syncPlayerSegment", "publishConfigRollout", "rollbackConfigRollout", "query_leaderboard" }, null, + new[] { "online-leaderboard" }, new[] { - new CapabilityOptionalDependency("online-assets", Localization.Keys.Capability.OnlineModule.Competition.OptionalAssetsAbsent), - new CapabilityOptionalDependency("online-match", Localization.Keys.Capability.OnlineModule.Competition.OptionalMatchAbsent), + new CapabilityOptionalDependency("online-assets", Keys.Capability.OnlineModule.Competition.OptionalAssetsAbsent), }, - typeof(OnlineCompetitionOptions)); - - /// - /// LiveOps 注册表(Register 期构造;admin 面 handler 取用)。 - /// - private OnlineLiveOpsRegistry _liveOps; - - /// - /// 排行榜服务(Register 期构造;admin 面 handler、投影链与激活期榜单预建取用)。 - /// - private OnlineLeaderboardService _leaderboards; - - /// - /// Match.Settled 排行榜投影器(Register 期装配;投影配置空白或 online-match 缺席时为 null)。 - /// - private OnlineMatchSettledLeaderboardProjector _projectionProjector; - - /// - /// Match.Settled 投影目标榜单标识(Register 期从 Options 读出;空白 = 不投影不预建;ActivateAsync 预建判据)。 - /// - private string _projectionBoardId; + null); /// /// 获取竞技能力清单,固定返回静态实例 。 @@ -110,113 +81,54 @@ public CapabilityManifest Manifest } /// - /// 读取竞技能力选项,懒默认注册内存版排行榜、赛季、锦标赛存储并解析生效实例,构造并注册排行榜服务与活动运营注册表;发放服务在场时再注册赛季服务与锦标赛服务;投影榜单标识非空白且对局结果存储在场时,注册 Match.Settled 排行榜投影器、订阅对局结算事件并添加投影重试的 tick 任务。 + /// 懒默认注册内存版赛季、锦标赛存储并解析生效实例;排行榜服务与发放服务均在场时再注册赛季服务与锦标赛服务 + /// (必选 online-leaderboard 缺席 = 装配失败,不会进入本方法后的降级分支;可选 assets 缺席时静默跳过)。 /// /// - /// Reads , registers in-memory leaderboard / season / tournament stores as lazy - /// defaults and resolves the effective instances, then builds and registers the leaderboard service and the live-ops - /// registry. Season and tournament services are registered only when the optional grant service is present. When the - /// projection board id is not blank and the match result store is present, it registers the Match.Settled leaderboard - /// projector, subscribes it to the match-settled event and adds the leaderboard-projection-retry tick job; - /// otherwise the projection is silently skipped. + /// Registers in-memory season / tournament stores as lazy defaults and resolves the effective instances. + /// Season and tournament services are registered only when both the leaderboard service (required + /// online-leaderboard product) and the optional grant service are present. /// /// 能力注册上下文 / Capability registration context public void Register(CapabilityRegistrationContext context) { - var options = context.GetOptions(); - var eventPublisher = context.GetService(); - - // 三 store 懒默认描述符(族 / 宿主覆盖恒胜出;GetService 命中覆盖或本默认)。 - context.AddService(static _ => new InMemoryOnlineLeaderboardStore()); - var leaderboardStore = context.GetService(); + // 两 store 懒默认描述符(族 / 宿主覆盖恒胜出;GetService 命中覆盖或本默认)。 context.AddService(static _ => new InMemoryOnlineSeasonStore()); var seasonStore = context.GetService(); context.AddService(static _ => new InMemoryOnlineTournamentStore()); var tournamentStore = context.GetService(); - var leaderboards = new OnlineLeaderboardService(leaderboardStore, options.Leaderboard, eventPublisher); - _leaderboards = leaderboards; - context.AddService(leaderboards); - - _liveOps = new OnlineLiveOpsRegistry(); - context.AddService(_liveOps); - - // 发放服务(assets 域可选产物):在场才装配赛季 / 锦标赛(壳时代 Seasons / Tournaments 置 null 的模块化等价)。 + // 排行榜服务(online-leaderboard 必选产物)与发放服务(assets 域可选产物):双在场才装配 + // 赛季 / 锦标赛(壳时代 Seasons / Tournaments 置 null 的模块化等价)。 + var leaderboards = context.GetService(); var grantService = context.GetOptionalService(); if (grantService != null) { + var eventPublisher = context.GetService(); context.AddService(new OnlineSeasonService(seasonStore, leaderboards, grantService, eventPublisher)); context.AddService(new OnlineTournamentService(tournamentStore, leaderboards, grantService, eventPublisher)); } - - // Match.Settled → 排行榜投影:Options 投影榜 id 非空白(空白 = 不投影)且对局结果存储在场 - // (online-match 被过滤 → 不装配不报错)才装配;订阅走机制事件总线(Register 期声明, - // 单个订阅体异常由机制记日志后继续分发,业务侧不再自行吞异常),失败经 tick job 重投。 - _projectionBoardId = options.LeaderboardProjection.MatchSettledBoardId; - var projectionResultStore = context.GetOptionalService(); - if (!string.IsNullOrWhiteSpace(_projectionBoardId) && projectionResultStore != null) - { - var projectionIdempotency = context.GetService(); - var projector = new OnlineMatchSettledLeaderboardProjector(projectionResultStore, leaderboards, projectionIdempotency, _projectionBoardId); - _projectionProjector = projector; - context.AddService(projector); - context.Subscribe(OnlineMatchRuntimeEvents.MatchSettled, onlineEvent => _projectionProjector.HandleEventAsync(onlineEvent).GetAwaiter().GetResult()); - context.AddTickJob("leaderboard-projection-retry", cancellationToken => _projectionProjector.RetryPendingAsync(cancellationToken)); - } } /// - /// 投影榜单标识为空白时直接返回;否则以 Top 1 查询探测目标榜单,已存在则返回,返回资源不存在时按累加计分、降序排序创建该榜单。 + /// 激活阶段无需处理(榜单预建与投影随榜单能力迁移至 online-leaderboard 包),直接返回已完成任务。 /// /// - /// Returns immediately when the projection board id is blank. Otherwise probes the target board with a top-1 query; - /// if it already exists nothing else happens, and if the probe reports resource-not-found the board is created with - /// the sum score-update policy and descending sort order. Any other failure aborts activation so the host can roll back. + /// Nothing to do on activation: board pre-building and the settled projection moved to the online-leaderboard package. /// - /// 能力激活上下文,用于解析 Online 作用域 / Capability activation context used to resolve the Online scope + /// 能力激活上下文 / Capability activation context /// 取消令牌 / Cancellation token - /// 表示异步激活操作的任务 / Task representing the asynchronous activation - /// 探测返回资源不存在以外的失败码,或创建榜单失败 / The probe fails with a code other than resource-not-found, or creating the board fails - public async Task ActivateAsync(CapabilityActivationContext context, CancellationToken cancellationToken) + /// 已完成的任务 / Completed task + public Task ActivateAsync(CapabilityActivationContext context, CancellationToken cancellationToken) { - if (string.IsNullOrWhiteSpace(_projectionBoardId)) - { - return; - } - - // 榜单预建(迁自 Launcher OnlineMatchBridgeWiring.EnsureMatchLeaderboardBoardAsync):投影目标榜 - // 查询-创建——GetTop 探针命中即已存在;ResourceNotFound 视作首建,按 Sum / Descending 创建; - // 其余失败码或创建失败 = 激活失败(抛 InvalidOperationException 由机制逆序回滚)。 - var scope = context.Services.GetService(); - var probe = await _leaderboards.GetTopAsync(scope, new OnlineLeaderboardTopQuery { LeaderboardId = _projectionBoardId, Count = 1, }, cancellationToken).ConfigureAwait(false); - if (probe.IsSuccess) - { - return; - } - - if (probe.Code != OnlineErrorCode.ResourceNotFound) - { - throw new InvalidOperationException("Leaderboard pre-build probe failed for board '" + _projectionBoardId + "' (code: " + probe.Code + ")."); - } - - var created = await _leaderboards.CreateAsync(scope, new OnlineLeaderboardCreateRequest - { - LeaderboardId = _projectionBoardId, - SortOrder = OnlineLeaderboardSortOrder.Descending, - ScoreUpdatePolicy = OnlineLeaderboardScoreUpdatePolicy.Sum, - }, 0, cancellationToken).ConfigureAwait(false); - if (!created.IsSuccess) - { - throw new InvalidOperationException("Leaderboard pre-build create failed for board '" + _projectionBoardId + "' (code: " + created.Code + ")."); - } + return Task.CompletedTask; } /// - /// 停用阶段无需处理:事件订阅与 tick 任务由宿主机制在注册时托管,激活仅预建榜单而不持有运行资源,直接返回已完成任务。 + /// 停用阶段无需处理:本模块不持有需要释放的运行资源,直接返回已完成任务。 /// /// - /// Nothing to do on deactivation: the event subscription and tick job are declared to the host during registration, - /// and activation only pre-creates the board without holding runtime resources, so a completed task is returned. + /// Nothing to do on deactivation: the module holds no runtime resources. /// /// 取消令牌 / Cancellation token /// 已完成的任务 / Completed task @@ -224,18 +136,4 @@ public Task DeactivateAsync(CancellationToken cancellationToken) { return Task.CompletedTask; } - - /// - /// 基于注册阶段构造的活动运营注册表登记活动运营管理动作,并基于排行榜服务登记排行榜查询管理动作。 - /// - /// - /// Registers the live-ops admin actions backed by the live-ops registry and the leaderboard query admin actions backed - /// by the leaderboard service, both built during registration. - /// - /// 管理动作注册表 / Admin action registry - public void RegisterAdminActions(AdminActionRegistry registry) - { - OnlineAdminLiveOpsHandlers.RegisterLiveOps(registry, _liveOps); - OnlineAdminLeaderboardHandlers.RegisterLeaderboardQuery(registry, _leaderboards); - } } diff --git a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs b/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs deleted file mode 100644 index e015d44fd..000000000 --- a/Capability/GameFrameX.Capability.Online.Competition/OnlineCompetitionOptions.cs +++ /dev/null @@ -1,104 +0,0 @@ -// ========================================================================================== -// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 -// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights -// 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the PRC and relevant 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 GameFrameX.Capability.Hosting.Abstractions; -using GameFrameX.Capability.Online.Competition.Leaderboard; - -namespace GameFrameX.Capability.Online.Competition; - -/// -/// 竞技能力包级 Options 根类型(C294:聚合榜单组件参数与 Match.Settled 投影配置; -/// 投影子对象收编族级键 MatchBridgeLeaderboardId → Settings.online-competition.LeaderboardProjection.MatchSettledBoardId, -/// 默认值唯一来源 = 字段初始值)。 -/// -public sealed class OnlineCompetitionOptions : ICapabilityOptions -{ - /// - /// 获取或设置排行榜组件选项(防刷阈值 / 限流窗口 / 读缓存 / 分页上限)。 - /// - public OnlineLeaderboardOptions Leaderboard { get; set; } = new OnlineLeaderboardOptions(); - - /// - /// 获取或设置 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 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) - { - validation.RequirePositive("Leaderboard.DefaultMaxScorePerSubmission", Leaderboard.DefaultMaxScorePerSubmission); - validation.RequirePositive("Leaderboard.RateLimitMaxSubmissions", Leaderboard.RateLimitMaxSubmissions); - 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.Leaderboard/AdminApi/OnlineAdminLeaderboardHandlers.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/AdminApi/OnlineAdminLeaderboardHandlers.cs index 0c15b3f6c..c4eea3308 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/AdminApi/OnlineAdminLeaderboardHandlers.cs +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/AdminApi/OnlineAdminLeaderboardHandlers.cs @@ -40,7 +40,7 @@ namespace GameFrameX.Capability.Online.Competition.AdminApi; /// /// 排行榜域 admin 命令(query_leaderboard——只读榜单查询:单元信息 + Top 条目 + 可选玩家附近窗口)。 /// -/// 维护约束:只读幂等包裹 false(无状态变更,与 query_match_settlement 同族);跨 App / 跨租户与 +/// 维护约束:只读幂等包裹 false(无状态变更,与 query_match_settlement 同族);作用域校验失败与 /// 榜单不存在同构 ResourceNotFound(排行榜服务反预言红线);玩家附近窗口为尽力投影(玩家未上榜时省略)。 /// /// diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/GameFrameX.Capability.Online.Leaderboard.csproj b/Capability/GameFrameX.Capability.Online.Leaderboard/GameFrameX.Capability.Online.Leaderboard.csproj new file mode 100644 index 000000000..bd2e3e857 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/GameFrameX.Capability.Online.Leaderboard.csproj @@ -0,0 +1,19 @@ + + + + + GameFrameX.Capability.Online.Leaderboard,GFX Online 排行榜能力包:榜单生命周期/分数提交与累加策略/周边与置顶查询/对局结算投影(Match.Settled 订阅+幂等+失败重投)+ admin handlers(query_leaderboard). Leaderboard capability package for the GFX Online family: board lifecycle, score submission with sum/best policies, around and top queries, the match-settled projection with idempotency and retry, and admin handlers. Documentation: https://gameframex.doc.alianblank.com + GameFrameX,Capability,Online,Leaderboard,Projection,GameServer + + + + + + + + + + + + + diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/IOnlineLeaderboardStore.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/IOnlineLeaderboardStore.cs index b3419f779..aca5e7d49 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/IOnlineLeaderboardStore.cs +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/IOnlineLeaderboardStore.cs @@ -37,7 +37,7 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// 排行榜存储契约(榜单定义 + 条目;InMemory 为单进程默认实现,生产持久化归 Server 仓运行时装配)。 /// /// 维护约束(红线): -/// (1) 作用域隔离——所有查询以 (TenantId, AppId) 为前置条件,跨作用域访问与不存在同构(null,反预言); +/// (1) 榜单为全局域投影目标——字典键即 LeaderboardId(无区服隔离位,同键即同榜); /// (2) 是唯一条目写入入口,**累计策略裁决与条目落档必须在同一临界区**, /// 并发投递不得交错撕裂(形态对齐票据 / 通知存储的临界区约定); /// (3) 出入参一律防御性拷贝——返回对象与内部状态无别名,调用方改写不影响存储。 @@ -46,33 +46,29 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; public interface IOnlineLeaderboardStore { /// - /// 创建榜单(同作用域同名榜单已存在时拒绝,返回 null,不覆盖)。 + /// 创建榜单(同名榜单已存在时拒绝,返回 null,不覆盖)。 /// - /// 榜单定义(作用域取其 TenantId / AppId)。 + /// 榜单定义。 /// 取消令牌。 /// 创建后的榜单副本;已存在返回 null。 Task CreateAsync(OnlineLeaderboard leaderboard, CancellationToken cancellationToken = default); /// - /// 按作用域查找榜单定义。 + /// 按榜单标识查找榜单定义。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识。 /// 取消令牌。 - /// 榜单副本;不存在或跨作用域返回 null。 - Task FindAsync(long tenantId, long appId, string leaderboardId, CancellationToken cancellationToken = default); + /// 榜单副本;不存在返回 null。 + Task FindAsync(string leaderboardId, CancellationToken cancellationToken = default); /// /// 查找单玩家条目。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识。 /// 玩家标识。 /// 取消令牌。 /// 条目副本;未上榜或榜单不存在返回 null。 - Task FindEntryAsync(long tenantId, long appId, string leaderboardId, long playerId, CancellationToken cancellationToken = default); + Task FindEntryAsync(string leaderboardId, long playerId, CancellationToken cancellationToken = default); /// /// 应用一笔分数提交(原子:累计策略裁决 + 条目落档在同一临界区)。 diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/InMemoryOnlineLeaderboardStore.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/InMemoryOnlineLeaderboardStore.cs index e7a17cd3c..787dd0166 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/InMemoryOnlineLeaderboardStore.cs +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/InMemoryOnlineLeaderboardStore.cs @@ -29,7 +29,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Threading; using System.Threading.Tasks; using GameFrameX.Foundation.Localization.Core; @@ -49,7 +48,7 @@ public sealed class InMemoryOnlineLeaderboardStore : IOnlineLeaderboardStore /// 全局读写锁(榜单与条目共用,保证快照一致性)。 private readonly object _syncRoot = new(); - /// 榜单定义表:键 = (TenantId, AppId, LeaderboardId)。 + /// 榜单定义表:键 = LeaderboardId(全局域投影,无区服隔离位)。 private readonly Dictionary _boards = new(); /// 条目表:键 = 榜单键 → (PlayerId → 条目)。 @@ -63,12 +62,12 @@ public InMemoryOnlineLeaderboardStore() } /// - /// 在全局锁内创建榜单:同作用域同标识已存在时拒绝返回 null,否则落档定义副本并初始化空条目表。 + /// 在全局锁内创建榜单:同标识已存在时拒绝返回 null,否则落档定义副本并初始化空条目表。 /// /// - /// Creates the leaderboard under the global lock: refuses with null when the same id already exists in the scope, otherwise stores a defensive copy of the definition and initializes an empty entry table. + /// Creates the leaderboard under the global lock: refuses with null when the same id already exists, otherwise stores a defensive copy of the definition and initializes an empty entry table. /// - /// 榜单定义(作用域取自其 TenantId 与 AppId)/ The leaderboard definition (scope taken from its TenantId and AppId) + /// 榜单定义 / The leaderboard definition /// 取消令牌 / Cancellation token /// 创建后的榜单副本;已存在返回 null / A copy of the created leaderboard; null when it already exists /// 当 为 null 时抛出 / Thrown when is null @@ -81,7 +80,7 @@ public Task CreateAsync(OnlineLeaderboard leaderboard, Cancel lock (_syncRoot) { - var key = BuildKey(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId); + var key = BuildKey(leaderboard.LeaderboardId); if (_boards.ContainsKey(key)) { return Task.FromResult(null); @@ -94,21 +93,19 @@ public Task CreateAsync(OnlineLeaderboard leaderboard, Cancel } /// - /// 在全局锁内按作用域与榜单标识查找榜单定义,返回防御性副本。 + /// 在全局锁内按榜单标识查找榜单定义,返回防御性副本。 /// /// - /// Finds the leaderboard definition by scope and leaderboard id under the global lock, returning a defensive copy. + /// Finds the leaderboard definition by leaderboard id under the global lock, returning a defensive copy. /// - /// 租户标识 / The tenant id - /// App 标识 / The app id /// 榜单标识 / The leaderboard id /// 取消令牌 / Cancellation token - /// 榜单副本;不存在或跨作用域返回 null / A copy of the leaderboard; null when not found or cross-scope - public Task FindAsync(long tenantId, long appId, string leaderboardId, CancellationToken cancellationToken = default) + /// 榜单副本;不存在返回 null / A copy of the leaderboard; null when not found + public Task FindAsync(string leaderboardId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - return Task.FromResult(TryFindBoard(tenantId, appId, leaderboardId, out var board) ? board.Copy() : null); + return Task.FromResult(TryFindBoard(leaderboardId, out var board) ? board.Copy() : null); } } @@ -118,17 +115,15 @@ public Task FindAsync(long tenantId, long appId, string leade /// /// Finds a single player's entry on the board under the global lock, returning a defensive copy. /// - /// 租户标识 / The tenant id - /// App 标识 / The app id /// 榜单标识 / The leaderboard id /// 玩家标识 / The player id /// 取消令牌 / Cancellation token /// 条目副本;未上榜或榜单不存在返回 null / A copy of the entry; null when the player is unranked or the board does not exist - public Task FindEntryAsync(long tenantId, long appId, string leaderboardId, long playerId, CancellationToken cancellationToken = default) + public Task FindEntryAsync(string leaderboardId, long playerId, CancellationToken cancellationToken = default) { lock (_syncRoot) { - if (!TryFindBoard(tenantId, appId, leaderboardId, out _) || !_entries.TryGetValue(BuildKey(tenantId, appId, leaderboardId), out var boardEntries) || !boardEntries.TryGetValue(playerId, out var entry)) + if (!TryFindBoard(leaderboardId, out _) || !_entries.TryGetValue(BuildKey(leaderboardId), out var boardEntries) || !boardEntries.TryGetValue(playerId, out var entry)) { return Task.FromResult(null); } @@ -167,7 +162,7 @@ public Task ApplySubmissionAsync(OnlineLeaderboard lock (_syncRoot) { - var key = BuildKey(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId); + var key = BuildKey(leaderboard.LeaderboardId); if (!_boards.ContainsKey(key) || !_entries.TryGetValue(key, out var boardEntries)) { // Localization: Online.Leaderboard.NotFoundOnWrite - 榜单不存在或已失效,写入前必须先经 FindAsync 解析 @@ -229,7 +224,7 @@ public Task> ListOrderedEntriesAsync(OnlineLeaderbo List copies; lock (_syncRoot) { - var key = BuildKey(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId); + var key = BuildKey(leaderboard.LeaderboardId); if (!_entries.TryGetValue(key, out var boardEntries)) { // Localization: Online.Leaderboard.NotFoundOnQuery - 榜单不存在或已失效,查询前必须先经 FindAsync 解析 @@ -273,7 +268,7 @@ public Task TryResetAsync(OnlineLeaderboard leaderboard, IReadOnlyList /// 在锁内解析榜单定义(调用方已持锁)。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识。 /// 解析到的榜单定义。 /// 存在返回 true。 - private bool TryFindBoard(long tenantId, long appId, string leaderboardId, out OnlineLeaderboard board) + private bool TryFindBoard(string leaderboardId, out OnlineLeaderboard board) { board = null; if (string.IsNullOrEmpty(leaderboardId)) @@ -348,7 +341,7 @@ private bool TryFindBoard(long tenantId, long appId, string leaderboardId, out O return false; } - if (!_boards.TryGetValue(BuildKey(tenantId, appId, leaderboardId), out var stored)) + if (!_boards.TryGetValue(BuildKey(leaderboardId), out var stored)) { return false; } @@ -397,14 +390,12 @@ private static bool TryResolveScore(OnlineLeaderboard leaderboard, OnlineLeaderb } /// - /// 构造存储键(作用域 + 榜单标识;跨作用域访问因键不同而自然隔离)。 + /// 构造存储键(榜单标识即键——全局域投影目标,同键即同榜)。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识。 /// 存储键。 - private static string BuildKey(long tenantId, long appId, string leaderboardId) + private static string BuildKey(string leaderboardId) { - return tenantId.ToString(CultureInfo.InvariantCulture) + ":" + appId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboardId; + return leaderboardId ?? string.Empty; } } \ No newline at end of file diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineCompetitionOptions.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineCompetitionOptions.cs index f548b97a9..e015d44fd 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineCompetitionOptions.cs +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/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.Leaderboard/OnlineLeaderboard.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboard.cs index 62bffdfba..93fe0723e 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboard.cs +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboard.cs @@ -30,10 +30,9 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// -/// 排行榜榜单定义(第一版个人榜;作用域 = (TenantId, AppId),App 内跨区服聚合)。 +/// 排行榜榜单定义(第一版个人榜;全局域投影目标,无区服隔离位——同 LeaderboardId 即同榜)。 /// -/// 维护约束(红线):榜单归属租户与 App 双键隔离——跨 App / 跨租户读写一律查不到(ResourceNotFound 反预言, -/// 对齐存储与频道的既有先例,不泄露榜单存在性);ServerId 不参与榜单隔离, +/// 维护约束(红线):榜单为全局域数据——同键读写天然成立,无跨区服隔离维度; /// 队伍榜 / 公会榜 / 复杂跨服排名延后(超出首版范围)。排序方向与累计策略创建后固化,运行期不可变更; /// 赛季维度的生命周期(重置 / 快照)归赛季域,本类型不承载赛季字段。 /// @@ -41,20 +40,10 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; public sealed class OnlineLeaderboard { /// - /// 获取或设置榜单标识(App 内唯一,创建方提供)。 + /// 获取或设置榜单标识(全局唯一,创建方提供)。 /// public string LeaderboardId { get; set; } - /// - /// 获取或设置租户标识(作用域隔离键)。 - /// - public long TenantId { get; set; } - - /// - /// 获取或设置 App 标识(作用域隔离键)。 - /// - public long AppId { get; set; } - /// /// 获取或设置排序方向(创建后固化)。 /// @@ -84,8 +73,6 @@ public OnlineLeaderboard Copy() return new OnlineLeaderboard { LeaderboardId = LeaderboardId, - TenantId = TenantId, - AppId = AppId, SortOrder = SortOrder, ScoreUpdatePolicy = ScoreUpdatePolicy, MaxScorePerSubmission = MaxScorePerSubmission, diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCapabilityModule.cs new file mode 100644 index 000000000..08de76567 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCapabilityModule.cs @@ -0,0 +1,215 @@ +// ========================================================================================== +// 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 related 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 see 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 legitimate 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 System; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Hosting.Abstractions; +using GameFrameX.Capability.Hosting.AdminApi; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Events; +using GameFrameX.Capability.Online.Abstractions.Idempotency; +using GameFrameX.Capability.Online.Abstractions.Scope; +using GameFrameX.Capability.Online.Competition; +using GameFrameX.Capability.Online.Competition.AdminApi; +using GameFrameX.Capability.Online.Competition.Leaderboard; +using GameFrameX.Capability.Online.Match; +using GameFrameX.Localization; + +namespace GameFrameX.Capability.Online.Leaderboard; + +/// +/// 排行榜能力(榜单生命周期 / 分数提交 / 查询 / 对局结算投影)的自装配模块(自竞技能力包拆出独立承载: +/// 按需引入 + Options 回调定制榜单参数)。 +/// +/// 维护约束(服务共享协议):模块无参构造(扫描可发现);Register 自装配本域——榜单 store 以懒默认 +/// 描述符注册(族 / 宿主覆盖恒胜出,模块不感知); 为唯一参数面 +/// (含榜单组件参数与 Match.Settled 投影配置):投影榜 id 非空白且对局结果存储(online-match 可选产物) +/// 在场时装配 Match.Settled 排行榜投影(机制总线订阅 + 失败重投 tick); +/// ActivateAsync 在投影榜 id 非空白时经榜单服务预建目标榜(查询-创建,见方法注释)。 +/// +/// +public sealed class OnlineLeaderboardCapabilityModule : ICapabilityModule, IAdminActionContributor +{ + /// + /// 排行榜能力清单(Id 冻结 = 终态包名;query_leaderboard 自竞技能力清单迁入;可选依赖 online-match + /// 经 声明,缺席时披露对应缺失功能名)。 + /// + public static readonly CapabilityManifest ManifestInstance = new( + "online-leaderboard", + "1.0.0", + new[] { "query_leaderboard" }, + null, + new[] + { + new CapabilityOptionalDependency("online-match", Keys.Capability.OnlineModule.Leaderboard.OptionalMatchAbsent), + }, + typeof(OnlineCompetitionOptions)); + + /// + /// 排行榜服务(Register 期构造;admin 面 handler、投影链与激活期榜单预建取用)。 + /// + private OnlineLeaderboardService _leaderboards; + + /// + /// Match.Settled 排行榜投影器(Register 期装配;投影配置空白或 online-match 缺席时为 null)。 + /// + private OnlineMatchSettledLeaderboardProjector _projectionProjector; + + /// + /// Match.Settled 投影目标榜单标识(Register 期从 Options 读出;空白 = 不投影不预建;ActivateAsync 预建判据)。 + /// + private string _projectionBoardId; + + /// + /// 获取排行榜能力清单,固定返回静态实例 。 + /// + /// + /// Gets the leaderboard capability manifest; always returns the static . + /// + /// 排行榜能力清单 / Leaderboard capability manifest + public CapabilityManifest Manifest + { + get { return ManifestInstance; } + } + + /// + /// 读取排行榜能力选项,懒默认注册内存版榜单存储并解析生效实例,构造并注册排行榜服务; + /// 投影榜单标识非空白且对局结果存储在场时,注册 Match.Settled 排行榜投影器、订阅对局结算事件并添加投影重试的 tick 任务。 + /// + /// + /// Reads , registers the in-memory leaderboard store as a lazy default and + /// resolves the effective instance, then builds and registers the leaderboard service. When the projection board id + /// is not blank and the match result store is present, it registers the Match.Settled leaderboard projector, + /// subscribes it to the match-settled event and adds the leaderboard-projection-retry tick job; + /// otherwise the projection is silently skipped. + /// + /// 能力注册上下文 / Capability registration context + public void Register(CapabilityRegistrationContext context) + { + var options = context.GetOptions(); + var eventPublisher = context.GetService(); + + // 榜单 store 懒默认描述符(族 / 宿主覆盖恒胜出;GetService 命中覆盖或本默认)。 + context.AddService(static _ => new InMemoryOnlineLeaderboardStore()); + var leaderboardStore = context.GetService(); + + var leaderboards = new OnlineLeaderboardService(leaderboardStore, options.Leaderboard, eventPublisher); + _leaderboards = leaderboards; + context.AddService(leaderboards); + + // Match.Settled → 排行榜投影:Options 投影榜 id 非空白(空白 = 不投影)且对局结果存储在场 + // (online-match 被过滤 → 不装配不报错)才装配;订阅走机制事件总线(Register 期声明, + // 单个订阅体异常由机制记日志后继续分发,业务侧不再自行吞异常),失败经 tick job 重投。 + _projectionBoardId = options.LeaderboardProjection.MatchSettledBoardId; + var projectionResultStore = context.GetOptionalService(); + if (!string.IsNullOrWhiteSpace(_projectionBoardId) && projectionResultStore != null) + { + var projectionIdempotency = context.GetService(); + var projector = new OnlineMatchSettledLeaderboardProjector(projectionResultStore, leaderboards, projectionIdempotency, _projectionBoardId); + _projectionProjector = projector; + context.AddService(projector); + context.Subscribe(OnlineMatchRuntimeEvents.MatchSettled, onlineEvent => _projectionProjector.HandleEventAsync(onlineEvent).GetAwaiter().GetResult()); + context.AddTickJob("leaderboard-projection-retry", cancellationToken => _projectionProjector.RetryPendingAsync(cancellationToken)); + } + } + + /// + /// 投影榜单标识为空白时直接返回;否则以 Top 1 查询探测目标榜单,已存在则返回,返回资源不存在时按累加计分、降序排序创建该榜单。 + /// + /// + /// Returns immediately when the projection board id is blank. Otherwise probes the target board with a top-1 query; + /// if it already exists nothing else happens, and if the probe reports resource-not-found the board is created with + /// the sum score-update policy and descending sort order. Any other failure aborts activation so the host can roll back. + /// + /// 能力激活上下文,用于解析 Online 作用域 / Capability activation context used to resolve the Online scope + /// 取消令牌 / Cancellation token + /// 表示异步激活操作的任务 / Task representing the asynchronous activation + /// 探测返回资源不存在以外的失败码,或创建榜单失败 / The probe fails with a code other than resource-not-found, or creating the board fails + public async Task ActivateAsync(CapabilityActivationContext context, CancellationToken cancellationToken) + { + if (string.IsNullOrWhiteSpace(_projectionBoardId)) + { + return; + } + + // 榜单预建(迁自竞技能力模块):投影目标榜查询-创建——GetTop 探针命中即已存在; + // ResourceNotFound 视作首建,按 Sum / Descending 创建;其余失败码或创建失败 = 激活失败 + // (抛 InvalidOperationException 由机制逆序回滚)。 + var scope = context.Services.GetService(); + var probe = await _leaderboards.GetTopAsync(scope, new OnlineLeaderboardTopQuery { LeaderboardId = _projectionBoardId, Count = 1, }, cancellationToken).ConfigureAwait(false); + if (probe.IsSuccess) + { + return; + } + + if (probe.Code != OnlineErrorCode.ResourceNotFound) + { + throw new InvalidOperationException("Leaderboard pre-build probe failed for board '" + _projectionBoardId + "' (code: " + probe.Code + ")."); + } + + var created = await _leaderboards.CreateAsync(scope, new OnlineLeaderboardCreateRequest + { + LeaderboardId = _projectionBoardId, + SortOrder = OnlineLeaderboardSortOrder.Descending, + ScoreUpdatePolicy = OnlineLeaderboardScoreUpdatePolicy.Sum, + }, 0, cancellationToken).ConfigureAwait(false); + if (!created.IsSuccess) + { + throw new InvalidOperationException("Leaderboard pre-build create failed for board '" + _projectionBoardId + "' (code: " + created.Code + ")."); + } + } + + /// + /// 停用阶段无需处理:事件订阅与 tick 任务由宿主机制在注册时托管,激活仅预建榜单而不持有运行资源,直接返回已完成任务。 + /// + /// + /// Nothing to do on deactivation: the event subscription and tick job are declared to the host during registration, + /// and activation only pre-creates the board without holding runtime resources, so a completed task is returned. + /// + /// 取消令牌 / Cancellation token + /// 已完成的任务 / Completed task + public Task DeactivateAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + /// + /// 基于注册阶段构造的排行榜服务登记排行榜查询管理动作。 + /// + /// + /// Registers the leaderboard query admin actions backed by the leaderboard service built during registration. + /// + /// 管理动作注册表 / Admin action registry + public void RegisterAdminActions(AdminActionRegistry registry) + { + OnlineAdminLeaderboardHandlers.RegisterLeaderboardQuery(registry, _leaderboards); + } +} diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCreateRequest.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCreateRequest.cs index 8934ef8ae..69b643a0c 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCreateRequest.cs +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardCreateRequest.cs @@ -32,14 +32,14 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// /// 排行榜创建请求(服务端运营 / 运行时装配入口;客户端无此入口)。 /// -/// 维护约束:作用域取鉴权上下文的 ,请求体不携带 TenantId / AppId(服务端不信任请求体作用域); -/// 同名榜单在 (TenantId, AppId) 内已存在时创建被拒绝(ParameterInvalid),不覆盖既有榜单。 +/// 维护约束:作用域取鉴权上下文的 ,请求体不携带作用域键位(服务端不信任请求体作用域); +/// 同名榜单已存在时创建被拒绝(ParameterInvalid),不覆盖既有榜单。 /// /// public sealed class OnlineLeaderboardCreateRequest { /// - /// 获取或设置榜单标识(App 内唯一,非空)。 + /// 获取或设置榜单标识(全局唯一,非空)。 /// public string LeaderboardId { get; set; } diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEvents.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEvents.cs index 797125442..286b8b092 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEvents.cs +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardEvents.cs @@ -57,14 +57,12 @@ public static class OnlineLeaderboardEvents /// /// 构造榜单创建事件。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识(可空;载荷落空字符串)。 /// 排序方向名。 /// 累计策略名。 /// 创建时刻(UTC 毫秒)。 /// 事件信封实例。 - public static OnlineEvent CreateLeaderboardCreated(long tenantId, long appId, string leaderboardId, string sortOrder, string scoreUpdatePolicy, long createdTime) + public static OnlineEvent CreateLeaderboardCreated(string leaderboardId, string sortOrder, string scoreUpdatePolicy, long createdTime) { var payload = new LeaderboardCreatedPayload { @@ -86,8 +84,6 @@ public static OnlineEvent CreateLeaderboardCreated(long tenantId, long appId, st EventType = LeaderboardCreated, OccurredTime = createdTime > 0 ? createdTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = 0, Source = Source, @@ -100,8 +96,6 @@ public static OnlineEvent CreateLeaderboardCreated(long tenantId, long appId, st /// /// 构造榜上分数更新事件。 /// - /// 租户标识。 - /// App 标识。 /// 榜单标识(可空;载荷落空字符串)。 /// 玩家标识。 /// 变更前分数。 @@ -109,7 +103,7 @@ public static OnlineEvent CreateLeaderboardCreated(long tenantId, long appId, st /// 来源结算结果标识(追溯键,兼作 CorrelationId)。 /// 变更时刻(UTC 毫秒)。 /// 事件信封实例。 - public static OnlineEvent CreateScoreUpdated(long tenantId, long appId, string leaderboardId, long playerId, long oldScore, long newScore, string sourceMatchResultId, long updatedTime) + public static OnlineEvent CreateScoreUpdated(string leaderboardId, long playerId, long oldScore, long newScore, string sourceMatchResultId, long updatedTime) { var payload = new ScoreUpdatedPayload { @@ -137,8 +131,6 @@ public static OnlineEvent CreateScoreUpdated(long tenantId, long appId, string l EventType = ScoreUpdated, OccurredTime = updatedTime > 0 ? updatedTime : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), SchemaVersion = 1, - TenantId = tenantId, - AppId = appId, ServerId = 0, PlayerId = playerId, Source = Source, diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionOptions.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionOptions.cs index 241945c3f..3084bc100 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardProjectionOptions.cs +++ b/Capability/GameFrameX.Capability.Online.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.Leaderboard/OnlineLeaderboardRateLimiter.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardRateLimiter.cs index eaecf9a1b..49301c31c 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardRateLimiter.cs +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardRateLimiter.cs @@ -35,7 +35,7 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// /// 排行榜提交限流器(防刷校验的高频半边:高频提交被拒、正常玩家不受影响)。 /// -/// 维护约束(天花板):滑动窗口计数,按 (TenantId, AppId, PlayerId) 分桶——阈值与窗口由 +/// 维护约束(天花板):滑动窗口计数,按 PlayerId 分桶——阈值与窗口由 /// 覆盖;只在幂等 Execute 分支计数(重放不烧配额)。 /// 形态对齐 OnlineMatchRateLimiter / OnlineChatRateLimiter(滑动窗口,不新增依赖); /// 桶在窗口过期后整桶重置,进程重启即清零——限流是速率保护不是配额,可接受;多实例共享存储归运行时装配。 @@ -46,7 +46,7 @@ public sealed class OnlineLeaderboardRateLimiter /// 全局读写锁。 private readonly object _syncRoot = new(); - /// 窗口计数桶:键 = (TenantId, AppId, PlayerId)。 + /// 窗口计数桶:键 = PlayerId。 private readonly Dictionary _windows = new(); /// 上一次全量清扫时刻(UTC 毫秒)。 @@ -80,15 +80,13 @@ public OnlineLeaderboardRateLimiter(int maxSubmissions, int windowSeconds) /// /// Tries to acquire one submission slot for the player within the sliding window. /// - /// 租户 ID / The tenant id - /// 应用 ID / The app id /// 玩家 ID / The player id /// 当前 Unix 毫秒时间戳(0 表示取当前时间)/ The current Unix time in milliseconds (0 for now) /// 窗口未满获取成功返回 true;已满返回 false / true if acquired within the window; false when the window is full - public bool TryAcquire(long tenantId, long appId, long playerId, long nowUnixMilliseconds = 0) + public bool TryAcquire(long playerId, long nowUnixMilliseconds = 0) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var key = tenantId + ":" + appId + ":" + playerId; + var key = playerId.ToString(System.Globalization.CultureInfo.InvariantCulture); lock (_syncRoot) { diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardResultProjector.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardResultProjector.cs index 52dda6631..120dfb553 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardResultProjector.cs +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardResultProjector.cs @@ -44,7 +44,7 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// /// 维护约束(红线): /// (1) **载荷零信任**——结算结果只从 (结算唯一落定点)按 -/// (TenantId, AppId, MatchId) 读取,且核对调用方传入的 MatchResultId 与存储值一致;本类型不接受 +/// MatchId 读取,且核对调用方传入的 MatchResultId 与存储值一致;本类型不接受 /// 任何调用方直接携带分数 / 结果载荷的入口(伪造标识 → ResourceNotFound,篡改载荷 → RiskControlRejected); /// (2) **写入幂等**——复用 ,键确定性派生 /// lb-{MatchResultId}-{LeaderboardId}-{PlayerId}(沿用「业务单号由结果标识派生」的既有约定), @@ -79,7 +79,7 @@ public OnlineLeaderboardResultProjector(IOnlineMatchResultStore matchResultStore /// /// 将一局已结算结果投影到目标榜单(幂等;逐玩家失败隔离)。 /// - /// 生效作用域(榜单与结果的 TenantId / AppId 以此为准)。 + /// 生效作用域。 /// 目标榜单标识。 /// 对局标识(据此从结算存储读取结果)。 /// 调用方持有的结果标识(与存储值核对,防伪造载荷)。 @@ -115,7 +115,7 @@ public async Task> ProjectAsync } var board = boardResult.Data; - var stored = await _matchResultStore.FindByMatchAsync(scope.TenantId, scope.AppId, matchId, cancellationToken).ConfigureAwait(false); + var stored = await _matchResultStore.FindByMatchAsync(matchId, cancellationToken).ConfigureAwait(false); if (stored == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "对局结果不存在或未结算"); @@ -163,7 +163,7 @@ public async Task> ProjectAsync /// 完成通知。 private async Task ProjectEntryAsync(OnlineLeaderboard board, OnlineMatchResult result, OnlineMatchResultEntry entry, long now, OnlineLeaderboardProjectionOutcome outcome, CancellationToken cancellationToken) { - var playerScope = new OnlineScope(result.TenantId, result.AppId, result.ServerId, entry.PlayerId); + var playerScope = new OnlineScope(result.ServerId, entry.PlayerId); var idempotencyKey = BuildIdempotencyKey(result.MatchResultId, board.LeaderboardId, entry.PlayerId); var decision = await _idempotencyService.BeginAsync(playerScope, idempotencyKey, BuildCanonicalRequestText(result.MatchResultId, board.LeaderboardId, entry.PlayerId, entry.Score), true, cancellationToken).ConfigureAwait(false); diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardService.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardService.cs index 87fd6d486..1d3bd44b8 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardService.cs +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineLeaderboardService.cs @@ -45,7 +45,7 @@ namespace GameFrameX.Capability.Online.Competition.Leaderboard; /// (1) **本服务没有任何接受「裸分数」的公开提交 API**——分数写入只经内部 /// (由可信写入链路 调用), /// 客户端无入口可刷分; -/// (2) 跨 App / 跨租户读写与「榜单不存在」同构返回 ResourceNotFound(反预言,不泄露榜单存在性); +/// (2) 作用域校验失败与「榜单不存在」同构返回 ResourceNotFound(反预言,不泄露榜单存在性); /// (3) Top N 读缓存 TTL + 写失效——任何成功写榜立即失效该榜缓存,缓存只影响读延迟不影响正确性。 /// /// @@ -84,9 +84,9 @@ public OnlineLeaderboardService(IOnlineLeaderboardStore store, OnlineLeaderboard } /// - /// 创建榜单(同作用域同名榜单已存在时拒绝;创建成功发布 Online.Leaderboard.Created 事件)。 + /// 创建榜单(同名榜单已存在时拒绝;创建成功发布 Online.Leaderboard.Created 事件)。 /// - /// 生效作用域(鉴权上下文产物;榜单归属取其 TenantId / AppId)。 + /// 生效作用域(鉴权上下文产物)。 /// 创建请求。 /// 当前时刻(UTC 毫秒;传 0 取系统时钟,测试可注入)。 /// 取消令牌。 @@ -126,8 +126,6 @@ public async Task> CreateAsync(OnlineScope scope var board = new OnlineLeaderboard { LeaderboardId = request.LeaderboardId, - TenantId = scope.TenantId, - AppId = scope.AppId, SortOrder = request.SortOrder, ScoreUpdatePolicy = request.ScoreUpdatePolicy, MaxScorePerSubmission = request.MaxScorePerSubmission, @@ -140,14 +138,14 @@ public async Task> CreateAsync(OnlineScope scope return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识已存在"); } - await PublishAsync(OnlineLeaderboardEvents.CreateLeaderboardCreated(created.TenantId, created.AppId, created.LeaderboardId, created.SortOrder.ToString(), created.ScoreUpdatePolicy.ToString(), created.CreatedTime), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineLeaderboardEvents.CreateLeaderboardCreated(created.LeaderboardId, created.SortOrder.ToString(), created.ScoreUpdatePolicy.ToString(), created.CreatedTime), cancellationToken).ConfigureAwait(false); return OnlineResult.Ok(created); } /// /// 查询 Top N(带 keyset 游标分页;游标由本服务编码,客户端不透明)。 /// - /// 生效作用域(跨 App / 跨租户与不存在同构拒绝)。 + /// 生效作用域。 /// Top N 查询载荷。 /// 取消令牌。 /// 本页条目与后继游标;失败返回对应错误码。 @@ -302,7 +300,7 @@ public async Task> GetAroundPlayerAsyn } /// - /// 内部:按作用域解析榜单定义(跨作用域与不存在同构返回失败 ResourceNotFound)。 + /// 内部:解析榜单定义(不存在同构返回失败 ResourceNotFound)。 /// /// 生效作用域。 /// 榜单标识。 @@ -320,7 +318,7 @@ internal async Task> ResolveBoardAsync(OnlineSco return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "榜单标识不能为空"); } - var board = await _store.FindAsync(scope.TenantId, scope.AppId, leaderboardId, cancellationToken).ConfigureAwait(false); + var board = await _store.FindAsync(leaderboardId, cancellationToken).ConfigureAwait(false); if (board == null) { return OnlineResult.Fail(OnlineErrorCode.ResourceNotFound, "排行榜不存在"); @@ -361,7 +359,7 @@ internal async Task ApplyTrustedScoreAsync(Online } var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - if (!_rateLimiter.TryAcquire(leaderboard.TenantId, leaderboard.AppId, submission.PlayerId, now)) + if (!_rateLimiter.TryAcquire(submission.PlayerId, now)) { return Failed(OnlineErrorCode.RateLimitExceeded, "提交过于频繁,已限流"); } @@ -374,7 +372,7 @@ internal async Task ApplyTrustedScoreAsync(Online } InvalidateCache(leaderboard); - await PublishAsync(OnlineLeaderboardEvents.CreateScoreUpdated(leaderboard.TenantId, leaderboard.AppId, leaderboard.LeaderboardId, submission.PlayerId, applied.OldScore, applied.Entry.Score, submission.SourceMatchResultId, applied.Entry.LastUpdateTime), cancellationToken).ConfigureAwait(false); + await PublishAsync(OnlineLeaderboardEvents.CreateScoreUpdated(leaderboard.LeaderboardId, submission.PlayerId, applied.OldScore, applied.Entry.Score, submission.SourceMatchResultId, applied.Entry.LastUpdateTime), cancellationToken).ConfigureAwait(false); return new OnlineLeaderboardWriteOutcome { @@ -450,7 +448,7 @@ private static OnlineLeaderboardWriteOutcome Failed(OnlineErrorCode code, string private async Task> GetSnapshotAsync(OnlineLeaderboard leaderboard, long nowUnixMilliseconds, CancellationToken cancellationToken) { var now = nowUnixMilliseconds > 0 ? nowUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); - var cacheKey = leaderboard.TenantId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.AppId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.LeaderboardId; + var cacheKey = leaderboard.LeaderboardId ?? string.Empty; if (_options.CacheEnabled) { lock (_cacheSyncRoot) @@ -484,7 +482,7 @@ private async Task> GetSnapshotAsync(OnlineLeaderbo /// 榜单定义。 private void InvalidateCache(OnlineLeaderboard leaderboard) { - var cacheKey = leaderboard.TenantId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.AppId.ToString(CultureInfo.InvariantCulture) + ":" + leaderboard.LeaderboardId; + var cacheKey = leaderboard.LeaderboardId ?? string.Empty; lock (_cacheSyncRoot) { _snapshotCache.Remove(cacheKey); diff --git a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineMatchSettledLeaderboardProjector.cs b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineMatchSettledLeaderboardProjector.cs index 86031ada5..723f6d7f5 100644 --- a/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineMatchSettledLeaderboardProjector.cs +++ b/Capability/GameFrameX.Capability.Online.Leaderboard/OnlineMatchSettledLeaderboardProjector.cs @@ -127,7 +127,7 @@ public async Task HandleEventAsync(OnlineEvent onlineEvent) try { // 榜单级作用域(PlayerId=0):投影器内部逐玩家以结算事实重建 scope。 - var scope = new OnlineScope(sourceEvent.TenantId, sourceEvent.AppId, sourceEvent.ServerId, 0); + var scope = new OnlineScope(sourceEvent.ServerId, 0); var projected = await _projector.ProjectAsync(scope, _leaderboardId, payload.MatchId, payload.MatchResultId).ConfigureAwait(false); if (!projected.IsSuccess) { @@ -163,7 +163,7 @@ public async Task RetryPendingAsync(CancellationToken cancellationToken) foreach (var entry in snapshot) { - var stored = await _matchResultStore.FindByMatchAsync(entry.TenantId, entry.AppId, entry.MatchId, cancellationToken).ConfigureAwait(false); + var stored = await _matchResultStore.FindByMatchAsync(entry.MatchId, cancellationToken).ConfigureAwait(false); if (stored == null) { // 结果已被清理:不可投影终态,移除。 @@ -171,7 +171,7 @@ public async Task RetryPendingAsync(CancellationToken cancellationToken) continue; } - var scope = new OnlineScope(entry.TenantId, entry.AppId, entry.ServerId, 0); + var scope = new OnlineScope(entry.ServerId, 0); var projected = await _projector.ProjectAsync(scope, _leaderboardId, entry.MatchId, entry.MatchResultId, 0, cancellationToken).ConfigureAwait(false); if (projected.IsSuccess) { @@ -232,7 +232,7 @@ private static MatchSettledPayload DeserializePayload(ReadOnlyMemory paylo /// /// 记录待重试条目(按 MatchResultId 去重;重复失败 Attempts 不衰减)。 /// - /// 来源事件(作用域三元组)。 + /// 来源事件(区服键)。 /// 已解析载荷。 private void RecordPending(OnlineEvent onlineEvent, MatchSettledPayload payload) { @@ -248,8 +248,6 @@ private void RecordPending(OnlineEvent onlineEvent, MatchSettledPayload payload) { MatchResultId = payload.MatchResultId, MatchId = payload.MatchId, - TenantId = onlineEvent.TenantId, - AppId = onlineEvent.AppId, ServerId = onlineEvent.ServerId, Attempts = 1, }; @@ -364,12 +362,6 @@ private sealed class PendingProjection /// 对局标识。 public string MatchId { get; set; } - /// 租户标识。 - public long TenantId { get; set; } - - /// App 标识。 - public long AppId { get; set; } - /// 区服标识。 public long ServerId { get; set; } diff --git a/Capability/GameFrameX.Capability.Online.Operations/GameFrameX.Capability.Online.Operations.csproj b/Capability/GameFrameX.Capability.Online.Operations/GameFrameX.Capability.Online.Operations.csproj index 574f4c246..c86409842 100644 --- a/Capability/GameFrameX.Capability.Online.Operations/GameFrameX.Capability.Online.Operations.csproj +++ b/Capability/GameFrameX.Capability.Online.Operations/GameFrameX.Capability.Online.Operations.csproj @@ -2,7 +2,7 @@ - GameFrameX.Capability.Online.Operations,GFX Online 运营聚合能力包:统一审计/游戏事件/Hotfix 回滚/在线总览/玩家时间线 + 事件桥与审计桥装配(机制事件总线逐主题订阅)+ 自装配模块(OnlineOperationsCapabilityModule,Options=OnlineOperationsOptions)+ admin handlers(Console 三 action). Operations aggregate capability package for the GFX Online family: unified audit, game events, hotfix rollback, overview and player timeline plus the event/audit bridge wiring over the mechanism event bus, the self-assembling capability module and admin handlers. Documentation: https://gameframex.doc.alianblank.com + GameFrameX.Capability.Online.Operations,GFX Online 运营聚合能力包(分析面冻结:游戏事件/总览/时间线不删除、不演进,数据面契约留服务端,查询 UI 归运营台;Hotfix 回滚为遗留活面):统一审计/Hotfix 回滚 + 事件桥与审计桥装配(机制事件总线逐主题订阅)+ 自装配模块(OnlineOperationsCapabilityModule,Options=OnlineOperationsOptions)+ admin handlers(Console 三 action). Operations aggregate capability package for the GFX Online family (frozen analysis face: game events, overview and timeline are neither removed nor evolved; hotfix rollback remains the active surface): unified audit, hotfix rollback and the event/audit bridge wiring over the mechanism event bus, the self-assembling capability module and admin handlers. Documentation: https://gameframex.doc.alianblank.com GameFrameX,Capability,Online,Operations,Audit,Timeline,Overview,HotfixRollback,GameEvents,GameServer + (机制面 Hosting.Abstractions / Hosting.Core 经 Online.Foundation 传递获得;管理面 UseAdminApi + 需显式引 Hosting.AdminApi——管理契约上移后 Online.Abstractions 不再传递 AdminApi)。 + 增减能力 = 只增删 ProjectReference,Program.cs 无按包装配代码。 --> + @@ -26,7 +28,12 @@ + + + + + diff --git a/Server.slnx b/Server.slnx index c90898761..e080d1a38 100644 --- a/Server.slnx +++ b/Server.slnx @@ -13,7 +13,7 @@ - + @@ -23,9 +23,17 @@ + + + + - + + + + + diff --git a/scripts/detached-liveops/README.md b/scripts/detached-liveops/README.md new file mode 100644 index 000000000..df6809e73 --- /dev/null +++ b/scripts/detached-liveops/README.md @@ -0,0 +1,18 @@ +# detached-liveops 存档 + +LiveOps 运营面(远程配置 / 设备组 / 定时任务 / 公告 / 玩家分群 / 配置灰度与回滚)已从能力包 +`GameFrameX.Capability.Online.Competition` 拆离:运营编排属平台运营特征,按包结构收敛裁决移交 +Admin 仓(运营台后端,clientDelivery 承接)。本目录为原文存档,不参与任何工程编译, +供 Admin 仓实现时按需搬迁。 + +原包内位置与形态: + +- `OnlineLiveOpsRegistry.cs` / `OnlineLiveOpsCommand.cs` / `OnlineLiveOpsEntry.cs` / `OnlineLiveOpsOperation.cs` + —— 原位于 `Capability/GameFrameX.Capability.Online.Competition/LiveOps/`(命名空间 + `GameFrameX.Capability.Online.Competition.LiveOps`),纯 POCO + 进程内注册表,零包外依赖。 +- `OnlineAdminLiveOpsHandlers.cs` —— 原位于同包 `AdminApi/`,admin 面 7 个 action 的处理器 + (publishRemoteConfig / syncDeviceGroup / syncScheduledTask / pushAnnouncement / syncPlayerSegment / + publishConfigRollout / rollbackConfigRollout),依赖 Hosting 管理契约与 Foundation.Json。 + +搬迁时注意:管理契约(`IAdminActionContributor` / `AdminActionRegistry` / `AdminApiRequest` 等)已上移 +`GameFrameX.Capability.Hosting.Abstractions` 包;Admin 仓经自身引用面消费。 From 0720dcec4b1eaa9d8a92cd7219bd4bd6adc252b0 Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 15:35:46 +0800 Subject: [PATCH 05/13] =?UTF-8?q?feat(analyzers):=20=E5=9B=BA=E5=8C=96?= =?UTF-8?q?=E5=8C=85=E5=88=86=E5=B1=82=E8=A7=84=E5=88=99=E5=B9=B6=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E7=BB=93=E6=9E=84=E6=B5=8B=E8=AF=95=E9=9D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 新增 GFX0023(层级单调 + 同层禁互引)、GFX0024(契约包零运行时 引用)、GFX0025(能力包四禁引 Apps/Hotfix/Proto/Core)三条 compilation-end 引用图规则,L0-L5 与层内序注册表固化全部工程引用 关系(同边可命中多条规则按规则维度去重),正反样例 18 例单测; 结构门禁测试同步新引用图(契约上移、Social/Match 拆引、Leaderboard 拆包、八能力拓扑序与 action 清单),组合测试 harness 注入夹具玩法 并固化零玩法形态回归。 Linear: GFX-1199 --- .../Architecture/CapabilityLayeringFacts.cs | 147 +++++++++++++ .../CapabilityPackageLayeringAnalyzer.cs | 159 ++++++++++++++ .../CapabilityLayeringAnalyzerTests.cs | 194 ++++++++++++++++++ .../GameFrameX.Tests/GameFrameX.Tests.csproj | 2 + .../Online/CapabilityPackageStructureTests.cs | 17 +- .../Online/OnlineAdminApiDispatcherTests.cs | 108 +++------- .../Online/OnlineCapabilityComposeTests.cs | 33 +-- .../Online/OnlineCapabilityTestHarness.cs | 4 + ...neMatchSettledLeaderboardProjectorTests.cs | 58 +++++- 9 files changed, 605 insertions(+), 117 deletions(-) create mode 100644 GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityLayeringFacts.cs create mode 100644 GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityPackageLayeringAnalyzer.cs create mode 100644 Tests/GameFrameX.Tests/Architecture/CapabilityLayeringAnalyzerTests.cs diff --git a/GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityLayeringFacts.cs b/GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityLayeringFacts.cs new file mode 100644 index 000000000..802ea00b9 --- /dev/null +++ b/GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityLayeringFacts.cs @@ -0,0 +1,147 @@ +// ========================================================================================== +// 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 related 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 see 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 legitimate 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 System.Collections.Generic; + +namespace GameFrameX.Architecture.Analyzers; + +/// +/// 框架仓分层事实表(GFX0023/24/25 的单一事实源):程序集名 → 层级序(整数 = 主层 ×10 + 层内序)。 +/// +/// 层级语义:L0 原语 / L1 运行时基座 / L2 Hosting 机制 / L3 Online 能力族 / L4 玩法层(Apps 数据 → Hotfix 逻辑 → 夹具)/ +/// L5 组合根与工具。只准高层引低层(严格小于);层内序承载既有设计内的同层上下游(如 Hotfix→Apps、 +/// AdminApi→Hosting.Core、能力族内 Foundation→Abstractions),新增或调整包边界须同步本表。 +/// 测试程序集与模板打包工程不参与分层断言。 +/// +/// +internal static class CapabilityLayeringFacts +{ + /// L0 原语层(零框架语义,可独立发布)。 + internal const int Layer0 = 0; + + /// 能力契约包判定后缀。 + private const string ContractSuffix = ".Abstractions"; + + /// + /// 程序集名 → 层级序(严格递增才合法;未登记的程序集不参与分层断言)。 + /// + private static readonly Dictionary Ranks = new() + { + // L0 原语(层内:本地化键 → 数学/工具 → 网络契约) + ["GameFrameX.Localization"] = Layer0, + ["GameFrameX.ProtoBuf.Net"] = Layer0, + ["GameFrameX.Utility"] = 1, + ["GameFrameX.Network.Abstractions"] = 2, + // L1 运行时基座(层内:存储/网络抽象 → 各实现 → Core → 产物配置) + ["GameFrameX.DataBase"] = 10, + ["GameFrameX.Network"] = 10, + ["GameFrameX.Discovery"] = 10, + ["GameFrameX.DataBase.Mongo"] = 11, + ["GameFrameX.DataBase.PostgreSql"] = 11, + ["GameFrameX.DataBase.Sqlite"] = 11, + ["GameFrameX.Network.HTTP"] = 11, + ["GameFrameX.Core"] = 12, + ["GameFrameX.Network.RemoteMessaging"] = 12, + ["GameFrameX.StartUp"] = 13, + ["GameFrameX.Config"] = 13, + ["GameFrameX.Proto"] = 13, + // L2 Hosting 机制(契约 → 机制 → 管理运行面) + ["GameFrameX.Capability.Hosting.Abstractions"] = 20, + ["GameFrameX.Capability.Hosting.Core"] = 21, + ["GameFrameX.Capability.Hosting.AdminApi"] = 22, + // L3 Online 能力族(脊柱 → 基座域 → 玩法域 → 适配/冻结面) + ["GameFrameX.Capability.Online.Abstractions"] = 30, + ["GameFrameX.Capability.Online.Foundation"] = 31, + ["GameFrameX.Capability.Online.Assets"] = 32, + ["GameFrameX.Capability.Online.Matchmaking"] = 33, + ["GameFrameX.Capability.Online.Social"] = 33, + ["GameFrameX.Capability.Online.Match"] = 34, + ["GameFrameX.Capability.Online.Leaderboard"] = 35, + ["GameFrameX.Capability.Online.Persistence"] = 35, + ["GameFrameX.Capability.Online.Competition"] = 36, + ["GameFrameX.Capability.Online.Operations"] = 36, + // L4 玩法层(Apps 数据 → Hotfix 逻辑 / 验收夹具) + ["GameFrameX.Apps"] = 40, + ["GameFrameX.Hotfix"] = 41, + ["GameFrameX.Apps.Sample"] = 41, + // L5 组合根与工具 + ["GameFrameX.Launcher"] = 50, + ["GameFrameX.Client"] = 50, + }; + + /// 能力实现包禁引清单(GFX0025):玩法层两工程、协议产物与胖核心——会话经 Foundation.Session 契约、协议经契约 DTO、玩法经桥契约。 + private static readonly HashSet CapabilityBannedReferences = new() + { + "GameFrameX.Apps", + "GameFrameX.Hotfix", + "GameFrameX.Proto", + "GameFrameX.Core", + }; + + /// 契约包可引用的 L0 原语集合(GFX0024 白名单;外部 NuGet 与其他契约包另判)。 + private static readonly HashSet ContractPrimitiveWhitelist = new() + { + "GameFrameX.Utility", + "GameFrameX.ProtoBuf.Net", + "GameFrameX.Network.Abstractions", + "GameFrameX.Localization", + }; + + /// 尝试取程序集层级序;未登记返回 false(不参与断言)。 + internal static bool TryGetRank(string name, out int rank) + { + return Ranks.TryGetValue(name, out rank); + } + + /// 契约包判定:GameFrameX.Capability.* 命名空间的 *.Abstractions 工程。 + internal static bool IsContractPackage(string name) + { + return name.StartsWith("GameFrameX.Capability.", System.StringComparison.Ordinal) + && name.EndsWith(ContractSuffix, System.StringComparison.Ordinal); + } + + /// 契约包引用白名单判定:其他契约包或 L0 原语。 + internal static bool IsAllowedContractReference(string name) + { + return IsContractPackage(name) || ContractPrimitiveWhitelist.Contains(name); + } + + /// 能力实现包禁引判定(GFX0025)。 + internal static bool IsBannedCapabilityReference(string name) + { + return CapabilityBannedReferences.Contains(name); + } + + /// 层级序格式化为可读层级(如 34 → L3.4)。 + internal static string FormatRank(int rank) + { + return "L" + (rank / 10).ToString() + "." + (rank % 10).ToString(); + } +} diff --git a/GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityPackageLayeringAnalyzer.cs b/GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityPackageLayeringAnalyzer.cs new file mode 100644 index 000000000..b4b3a8e3c --- /dev/null +++ b/GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityPackageLayeringAnalyzer.cs @@ -0,0 +1,159 @@ +// ========================================================================================== +// 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 related 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 see 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 legitimate 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 System.Collections.Generic; +using System.Collections.Immutable; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace GameFrameX.Architecture.Analyzers; + +/// +/// GFX0023/24/25:框架仓包分层规则(引用图断言,与 GFX0017/18 同族 compilation-end 检查)。 +/// +/// 三条规则:① 层级单调——只准高层引低层(严格小于),同层禁互引(GFX0023); +/// ② 契约包(*.Abstractions)零运行时引用——只准引用 L0 原语与其他契约包(GFX0024); +/// ③ 能力实现包四禁引——Apps / Hotfix / Proto / Core(GFX0025)。 +/// 数据来源为编译器引用图(含传递引用,无源码使用同样检查);未登记进 +/// 的程序集不参与断言。 +/// +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class CapabilityPackageLayeringAnalyzer : DiagnosticAnalyzer +{ + private static readonly DiagnosticDescriptor LayerMonotonicRule = new( + "GFX0023", + "包分层必须单调(同层禁互引)", + "程序集 '{0}'({1})引用了 '{2}'({3}):只准高层引低层(Ln→Lm, m<n)、同层禁互引;请把公共面下沉到更低层或调整包边界", + ArchitectureAnalyzerConstants.Category, + DiagnosticSeverity.Error, + true, + customTags: new[] { WellKnownDiagnosticTags.CompilationEnd }); + + private static readonly DiagnosticDescriptor ContractPurityRule = new( + "GFX0024", + "契约包不得引用运行时/实现工程", + "契约包 '{0}' 引用了 '{1}':契约包只准引用 L0 原语与其他契约包;管理面/机制运行时应反向依赖契约(契约上移,勿在契约内引实现)", + ArchitectureAnalyzerConstants.Category, + DiagnosticSeverity.Error, + true, + customTags: new[] { WellKnownDiagnosticTags.CompilationEnd }); + + private static readonly DiagnosticDescriptor CapabilityBanRule = new( + "GFX0025", + "能力包禁止引用 Apps/Hotfix/Proto/Core", + "能力包 '{0}' 引用了 '{1}':会话请经 Foundation.Session 契约、协议请经契约 DTO 隔离、玩法请经桥契约;能力包不得依赖玩法层、协议产物与胖核心", + ArchitectureAnalyzerConstants.Category, + DiagnosticSeverity.Error, + true, + customTags: new[] { WellKnownDiagnosticTags.CompilationEnd }); + + public override ImmutableArray SupportedDiagnostics + => ImmutableArray.Create(LayerMonotonicRule, ContractPurityRule, CapabilityBanRule); + + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.RegisterCompilationAction(AnalyzeReferences); + } + + private static void AnalyzeReferences(CompilationAnalysisContext context) + { + var compilation = context.Compilation; + var tree = compilation.SyntaxTrees.FirstOrDefault(); + var location = tree == null ? Location.None : tree.GetRoot(context.CancellationToken).GetFirstToken().GetLocation(); + + // 引用闭包 BFS(与 GFX0017 同口径:含传递引用,不依赖源码使用); + // 编译自身为登记包时(分析器接线进业务工程的形态)其直接出边一并检查。 + var queue = new Queue(); + var visited = new HashSet(System.StringComparer.Ordinal); + var reported = new HashSet<(int Rule, string From, string To)>(); + var consumerName = compilation.AssemblyName; + var consumerRegistered = CapabilityLayeringFacts.TryGetRank(consumerName, out _); + foreach (var assembly in compilation.SourceModule.ReferencedAssemblySymbols) + { + queue.Enqueue(assembly); + if (consumerRegistered) + { + CheckEdge(context, location, reported, consumerName, assembly.Identity.Name); + } + } + + while (queue.Count > 0) + { + context.CancellationToken.ThrowIfCancellationRequested(); + var assembly = queue.Dequeue(); + if (!visited.Add(assembly.Identity.Name)) + { + continue; + } + + foreach (var dependency in assembly.Modules.SelectMany(module => module.ReferencedAssemblySymbols)) + { + queue.Enqueue(dependency); + CheckEdge(context, location, reported, assembly.Identity.Name, dependency.Identity.Name); + } + } + } + + /// 单边检查:两端均在分层事实表登记时逐条执行三条规则(同一边可同时命中多条,各自去重报出)。 + private static void CheckEdge(CompilationAnalysisContext context, Location location, HashSet<(int Rule, string From, string To)> reported, string fromName, string toName) + { + if (!CapabilityLayeringFacts.TryGetRank(fromName, out var fromRank) + || !CapabilityLayeringFacts.TryGetRank(toName, out var toRank)) + { + return; + } + + // ① 层级单调 + 同层禁互引(严格小于才合法)。 + if (toRank >= fromRank && reported.Add((1, fromName, toName))) + { + context.ReportDiagnostic(Diagnostic.Create(LayerMonotonicRule, location, fromName, + CapabilityLayeringFacts.FormatRank(fromRank), toName, CapabilityLayeringFacts.FormatRank(toRank))); + } + + // ② 契约包零运行时引用(L0 原语与其他契约包之外一律拒绝)。 + if (CapabilityLayeringFacts.IsContractPackage(fromName) + && !CapabilityLayeringFacts.IsAllowedContractReference(toName) + && reported.Add((2, fromName, toName))) + { + context.ReportDiagnostic(Diagnostic.Create(ContractPurityRule, location, fromName, toName)); + } + + // ③ 能力实现包四禁引(Apps / Hotfix / Proto / Core)。 + if (CapabilityBoundaryFacts.IsImplementation(fromName) + && CapabilityLayeringFacts.IsBannedCapabilityReference(toName) + && reported.Add((3, fromName, toName))) + { + context.ReportDiagnostic(Diagnostic.Create(CapabilityBanRule, location, fromName, toName)); + } + } +} diff --git a/Tests/GameFrameX.Tests/Architecture/CapabilityLayeringAnalyzerTests.cs b/Tests/GameFrameX.Tests/Architecture/CapabilityLayeringAnalyzerTests.cs new file mode 100644 index 000000000..742d232e9 --- /dev/null +++ b/Tests/GameFrameX.Tests/Architecture/CapabilityLayeringAnalyzerTests.cs @@ -0,0 +1,194 @@ +// ========================================================================================== +// 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 related 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 see 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 legitimate 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 System.Collections.Immutable; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using GameFrameX.Architecture.Analyzers; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Diagnostics; +using Xunit; + +namespace GameFrameX.Tests.Architecture; + +/// +/// 分层规则分析器单测(GFX0023 层级单调 + 同层禁互引 / GFX0024 契约包零运行时引用 / GFX0025 能力包四禁引): +/// 全部经内存 Emit 的伪程序集构造引用图(不引入真实工程闭包),正反样例逐规则断言。 +/// +public sealed class CapabilityLayeringAnalyzerTests +{ + private static readonly ImmutableArray PlatformReferences = ((string)AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES")) + .Split(Path.PathSeparator) + .Where(path => !Path.GetFileName(path).StartsWith("GameFrameX.", System.StringComparison.Ordinal)) + .Select(path => (MetadataReference)MetadataReference.CreateFromFile(path)).ToImmutableArray(); + + [Fact] + public async Task SameLayerReference_IsRejected() + { + var matchmaking = Emit("GameFrameX.Capability.Online.Matchmaking", "public class Dependency { }"); + var social = Emit("GameFrameX.Capability.Online.Social", "public class Peer { public Dependency Value; }", matchmaking); + var diagnostic = Assert.Single(await Analyze(Compile("GameFrameX.Tests", "public class Consumer { }", social), new CapabilityPackageLayeringAnalyzer())); + Assert.Equal("GFX0023", diagnostic.Id); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); + Assert.Contains("GameFrameX.Capability.Online.Social", diagnostic.GetMessage()); + Assert.Contains("GameFrameX.Capability.Online.Matchmaking", diagnostic.GetMessage()); + Assert.Contains("L3.3", diagnostic.GetMessage()); + } + + [Fact] + public async Task UpwardReference_IsRejected() + { + var match = Emit("GameFrameX.Capability.Online.Match", "public class Dependency { }"); + var social = Emit("GameFrameX.Capability.Online.Social", "public class Peer { public Dependency Value; }", match); + var diagnostic = Assert.Single(await Analyze(Compile("GameFrameX.Tests", "public class Consumer { }", social), new CapabilityPackageLayeringAnalyzer())); + Assert.Equal("GFX0023", diagnostic.Id); + Assert.Contains("L3.4", diagnostic.GetMessage()); + Assert.Contains("L3.3", diagnostic.GetMessage()); + } + + [Theory] + [InlineData("GameFrameX.Capability.Online.Match", "GameFrameX.Capability.Online.Assets")] + [InlineData("GameFrameX.Capability.Online.Leaderboard", "GameFrameX.Capability.Online.Match")] + [InlineData("GameFrameX.Capability.Online.Competition", "GameFrameX.Capability.Online.Leaderboard")] + [InlineData("GameFrameX.Capability.Online.Persistence", "GameFrameX.DataBase")] + [InlineData("GameFrameX.Hotfix", "GameFrameX.Apps")] + [InlineData("GameFrameX.Capability.Hosting.AdminApi", "GameFrameX.Capability.Hosting.Core")] + public async Task DownwardReference_IsAllowed(string fromName, string toName) + { + var dependency = Emit(toName, "public class Dependency { }"); + var consumer = Emit(fromName, "public class Peer { public Dependency Value; }", dependency); + Assert.Empty(await Analyze(Compile("GameFrameX.Tests", "public class Consumer { }", consumer), new CapabilityPackageLayeringAnalyzer())); + } + + [Fact] + public async Task ContractPackageReferencingRuntime_IsRejected() + { + var adminApi = Emit("GameFrameX.Capability.Hosting.AdminApi", "public class Runtime { }"); + var contracts = Emit("GameFrameX.Capability.Online.Abstractions", "public class Contract { public Runtime Value; }", adminApi); + var diagnostic = Assert.Single(await Analyze(Compile("GameFrameX.Tests", "public class Consumer { }", contracts), new CapabilityPackageLayeringAnalyzer())); + Assert.Equal("GFX0024", diagnostic.Id); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); + Assert.Contains("GameFrameX.Capability.Online.Abstractions", diagnostic.GetMessage()); + Assert.Contains("GameFrameX.Capability.Hosting.AdminApi", diagnostic.GetMessage()); + } + + [Theory] + [InlineData("GameFrameX.Localization")] + [InlineData("GameFrameX.Utility")] + [InlineData("GameFrameX.Capability.Hosting.Abstractions")] + public async Task ContractPackageReferencingPrimitivesOrContracts_IsAllowed(string targetName) + { + var primitive = Emit(targetName, "public class Target { }"); + var contracts = Emit("GameFrameX.Capability.Online.Abstractions", "public class Contract { public Target Value; }", primitive); + Assert.Empty(await Analyze(Compile("GameFrameX.Tests", "public class Consumer { }", contracts), new CapabilityPackageLayeringAnalyzer())); + } + + [Theory] + [InlineData("GameFrameX.Proto")] + [InlineData("GameFrameX.Core")] + public async Task CapabilityPackageReferencingBannedAssembly_IsRejected(string bannedName) + { + var banned = Emit(bannedName, "public class Banned { }"); + var capability = Emit("GameFrameX.Capability.Online.Social", "public class Peer { public Banned Value; }", banned); + var diagnostic = Assert.Single(await Analyze(Compile("GameFrameX.Tests", "public class Consumer { }", capability), new CapabilityPackageLayeringAnalyzer())); + Assert.Equal("GFX0025", diagnostic.Id); + Assert.Equal(DiagnosticSeverity.Error, diagnostic.Severity); + Assert.Contains("GameFrameX.Capability.Online.Social", diagnostic.GetMessage()); + Assert.Contains(bannedName, diagnostic.GetMessage()); + } + + [Theory] + [InlineData("GameFrameX.Apps")] + [InlineData("GameFrameX.Hotfix")] + public async Task CapabilityPackageReferencingGameplayLayer_ReportsLayeringAndBanTogether(string bannedName) + { + // 玩法层在能力包之上:同一出边同时命中层级单调(GFX0023)与四禁引(GFX0025),两条互补报出。 + var banned = Emit(bannedName, "public class Banned { }"); + var capability = Emit("GameFrameX.Capability.Online.Social", "public class Peer { public Banned Value; }", banned); + var diagnostics = (await Analyze(Compile("GameFrameX.Tests", "public class Consumer { }", capability), new CapabilityPackageLayeringAnalyzer())).OrderBy(item => item.Id).ToArray(); + Assert.Equal(2, diagnostics.Length); + Assert.Equal("GFX0023", diagnostics[0].Id); + Assert.Equal("GFX0025", diagnostics[1].Id); + Assert.Contains(bannedName, diagnostics[1].GetMessage()); + } + + [Fact] + public async Task RegisteredConsumerAssembly_OwnEdgesAreChecked() + { + var apps = Emit("GameFrameX.Apps", "public class Data { }"); + var matchmaking = Emit("GameFrameX.Capability.Online.Matchmaking", "public class Dependency { }"); + var social = Emit("GameFrameX.Capability.Online.Social", "public class Peer { public Dependency Value; }", matchmaking); + // 编译自身 = 登记包(同层违规),直接引用出边也应被检查(Hotfix→Apps 合法,Social→Matchmaking 同层违规)。 + var diagnostics = await Analyze(Compile("GameFrameX.Hotfix", "public class Consumer { }", apps, social), new CapabilityPackageLayeringAnalyzer()); + var violation = Assert.Single(diagnostics); + Assert.Equal("GFX0023", violation.Id); + Assert.Contains("GameFrameX.Capability.Online.Social", violation.GetMessage()); + } + + [Fact] + public async Task UnregisteredAssemblies_AreIgnored() + { + var external = Emit("Contoso.External", "public class External { }"); + var consumer = Emit("GameFrameX.Capability.Online.Match", "public class Peer { public External Value; }", external); + Assert.Empty(await Analyze(Compile("GameFrameX.Tests", "public class Consumer { }", consumer), new CapabilityPackageLayeringAnalyzer())); + } + + private static CSharpCompilation Compile(string name, string source, params MetadataReference[] references) + { + var compilation = CSharpCompilation.Create(name, new[] { CSharpSyntaxTree.ParseText(source, path: "Fixture.cs") }, + PlatformReferences.Concat(references), new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + AssertNoErrors(compilation); + return compilation; + } + + private static MetadataReference Emit(string name, string source, params MetadataReference[] references) + { + using (var stream = new MemoryStream()) + { + var result = Compile(name, source, references).Emit(stream); + Assert.True(result.Success, string.Join(System.Environment.NewLine, result.Diagnostics)); + return MetadataReference.CreateFromImage(stream.ToArray()); + } + } + + private static void AssertNoErrors(Compilation compilation) + { + Assert.Empty(compilation.GetDiagnostics().Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)); + } + + private static async Task> Analyze(Compilation compilation, DiagnosticAnalyzer analyzer) + { + var diagnostics = await compilation.WithAnalyzers(ImmutableArray.Create(analyzer)).GetAnalyzerDiagnosticsAsync(); + Assert.DoesNotContain(diagnostics, diagnostic => diagnostic.Id == "AD0001"); + return diagnostics; + } +} diff --git a/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj b/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj index 27ec729cb..f7324b7fc 100644 --- a/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj +++ b/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj @@ -53,6 +53,7 @@ + @@ -65,6 +66,7 @@ + diff --git a/Tests/GameFrameX.Tests/Online/CapabilityPackageStructureTests.cs b/Tests/GameFrameX.Tests/Online/CapabilityPackageStructureTests.cs index 142ce9ef8..c5bd2a190 100644 --- a/Tests/GameFrameX.Tests/Online/CapabilityPackageStructureTests.cs +++ b/Tests/GameFrameX.Tests/Online/CapabilityPackageStructureTests.cs @@ -40,9 +40,9 @@ namespace GameFrameX.Tests.Online public class CapabilityPackageStructureTests { /// - /// 期望的 ProjectReference 精确集合(工程 → 允许引用的工程名集合;C294 终态,逐条取自 Capability/*/ *.csproj: - /// Hosting.Abstractions → Localization;Hosting.AdminApi → Abstractions + Localization + Hosting.Core; - /// Online.Abstractions → Localization + Hosting.AdminApi;Social → Apps + DataBase;Match → Core + Proto)。 + /// 期望的 ProjectReference 精确集合(工程 → 允许引用的工程名集合;包结构收敛终态,逐条取自 Capability/*/*.csproj: + /// 管理契约 13 型上移后 Online.Abstractions → Localization + Hosting.Abstractions(不再引 AdminApi); + /// Social 拆 Apps/DataBase、Match 拆 Core/Proto;Leaderboard 自 Competition 拆包;Competition(冻结)→ Abstractions + Assets + Leaderboard)。 /// private static readonly Dictionary ExpectedProjectReferences = new() { @@ -50,12 +50,13 @@ public class CapabilityPackageStructureTests ["GameFrameX.Capability.Hosting.Core"] = new[] { "GameFrameX.Capability.Hosting.Abstractions", "GameFrameX.Localization" }, ["GameFrameX.Capability.Hosting.AdminApi"] = new[] { "GameFrameX.Capability.Hosting.Abstractions", "GameFrameX.Localization", "GameFrameX.Capability.Hosting.Core" }, ["GameFrameX.Capability.Online.Assets"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Hosting.Core" }, - ["GameFrameX.Capability.Online.Social"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Online.Foundation", "GameFrameX.Capability.Hosting.Core", "GameFrameX.DataBase", "GameFrameX.Apps" }, + ["GameFrameX.Capability.Online.Social"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Online.Foundation", "GameFrameX.Capability.Hosting.Core" }, ["GameFrameX.Capability.Online.Matchmaking"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Hosting.Core" }, - ["GameFrameX.Capability.Online.Match"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Online.Assets", "GameFrameX.Core", "GameFrameX.Proto", "GameFrameX.Capability.Online.Matchmaking", "GameFrameX.Capability.Hosting.Core" }, - ["GameFrameX.Capability.Online.Competition"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Online.Assets", "GameFrameX.Capability.Online.Match", "GameFrameX.Capability.Hosting.Core" }, + ["GameFrameX.Capability.Online.Leaderboard"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Online.Match" }, + ["GameFrameX.Capability.Online.Match"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Online.Assets", "GameFrameX.Capability.Online.Matchmaking", "GameFrameX.Capability.Hosting.Core" }, + ["GameFrameX.Capability.Online.Competition"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Online.Assets", "GameFrameX.Capability.Online.Leaderboard" }, ["GameFrameX.Capability.Online.Operations"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Online.Foundation", "GameFrameX.Capability.Online.Assets", "GameFrameX.Capability.Online.Social", "GameFrameX.Capability.Online.Matchmaking", "GameFrameX.Capability.Online.Match", "GameFrameX.Capability.Hosting.Core" }, - ["GameFrameX.Capability.Online.Abstractions"] = new[] { "GameFrameX.Localization", "GameFrameX.Capability.Hosting.AdminApi" }, + ["GameFrameX.Capability.Online.Abstractions"] = new[] { "GameFrameX.Localization", "GameFrameX.Capability.Hosting.Abstractions" }, ["GameFrameX.Capability.Online.Foundation"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Hosting.Core" }, ["GameFrameX.Capability.Online.Persistence"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Online.Foundation", "GameFrameX.Capability.Online.Assets", "GameFrameX.Capability.Online.Social", "GameFrameX.Capability.Online.Match", "GameFrameX.Capability.Hosting.Core", "GameFrameX.DataBase" }, }; @@ -70,6 +71,7 @@ private static readonly (string PackageName, string CapabilityId, GameFrameX.Cap ("GameFrameX.Capability.Online.Assets", "online-assets", GameFrameX.Capability.Online.Assets.OnlineAssetsCapabilityModule.ManifestInstance), ("GameFrameX.Capability.Online.Social", "online-social", GameFrameX.Capability.Online.Social.OnlineSocialCapabilityModule.ManifestInstance), ("GameFrameX.Capability.Online.Matchmaking", "online-matchmaking", GameFrameX.Capability.Online.Matchmaking.OnlineMatchmakingCapabilityModule.ManifestInstance), + ("GameFrameX.Capability.Online.Leaderboard", "online-leaderboard", GameFrameX.Capability.Online.Leaderboard.OnlineLeaderboardCapabilityModule.ManifestInstance), ("GameFrameX.Capability.Online.Match", "online-match", GameFrameX.Capability.Online.Match.OnlineMatchCapabilityModule.ManifestInstance), ("GameFrameX.Capability.Online.Competition", "online-competition", GameFrameX.Capability.Online.Competition.OnlineCompetitionCapabilityModule.ManifestInstance), ("GameFrameX.Capability.Online.Operations", "online-operations", GameFrameX.Capability.Online.Operations.OnlineOperationsCapabilityModule.ManifestInstance), @@ -180,6 +182,7 @@ public void Launcher_ReferencesOnlineCapabilityPackages_Directly() "GameFrameX.Capability.Online.Assets", "GameFrameX.Capability.Online.Competition", "GameFrameX.Capability.Online.Foundation", + "GameFrameX.Capability.Online.Leaderboard", "GameFrameX.Capability.Online.Match", "GameFrameX.Capability.Online.Matchmaking", "GameFrameX.Capability.Online.Operations", diff --git a/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs index 9e24bf7f7..823d972e3 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs @@ -87,29 +87,29 @@ private static void AssertInnerCode(string innerJson, OnlineErrorCode expectedCo } /// - /// 验证注册表 = 七能力 manifest 声明的全部业务 action + 三个机制元端点(双向对账后两边严格相等)。 + /// 验证注册表 = 八能力 manifest 声明的全部业务 action + 三个机制元端点(双向对账后两边严格相等)。 /// [Fact] - public async Task ActionNames_ShouldRegisterAllThirtySevenDeclaredActionsPlusThreeMetaEndpoints() + public async Task ActionNames_ShouldRegisterAllThirtyDeclaredActionsPlusThreeMetaEndpoints() { await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => { var dispatcher = OnlineCapabilityTestHarness.CreateDispatcher(runtime.Host); - // 业务 action 37 = assets 7(grant_asset / revoke_asset / query_wallet_ledger / query_asset_audit / query_transaction_detail + // 业务 action 30 = assets 7(grant_asset / revoke_asset / query_wallet_ledger / query_asset_audit / query_transaction_detail // / query_compensation_queue / resolve_compensation_manual_review) // + foundation 1(suspend_resume_player) // + social 8(kick_player / revoke_token / mute_player / query_report_cases / update_report_case / // send_admin_notification / query_chat_messages / match_isolation) // + matchmaking 4(query_match_queue_overview / query_match_ticket_failures / query_match_abnormal_tickets / cancel_match_ticket) // + match 2(end_abnormal_match / query_match_settlement) - // + competition 8(LiveOps 7 + query_leaderboard) + // + leaderboard 1(query_leaderboard) // + operations 7(query_online_overview / query_player_timeline / query_online_audit_events + hotfix 受控操作族 4); // 机制元端点 3:list_capabilities + list_capability_settings(调度器持有报告)+ list_capability_services(调度器持有服务面)。 var declaredActions = runtime.Report.Entries.SelectMany(entry => entry.Manifest.Actions).ToList(); - Assert.Equal(37, declaredActions.Count); + Assert.Equal(30, declaredActions.Count); Assert.Equal(declaredActions.Count + 3, dispatcher.ActionNames.Count); - Assert.Equal(40, dispatcher.ActionNames.Count); + Assert.Equal(33, dispatcher.ActionNames.Count); foreach (var action in declaredActions) { Assert.Contains(action, dispatcher.ActionNames); @@ -120,7 +120,6 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => Assert.Contains("list_capability_services", dispatcher.ActionNames); Assert.Contains("query_match_settlement", dispatcher.ActionNames); Assert.Contains("query_leaderboard", dispatcher.ActionNames); - Assert.Contains("rollbackConfigRollout", dispatcher.ActionNames); Assert.Contains("rollback_hotfix_version", dispatcher.ActionNames); return Task.CompletedTask; }); @@ -136,7 +135,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => { var dispatcher = OnlineCapabilityTestHarness.CreateDispatcher(runtime.Host); - var envelopeJson = await dispatcher.DispatchAsync("query_compensation_queue", "{\"ServerId\":1001}"); + var envelopeJson = await dispatcher.DispatchAsync("query_compensation_queue", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}"); var innerJson = ReadInnerJson(envelopeJson); using (var document = JsonDocument.Parse(innerJson)) { @@ -159,7 +158,7 @@ public async Task Dispatch_UnknownAction_ShouldReturnInner4002() { await WithDispatcherAsync(async dispatcher => { - var envelope = await dispatcher.DispatchAsync("definitely_not_an_action", "{\"ServerId\":1001}"); + var envelope = await dispatcher.DispatchAsync("definitely_not_an_action", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}"); AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.ResourceNotFound); }); } @@ -191,12 +190,14 @@ await WithDispatcherAsync(async dispatcher => } /// - /// 验证跨区服作用域返回 3004(单键化后不再产生 3002/3003)。 + /// 验证跨租户 / 跨应用 / 跨区服分别返回 3002 / 3003 / 3004。 /// /// 请求体。 /// 期望业务码。 [Theory] - [InlineData("{\"ServerId\":2002}", OnlineErrorCode.ServerScopeDenied)] + [InlineData("{\"TenantId\":2,\"AppId\":1,\"ServerId\":1001}", OnlineErrorCode.CrossTenantDenied)] + [InlineData("{\"TenantId\":1,\"AppId\":2,\"ServerId\":1001}", OnlineErrorCode.CrossAppDenied)] + [InlineData("{\"TenantId\":1,\"AppId\":1,\"ServerId\":2002}", OnlineErrorCode.ServerScopeDenied)] public async Task Dispatch_ScopeMismatch_ShouldReturnGuardCode(string body, OnlineErrorCode expectedCode) { await WithDispatcherAsync(async dispatcher => @@ -215,7 +216,7 @@ public async Task Dispatch_GrantAsset_ShouldRoundTripThroughLedgerAndDetail() await WithDispatcherAsync(async dispatcher => { var grantEnvelope = await dispatcher.DispatchAsync("grant_asset", - "{\"ServerId\":1001,\"PlayerId\":\"9001\",\"Reason\":\"admin-test\",\"IdempotencyKey\":\"GFX-GRANT-test-1\",\"GrantItems\":[{\"ItemOrCurrencyType\":\"Coin\",\"Quantity\":100}]}"); + "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9001\",\"Reason\":\"admin-test\",\"IdempotencyKey\":\"GFX-GRANT-test-1\",\"GrantItems\":[{\"ItemOrCurrencyType\":\"Coin\",\"Quantity\":100}]}"); string transactionId; using (var document = JsonDocument.Parse(ReadInnerJson(grantEnvelope))) { @@ -230,7 +231,7 @@ await WithDispatcherAsync(async dispatcher => } var ledgerEnvelope = await dispatcher.DispatchAsync("query_wallet_ledger", - "{\"ServerId\":1001,\"PlayerId\":\"9001\",\"PageSize\":20}"); + "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9001\",\"PageSize\":20}"); using (var ledgerDocument = JsonDocument.Parse(ReadInnerJson(ledgerEnvelope))) { var items = ledgerDocument.RootElement.GetProperty("Data").GetProperty("Items"); @@ -242,7 +243,7 @@ await WithDispatcherAsync(async dispatcher => } var detailEnvelope = await dispatcher.DispatchAsync("query_transaction_detail", - "{\"ServerId\":1001,\"TransactionId\":\"" + transactionId + "\"}"); + "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"TransactionId\":\"" + transactionId + "\"}"); using (var detailDocument = JsonDocument.Parse(ReadInnerJson(detailEnvelope))) { var data = detailDocument.RootElement.GetProperty("Data"); @@ -264,7 +265,7 @@ public async Task Dispatch_GrantAsset_WithoutPlayer_ShouldReturnInner4001() await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("grant_asset", - "{\"ServerId\":1001,\"Reason\":\"admin-test\",\"GrantItems\":[{\"ItemOrCurrencyType\":\"Coin\",\"Quantity\":100}]}"); + "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"Reason\":\"admin-test\",\"GrantItems\":[{\"ItemOrCurrencyType\":\"Coin\",\"Quantity\":100}]}"); AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.ParameterInvalid); }); } @@ -277,7 +278,7 @@ public async Task Dispatch_MutePlayer_TwiceWithSameKey_ShouldReplayFirstResponse { await WithDispatcherAsync(async dispatcher => { - const string body = "{\"ServerId\":1001,\"PlayerId\":\"9002\",\"PenaltyId\":77,\"IdempotencyKey\":\"penalty-77-mute-1001\"}"; + const string body = "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9002\",\"PenaltyId\":77,\"IdempotencyKey\":\"penalty-77-mute-1001\"}"; var first = await dispatcher.DispatchAsync("mute_player", body); var second = await dispatcher.DispatchAsync("mute_player", body); Assert.Equal(first, second); @@ -299,7 +300,7 @@ public async Task Dispatch_KickPlayer_WithoutSessions_ShouldConfirm() await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("kick_player", - "{\"ServerId\":1001,\"PlayerId\":\"9003\",\"PenaltyId\":78,\"IdempotencyKey\":\"penalty-78-kick-1001\"}"); + "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9003\",\"PenaltyId\":78,\"IdempotencyKey\":\"penalty-78-kick-1001\"}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var root = document.RootElement; @@ -317,7 +318,7 @@ public async Task Dispatch_QueryOnlineOverview_ShouldReturnCounters() { await WithDispatcherAsync(async dispatcher => { - var envelope = await dispatcher.DispatchAsync("query_online_overview", "{\"ServerId\":1001}"); + var envelope = await dispatcher.DispatchAsync("query_online_overview", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var root = document.RootElement; @@ -342,7 +343,7 @@ public async Task Dispatch_EndAbnormalMatch_ShouldReturnInner5003() await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("end_abnormal_match", - "{\"ServerId\":1001,\"MatchId\":\"m-1\",\"Reason\":\"test\",\"ReviewerOperatorId\":\"admin\",\"IdempotencyKey\":\"onlineControlled-end_abnormal_match-m-1-1001\"}"); + "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"MatchId\":\"m-1\",\"Reason\":\"test\",\"ReviewerOperatorId\":\"admin\",\"IdempotencyKey\":\"onlineControlled-end_abnormal_match-m-1-1001\"}"); AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.StateOperationForbidden); }); } @@ -356,7 +357,7 @@ public async Task Dispatch_QueryPlayerTimeline_Empty_ShouldReturnEmptyEvents() await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("query_player_timeline", - "{\"ServerId\":1001,\"PlayerId\":\"9004\"}"); + "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9004\"}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var data = document.RootElement.GetProperty("Data"); @@ -366,67 +367,6 @@ await WithDispatcherAsync(async dispatcher => }); } - /// - /// 验证 publishRemoteConfig(LiveOps 族)成功返回确认版本。 - /// - [Fact] - public async Task Dispatch_PublishRemoteConfig_ShouldReturnConfirmVersion() - { - await WithDispatcherAsync(async dispatcher => - { - var envelope = await dispatcher.DispatchAsync("publishRemoteConfig", - "{\"ServerId\":1001,\"ConfigId\":5001,\"Reason\":\"admin-test\"}"); - using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) - { - var root = document.RootElement; - Assert.Equal(0, root.GetProperty("Code").GetInt32()); - var data = root.GetProperty("Data"); - Assert.False(string.IsNullOrEmpty(data.GetProperty("ConfirmVersion").GetString())); - Assert.True(data.GetProperty("ServerTime").GetInt64() > 0); - } - }); - } - - /// - /// 验证 publishConfigRollout 灰度百分比超界(101 / -1)返回内层 4001(边界校验拒绝非法值)。 - /// - [Fact] - public async Task Dispatch_PublishConfigRollout_PercentOutOfRange_ShouldReturnInner4001() - { - await WithDispatcherAsync(async dispatcher => - { - var envelope = await dispatcher.DispatchAsync("publishConfigRollout", - "{\"ServerId\":1001,\"ConfigKind\":1,\"ConfigKey\":\"remote-config-key\",\"ConfigVersion\":3,\"Percent\":101,\"Reason\":\"admin-test\"}"); - AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.ParameterInvalid); - - envelope = await dispatcher.DispatchAsync("publishConfigRollout", - "{\"ServerId\":1001,\"ConfigKind\":1,\"ConfigKey\":\"remote-config-key\",\"ConfigVersion\":3,\"Percent\":-1,\"Reason\":\"admin-test\"}"); - AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.ParameterInvalid); - }); - } - - /// - /// 验证 publishConfigRollout 灰度百分比合法边界(0 / 100 / 缺省)成功返回确认版本。 - /// - [Fact] - public async Task Dispatch_PublishConfigRollout_PercentBoundary_ShouldReturnConfirmVersion() - { - await WithDispatcherAsync(async dispatcher => - { - foreach (var percent in new[] { "\"Percent\":0,", "\"Percent\":100,", "" }) - { - var envelope = await dispatcher.DispatchAsync("publishConfigRollout", - "{\"ServerId\":1001,\"ConfigKind\":1,\"ConfigKey\":\"remote-config-key\",\"ConfigVersion\":3," + percent + "\"Reason\":\"admin-test\"}"); - using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) - { - var root = document.RootElement; - Assert.Equal(0, root.GetProperty("Code").GetInt32()); - Assert.False(string.IsNullOrEmpty(root.GetProperty("Data").GetProperty("ConfirmVersion").GetString())); - } - } - }); - } - /// /// 验证 suspend_resume_player 缺 Direction 返回内层 4001(受控双向命令必填)。 /// @@ -436,7 +376,7 @@ public async Task Dispatch_SuspendResumePlayer_WithoutDirection_ShouldReturnInne await WithDispatcherAsync(async dispatcher => { var envelope = await dispatcher.DispatchAsync("suspend_resume_player", - "{\"ServerId\":1001,\"PlayerId\":\"9005\",\"Reason\":\"test\",\"ReviewerOperatorId\":\"admin\",\"IdempotencyKey\":\"onlineControlled-suspend_resume_player-9005-1001\"}"); + "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"PlayerId\":\"9005\",\"Reason\":\"test\",\"ReviewerOperatorId\":\"admin\",\"IdempotencyKey\":\"onlineControlled-suspend_resume_player-9005-1001\"}"); AssertInnerCode(ReadInnerJson(envelope), OnlineErrorCode.ParameterInvalid); }); } @@ -449,7 +389,7 @@ public async Task Dispatch_QueryReportCases_Empty_ShouldReturnEmptyItems() { await WithDispatcherAsync(async dispatcher => { - var envelope = await dispatcher.DispatchAsync("query_report_cases", "{\"ServerId\":1001}"); + var envelope = await dispatcher.DispatchAsync("query_report_cases", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var data = document.RootElement.GetProperty("Data"); @@ -467,7 +407,7 @@ public async Task Dispatch_QueryMatchQueueOverview_ShouldReturnQueuesArray() { await WithDispatcherAsync(async dispatcher => { - var envelope = await dispatcher.DispatchAsync("query_match_queue_overview", "{\"ServerId\":1001}"); + var envelope = await dispatcher.DispatchAsync("query_match_queue_overview", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001}"); using (var document = JsonDocument.Parse(ReadInnerJson(envelope))) { var data = document.RootElement.GetProperty("Data"); diff --git a/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs b/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs index 343eef36c..5a5711999 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs @@ -82,13 +82,14 @@ public class OnlineCapabilityComposeTests private static readonly HttpClient SharedHttpClient = new HttpClient(); /// - /// 七能力全装配的拓扑序(依赖边:social→foundation、matchmaking→social、match 可选 assets/matchmaking、 - /// competition 可选 assets/match、operations→foundation 可选 assets/social/match/matchmaking;同层按能力 Id Ordinal)。 + /// 八能力全装配的拓扑序(依赖边:social→foundation、matchmaking→social、match 可选 assets/matchmaking、 + /// leaderboard 可选 match、competition 必选 leaderboard 可选 assets、operations→foundation 可选 assets/social/match/matchmaking; + /// 同层按能力 Id Ordinal)。 /// private static readonly string[] ExpectedTopologicalOrder = { "online-assets", "online-foundation", "online-social", "online-matchmaking", - "online-match", "online-competition", "online-operations", + "online-match", "online-leaderboard", "online-competition", "online-operations", }; /// @@ -189,7 +190,7 @@ private static async Task PostAsync(string action, string body) } /// - /// 业务面单开:产出业务宿主、无管理面;七能力全部启用,装配序 = 拓扑序(依赖恒先于依赖方),宿主模块表同序。 + /// 业务面单开:产出业务宿主、无管理面;八能力全部启用,装配序 = 拓扑序(依赖恒先于依赖方),宿主模块表同序。 /// [Fact] public async Task Compose_RuntimeOnly_ComposesHostWithoutAdminInTopologicalOrder() @@ -199,7 +200,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => Assert.NotNull(runtime.Host); Assert.Null(runtime.AdminApi); Assert.Equal(ExpectedTopologicalOrder, runtime.Report.EnabledIdsInOrder); - Assert.Equal(7, runtime.Report.Entries.Count(entry => entry.State == CapabilityFilterState.Enabled)); + Assert.Equal(8, runtime.Report.Entries.Count(entry => entry.State == CapabilityFilterState.Enabled)); Assert.Equal(ExpectedTopologicalOrder, runtime.Host.Modules.Select(module => module.Manifest.Id).ToArray()); var order = runtime.Report.EnabledIdsInOrder.ToList(); @@ -221,7 +222,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => /// /// 管理面单开(EnableRuntime=false + UseAdminApi):业务宿主不交付(Host 为 null),管理面产出; - /// 新设计下每个模块的 Register 仍执行,报告完整(七能力全部启用、拓扑序不变)。 + /// 新设计下每个模块的 Register 仍执行,报告完整(八能力全部启用、拓扑序不变)。 /// [Fact] public async Task Compose_AdminOnly_HostNullAdminPresentReportComplete() @@ -264,14 +265,14 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => } /// - /// 空列表 = 全装配红线:白名单与排除表均为空数组时不过滤,七能力全部启用。 + /// 空列表 = 全装配红线:白名单与排除表均为空数组时不过滤,八能力全部启用。 /// [Fact] public async Task Compose_EmptyFilterLists_AssembleAll() { await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => { - Assert.Equal(7, runtime.Report.Entries.Count(entry => entry.State == CapabilityFilterState.Enabled)); + Assert.Equal(8, runtime.Report.Entries.Count(entry => entry.State == CapabilityFilterState.Enabled)); Assert.Equal(ExpectedTopologicalOrder, runtime.Report.EnabledIdsInOrder); return Task.CompletedTask; }, null, options => options.Filter = new CapabilityAssemblyFilter(Array.Empty(), Array.Empty())); @@ -285,7 +286,7 @@ public async Task Compose_BlankEntries_TreatedAsUnfiltered() { await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => { - Assert.Equal(7, runtime.Report.Entries.Count(entry => entry.State == CapabilityFilterState.Enabled)); + Assert.Equal(8, runtime.Report.Entries.Count(entry => entry.State == CapabilityFilterState.Enabled)); return Task.CompletedTask; }, null, options => options.Filter = new CapabilityAssemblyFilter(new[] { string.Empty, " " }, new[] { string.Empty, " " })); } @@ -306,7 +307,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => } /// - /// 排除表生效:叶子能力 online-operations(无下游必选依赖)为 ExcludedByDisableList,其余六能力保持装配。 + /// 排除表生效:叶子能力 online-operations(无下游必选依赖)为 ExcludedByDisableList,其余七能力保持装配。 /// [Fact] public async Task Compose_DisableList_ExcludesCapabilityFromReport() @@ -314,7 +315,7 @@ public async Task Compose_DisableList_ExcludesCapabilityFromReport() await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => { Assert.Equal(CapabilityFilterState.ExcludedByDisableList, FindEntry(runtime.Report, "online-operations").State); - Assert.Equal(6, runtime.Report.EnabledIdsInOrder.Count); + Assert.Equal(7, runtime.Report.EnabledIdsInOrder.Count); Assert.DoesNotContain("online-operations", runtime.Report.EnabledIdsInOrder); return Task.CompletedTask; }, null, options => options.Filter = new CapabilityAssemblyFilter(null, new[] { "online-operations" })); @@ -336,7 +337,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => var payload = inner.RootElement.GetProperty("Data"); Assert.Equal("online-operations", payload.GetProperty("NotInstalledCapability").GetString()); var installed = ReadStrings(payload.GetProperty("InstalledCapabilities")); - Assert.Equal(6, installed.Length); + Assert.Equal(7, installed.Length); Assert.DoesNotContain("online-operations", installed); } }, null, options => options.Filter = new CapabilityAssemblyFilter(null, new[] { "online-operations" })); @@ -368,10 +369,10 @@ await WithComposedAsync(options, async runtime => Assert.Equal(0, inner.RootElement.GetProperty("Code").GetInt32()); var data = inner.RootElement.GetProperty("Data"); var entries = IndexBy(data.GetProperty("Capabilities"), "Id"); - Assert.Equal(7, entries.Count); + Assert.Equal(8, entries.Count); Assert.Equal("ExcludedByDisableList", entries["online-assets"].GetProperty("State").GetString()); Assert.Equal("Enabled", entries["online-foundation"].GetProperty("State").GetString()); - Assert.Equal(6, data.GetProperty("EnabledIdsInOrder").GetArrayLength()); + Assert.Equal(7, data.GetProperty("EnabledIdsInOrder").GetArrayLength()); } using (var inner = ParseInner(await PostAsync("grant_asset", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"RequestId\":\"r2\"}"))) @@ -601,7 +602,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => Assert.Equal(ExpectedTopologicalOrder, ReadStrings(data.GetProperty("EnabledIdsInOrder"))); var entries = IndexBy(data.GetProperty("Capabilities"), "Id"); - Assert.Equal(7, entries.Count); + Assert.Equal(8, entries.Count); var match = entries["online-match"]; Assert.Equal(new[] { "online-assets", "online-matchmaking" }, ReadStrings(match.GetProperty("OptionalCapabilityIds"))); @@ -733,7 +734,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => var match = FindEntry(runtime.Report, "online-match"); Assert.Equal(CapabilityFilterState.Enabled, match.State); Assert.Contains("online-match", runtime.Report.EnabledIdsInOrder); - Assert.Equal(5, runtime.Report.EnabledIdsInOrder.Count); + Assert.Equal(6, runtime.Report.EnabledIdsInOrder.Count); foreach (var absentId in new[] { "online-assets", "online-matchmaking" }) { diff --git a/Tests/GameFrameX.Tests/Online/OnlineCapabilityTestHarness.cs b/Tests/GameFrameX.Tests/Online/OnlineCapabilityTestHarness.cs index f2dd9bb9d..34901ff36 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineCapabilityTestHarness.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineCapabilityTestHarness.cs @@ -38,6 +38,7 @@ using GameFrameX.Capability.Online.Abstractions.Contracts; using GameFrameX.Capability.Online.Abstractions.Idempotency; using GameFrameX.Capability.Online.Abstractions.Scope; +using GameFrameX.Capability.Online.Match; using GameFrameX.Capability.Online.Operations.HotfixRollback; using GameFrameX.Capability.Online.Social; using Xunit; @@ -87,6 +88,9 @@ public static CapabilityCompositionOptions CreateOptions(string settingsJson = n // 宿主扩展点:Social 的玩家目录与 Operations 的热更回滚执行器(两者均 RequireHostService,缺失即装配 fail-fast)。 options.Override(new EmptyPlayerDirectory()); options.Override(new NoopHotfixRollbackExecutor()); + + // 玩法注入:RPS 验收夹具游戏(原包内自动注册的对局玩法;生产装配由各宿主组合根自行注入)。 + options.Configure(match => match.AddGame(new OnlineRockPaperScissorsGame())); return options; } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs index 06d3e2ad8..4eecf0bd2 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs @@ -38,6 +38,9 @@ using GameFrameX.Capability.Online.Abstractions.Scope; using GameFrameX.Capability.Online.Assets; using GameFrameX.Capability.Online.Competition; +using GameFrameX.Capability.Online.Abstractions; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Leaderboard; using GameFrameX.Capability.Online.Competition.Leaderboard; using GameFrameX.Capability.Online.Match; using GameFrameX.Foundation.Idempotency; @@ -73,8 +76,8 @@ public class OnlineMatchSettledLeaderboardProjectorTests /// 静默调度间隔(毫秒):tick 一律由用例显式驱动,后台循环在用例时长内不触发。 private const int QuietSchedulerIntervalMilliseconds = 3600000; - /// Competition 投影配置段(Settings 子对象:目标榜单 = )。 - private const string ProjectionSettings = "{\"online-competition\":{\"LeaderboardProjection\":{\"MatchSettledBoardId\":\"" + BoardId + "\"}}}"; + /// Leaderboard 投影配置段(Settings 子对象:目标榜单 = )。 + private const string ProjectionSettings = "{\"online-leaderboard\":{\"LeaderboardProjection\":{\"MatchSettledBoardId\":\"" + BoardId + "\"}}}"; /// /// 验证订阅半边:结算事件驱动投影落榜(Top 查询可见分数),同 EventId 重复投递被去重。 @@ -209,7 +212,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => Assert.NotNull(entry); Assert.Equal(42, entry.Score); Assert.Empty(projector.QueryStatus()); - }, ProjectionSettings, options => ConfigureComposition(options, null, "online-match", "online-competition")); + }, ProjectionSettings, options => ConfigureComposition(options, null, "online-match", "online-leaderboard")); } /// @@ -221,12 +224,41 @@ public async Task Compose_ZeroSettingsDefaultsProjectionOn_BlankOverrideTurnsItO { var configured = await RunOneTickRoundAsync(ProjectionSettings, true); var zeroSettings = await RunOneTickRoundAsync(null, true); - var blankBoard = await RunOneTickRoundAsync("{\"online-competition\":{\"LeaderboardProjection\":{\"MatchSettledBoardId\":\" \"}}}", false); + var blankBoard = await RunOneTickRoundAsync("{\"online-leaderboard\":{\"LeaderboardProjection\":{\"MatchSettledBoardId\":\" \"}}}", false); Assert.Equal(configured, zeroSettings); Assert.Equal(configured - 1, blankBoard); } + /// + /// 零玩法形态回归:宿主未注入任何玩法时 online-match 照常装配(运行时 / 结算管线在场), + /// 但对局桥与匹配域桥均不发布(缺席态由桥显式失败承载)、通知出站端口保持缺省空实现。 + /// + [Fact] + public async Task Compose_WithoutGames_SkipsBridgesButComposesRuntime() + { + var options = new CapabilityCompositionOptions(OnlineCapabilityTestHarness.FamilySection(null), new CollectingCapabilityAssemblyLog()) + { + HostOptions = new CapabilityHostOptions { TenantId = TenantId, AppId = AppId, ServerId = ServerId, }, + }; + ConfigureComposition(options, null, "online-match"); + var runtime = CapabilityComposition.Compose(new OnlineCapabilityFamily(), options); + try + { + await runtime.Host.StartAsync(); + var entry = runtime.Report.Entries.Single(item => item.Manifest.Id == "online-match"); + Assert.Equal(CapabilityFilterState.Enabled, entry.State); + Assert.NotNull(runtime.Host.Services.GetService()); + Assert.Null(runtime.Host.Services.GetOptionalService()); + Assert.Null(runtime.Host.Services.GetOptionalService()); + Assert.IsType(runtime.Host.Services.GetService()); + } + finally + { + await runtime.StopAsync(); + } + } + /// /// 验证可选依赖缺席:配置了投影榜 id 但 online-match 未装配(对局结果存储缺席)→ 不装配投影器、不报错。 /// @@ -239,21 +271,27 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => Assert.DoesNotContain("online-match", runtime.Report.EnabledIdsInOrder); Assert.Null(runtime.Host.Services.GetOptionalService()); - }, ProjectionSettings, options => ConfigureComposition(options, null, "online-competition")); + }, ProjectionSettings, options => ConfigureComposition(options, null, "online-leaderboard")); } /// - /// 验证依赖声明(C294:竞技对对局为可选依赖):online-competition 以可选方式声明 online-match 且无必选依赖, - /// online-match 不以任何方式依赖 online-competition(拓扑无环)。 + /// 验证依赖声明(榜单自竞技拆包后):online-competition 必选依赖 online-leaderboard(赛季 / 锦标赛的榜单写路径)、 + /// 可选依赖 online-assets;online-leaderboard 可选依赖 online-match 且无必选依赖; + /// online-match 不以任何方式依赖两者(拓扑无环)。 /// [Fact] public void ManifestDependency_ShouldBeAcyclic() { var competition = OnlineCompetitionCapabilityModule.ManifestInstance; + var leaderboard = OnlineLeaderboardCapabilityModule.ManifestInstance; var match = OnlineMatchCapabilityModule.ManifestInstance; - Assert.Contains(competition.Optional, dependency => dependency.CapabilityId == "online-match"); - Assert.DoesNotContain("online-match", competition.Requires); + Assert.Contains("online-leaderboard", competition.Requires); + Assert.Contains(competition.Optional, dependency => dependency.CapabilityId == "online-assets"); + Assert.Contains(leaderboard.Optional, dependency => dependency.CapabilityId == "online-match"); + Assert.Empty(leaderboard.Requires); + Assert.DoesNotContain("online-leaderboard", match.Requires); + Assert.DoesNotContain(match.Optional, dependency => dependency.CapabilityId == "online-leaderboard"); Assert.DoesNotContain("online-competition", match.Requires); Assert.DoesNotContain(match.Optional, dependency => dependency.CapabilityId == "online-competition"); } @@ -294,7 +332,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => Assert.Empty(recorder.FailedJobNames); executed = recorder.LastExecutedJobCount; - }, settingsJson, options => ConfigureComposition(options, recorder, "online-match", "online-competition")); + }, settingsJson, options => ConfigureComposition(options, recorder, "online-match", "online-leaderboard")); Assert.True(executed > 0); return executed; From 6bed32e9e6892e97623ddfcd3670c490e44c9ccd Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 15:35:46 +0800 Subject: [PATCH 06/13] =?UTF-8?q?doc(changelog):=20=E7=99=BB=E8=AE=B0?= =?UTF-8?q?=E5=8C=85=E7=BB=93=E6=9E=84=E6=94=B6=E6=95=9B=E5=8F=98=E6=9B=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Linear: GFX-1199 --- CHANGELOG.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 117ad8114..31894a798 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -29,6 +29,8 @@ * Dockerfile 构建层优化:restore 前先分层 COPY 全部工程与属性文件(仅项目结构/版本清单变化才重新 restore,源码变更实测 restore 层命中 CACHED);删除 final 阶段重复的 publish COPY;热更 DLL 同步移除 `|| true` 吞错(glob 未匹配或复制失败改为构建期 fail fast);scripts/acceptance.sh 仓库根改为按脚本自身位置推导并修正解决方案为 Server.slnx(原硬编码个人绝对路径且引用已不存在的 Server.sln) +* 包结构收敛:Standard 12 包定格 + 五处倒挂修剪 + 分层规则分析器固化(C463,GFX-1199):①管理契约 13 型(`IAdminActionContributor`/`AdminActionRegistry`/`AdminApiRequest` 等)自 Hosting.AdminApi 上移 Hosting.Abstractions(命名空间保留),`Online.Abstractions` 拆除对 AdminApi 的反向依赖;②`Online.Social` 拆除对 Apps/DataBase 的引用(旧好友数据一次性迁移代码存档 `scripts/legacy/`,`MigrateLegacyFriendData` 配置键废止——能力配置绑定器对未知字段严格 fail-fast,老 JSON 须删除该键);③`Online.Match` 拆除对 Core.Session/Proto 的依赖——撮合成立推送改经出站契约 `IOnlineMatchAssignmentNotifier`(包内缺省空实现,Launcher 以 `OnlineMatchAssignmentSessionNotifier` 注入等价 best-effort 推送);④RPS 样例游戏三文件自 Online.Match 移入新验收夹具工程 `GameFrameX.Apps.Sample`(test-fixture),玩法经 `OnlineMatchOptions.AddGame` 由宿主注入(`IOnlineMatchGame` 增 `BuildBridgeView` 契约面,零玩法形态不发布对局桥);⑤排行榜自 Competition 拆独立包 `Online.Leaderboard`(新模块 online-leaderboard,`OnlineCompetitionOptions` 与 `query_leaderboard` 随迁,配置段改 `Online.Settings.online-leaderboard`),Competition 保留冻结的赛季/锦标赛(必选依赖 online-leaderboard);⑥LiveOps 运营面五文件拆离存档 `scripts/detached-liveops/`(移交 Admin 仓),Operations 分析面(游戏事件/总览/时间线)原地冻结标注;⑦新增分层分析器 GFX0023(层级单调+同层禁互引)/GFX0024(契约包零运行时引用)/GFX0025(能力包四禁引 Apps/Hotfix/Proto/Core),L0–L5+层内序注册表固化全部工程引用图;⑧slnx 分组 `/Capability/Standard|Frozen|Experimental` 与 `/Fixture/`,gfx-online 模板新增 Leaderboard 开关并显式引用 Hosting.AdminApi。admin 注册表业务 action 37→30;存量 `Online.Settings.online-competition.*` 配置段须迁移或删除(装配期严格 fail-fast)。 + ### Fixed * HTTP 请求管线正确性与响应一致性(C458,GFX-1180,GitHub #926):ProtoBuf 成功响应写出前更正 Content-Type 为 `application/x-protobuf`(原恒为 JSON,按媒体类型分派的客户端/网关解析二进制体失败);参数字典改 OrdinalIgnoreCase 并同步把 Query 提取改 TryAdd——大小写差异同名键(Query↔Body、Query↔Query)一律显式 `ParamErr` 拒绝,消除「被校验/被签名的 Query 值被 Body 静默覆盖」窗口;非 JSON 对象 Body(null 字面量/数组/标量/空体)以参数错误拒绝(新键 `Network.Http.RequestBodyNotJsonObject`),不再落入顶层 catch 记服务器错误日志;非 GET 缺 Content-Type 改统一 JSON envelope;DataAnnotations 校验失败业务码由字面量 400 统一为 `GameHttpStatusCode.ParamErr`;Swagger 路由匹配改末段精确比较(互为后缀命令不再错配文档,驼峰路由可匹配)且 GET 参数必填性跟随 `RequiredAttribute`;AOP 拒绝且未自行写响应时管线回写校验失败 envelope(契约写入 `IHttpAopHandler.Run`);`CheckSign` 缺 sign/timestamp 改本地化消息。对外破坏性:依赖 `code == 400` 判定校验失败的客户端改判 `code == 13`;`HttpStatusMessage.Success`/`NotFoundCommand`/`CheckFailedCommand` 及孤儿键 `Network.Http.NotFoundCommand`/`CheckFailedCommand` 删除(公共 API,下游如有引用需迁移)。 * Utility 安全修复:配置凭据脱敏、解压炸弹上限、冲突异常 Secret 脱敏与压缩失败显式抛出(C433,GFX-1173,GitHub #919):①`AppSetting.ToString/ToFormatString` 经浅拷贝掩码后序列化——`DataBasePassword`/`HttpSignSecret`/`InterNodeAuthSecret`/`HttpsCertPassword` 非空值输出 `***`(null/空串原样保留区分「未配置」),四个凭据不再随启动/停止日志明文外发;②`CompressionHelper.Decompress` 新增 `maxOutputLength` 上限重载(旧签名转发 const 默认 64MB),膨胀过程内超限即抛 `InvalidDataException`——Network `DefaultMessageDecompressHandler` 增构造参数上限、RemoteMessaging `IMessageCompressionAlgorithm.Decompress` 接口加参(const 默认值,源码兼容;`DefaultMessageCodec` 显式传 `_maxDecompressedSize`),事后长度检查降级为兜底防线,1MB 高压缩比帧不再可膨胀至 GB 级托管内存;③`SettingFieldConflict` 敏感字段判定扩展 Secret/Token 子串——多 Role 配置冲突异常不再明文携带 `HttpSignSecret`/`InterNodeAuthSecret`;④`RandomHelper` 类文档声明双随机源分级(基础接口 `Random.Shared` 非加密 PRNG 禁用于令牌/验证码/防作弊场景,安全场景用权重系列 CSPRNG 或 `RandomNumberGenerator`);⑤落地已归档 C349 既定方案:`Compress` 异常原样抛出、`Decompress` 对非法/损坏/截断数据统一抛 `InvalidDataException`(含 SharpZipLib 截断流死循环主动判定),删除「失败静默返回原始字节」回退与 `CompressFailed` 本地化键;⑥`FP.Sqrt/Acos` 越界异常构造器实参换序(本地化消息进 `Message`、`"x"` 进 `ParamName`,修复前 `ParamName == null`)。公共 API 行为变更经本条披露;解压炸弹/脱敏/截断/参数名均有回归用例锁定。 From 85ed852bb9cf640bea0f91587fe0a89fe40cb155 Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 17:45:46 +0800 Subject: [PATCH 07/13] =?UTF-8?q?fix(online-social):=20=E8=A1=A5=E9=BD=90?= =?UTF-8?q?=E5=8D=95=E9=94=AE=E5=8C=96=E9=81=97=E6=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit rebase 对齐 D4 时按分支侧解冲突,遗漏了 main 侧两处单键签名: 扫除 tick 任务 SweepExpiredAsync 已无租户/App 入参,投影测试 HostOptions 只剩 ServerId 单键,本提交一并对齐。 --- .../OnlineSocialCapabilityModule.cs | 5 ++--- .../Online/OnlineMatchSettledLeaderboardProjectorTests.cs | 2 +- 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs index c7781f197..ad36e325d 100644 --- a/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Social/OnlineSocialCapabilityModule.cs @@ -221,14 +221,13 @@ public void Register(CapabilityRegistrationContext context) context.AddService(_chat); context.AddService(_socialDecisions); - var scope = _scope; context.AddTickJob("notification-expiry-sweep", async ct => { - await _notifications.SweepExpiredAsync(scope.TenantId, scope.AppId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); + await _notifications.SweepExpiredAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); }); context.AddTickJob("friend-request-expiry-sweep", async ct => { - await _friends.SweepExpiredAsync(scope.TenantId, scope.AppId, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); + await _friends.SweepExpiredAsync(DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), ct).ConfigureAwait(false); }); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs index 4eecf0bd2..31c171ea9 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchSettledLeaderboardProjectorTests.cs @@ -239,7 +239,7 @@ public async Task Compose_WithoutGames_SkipsBridgesButComposesRuntime() { var options = new CapabilityCompositionOptions(OnlineCapabilityTestHarness.FamilySection(null), new CollectingCapabilityAssemblyLog()) { - HostOptions = new CapabilityHostOptions { TenantId = TenantId, AppId = AppId, ServerId = ServerId, }, + HostOptions = new CapabilityHostOptions { ServerId = ServerId, }, }; ConfigureComposition(options, null, "online-match"); var runtime = CapabilityComposition.Compose(new OnlineCapabilityFamily(), options); From ffc94bdcab6201aca566fb802aa98e0b891c401d Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 17:45:53 +0800 Subject: [PATCH 08/13] =?UTF-8?q?fix(online-match):=20=E5=AF=B9=E5=B1=80?= =?UTF-8?q?=E6=A8=A1=E5=BC=8F=E6=94=B9=E6=8C=89=E7=A5=A8=E6=8D=AE=E6=A8=A1?= =?UTF-8?q?=E5=BC=8F=E8=A7=A3=E6=9E=90=E6=89=BF=E8=BD=BD=E7=8E=A9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 原实现对局 Mode 恒写首个注册玩法的模式,多玩法注册时第二模式 会被改写为首个模式(PR #964 评审 Major)。现按票据模式解析承载 玩法:精确命中优先,单玩法形态回落承载全部票据模式(票据模式为 客户端撮合语义 1v1/2v2,与玩法注册键属两套取值空间),多玩法未 命中按未注册该模式显式失败;新增多模式回归测试固化三分支。 --- .../OnlineMatchDomainService.cs | 10 +- .../OnlineMatchRuntime.cs | 34 +++ .../Online/OnlineMatchDomainMultiModeTests.cs | 203 ++++++++++++++++++ 3 files changed, 246 insertions(+), 1 deletion(-) create mode 100644 Tests/GameFrameX.Tests/Online/OnlineMatchDomainMultiModeTests.cs diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchDomainService.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchDomainService.cs index c4d93d462..c859c8df8 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchDomainService.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchDomainService.cs @@ -568,12 +568,20 @@ private async Task> ResolveOrCreateActorAsync(Onl var actor = await _runtime.ResolveActorAsync(runtimeMatchId, cancellationToken).ConfigureAwait(false); if (actor == null) { + // 票据模式 → 承载玩法解析(精确命中优先;单玩法形态回落承载全部票据模式), + // 对局 Mode 取解析出玩法的注册键(与运行时玩法查表一致,多玩法下不再串写首个玩法的模式)。 + var game = _runtime.ResolveGameForTicketMode(registration.Mode); + if (game == null) + { + return OnlineResult.Fail(OnlineErrorCode.ParameterInvalid, "未注册该模式的玩法实现"); + } + var assignment = new OnlineMatchAssignment { ServerId = scope.ServerId, MatchId = runtimeMatchId, AssignmentId = registration.AssignmentId, - Mode = _game.Mode, + Mode = game.Mode, Region = registration.Region, CreatedAtTime = registration.CreatedAtTime, TicketIds = new List(registration.TicketIds), diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntime.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntime.cs index 498248523..c3ada5dc1 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntime.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchRuntime.cs @@ -148,6 +148,40 @@ public void RegisterGame(IOnlineMatchGame game) } } + /// + /// 按票据模式解析承载玩法:精确命中注册玩法时返回该玩法;未命中且全局仅注册单一玩法时回落该玩法 + /// (单玩法形态承载全部票据模式——票据模式为客户端撮合语义(如 1v1 / 2v2),与玩法注册键属两套取值空间); + /// 多玩法注册且未命中时返回 null(由调用方按未注册该模式处理)。 + /// + /// 票据匹配模式(客户端撮合语义)。 + /// 承载玩法;无法唯一定位时为 null。 + public IOnlineMatchGame ResolveGameForTicketMode(int ticketMode) + { + lock (_syncRoot) + { + if (_games.TryGetValue(ticketMode, out var game)) + { + return game; + } + + return _games.Count == 1 ? FirstRegisteredGame() : null; + } + } + + /// + /// 取唯一注册玩法(仅在 恰有一项时于锁内调用)。 + /// + /// 唯一注册玩法。 + private IOnlineMatchGame FirstRegisteredGame() + { + foreach (var game in _games.Values) + { + return game; + } + + return null; + } + /// /// 由匹配分配创建对局(上游匹配域的 assignment)。 /// 成员表按 assignment 的玩家集合预置(分配即成员已定),对局进入等待阶段。 diff --git a/Tests/GameFrameX.Tests/Online/OnlineMatchDomainMultiModeTests.cs b/Tests/GameFrameX.Tests/Online/OnlineMatchDomainMultiModeTests.cs new file mode 100644 index 000000000..7d4a712cd --- /dev/null +++ b/Tests/GameFrameX.Tests/Online/OnlineMatchDomainMultiModeTests.cs @@ -0,0 +1,203 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Scope; +using GameFrameX.Capability.Online.Match; +using GameFrameX.Capability.Online.Matchmaking; +using Xunit; + +namespace GameFrameX.Tests.Online +{ + /// + /// 匹配域多模式回归:多玩法注册时票据模式必须命中对应玩法的注册键(不再串写首个玩法的模式), + /// 以及 的精确命中 / 单玩法回落 / 多玩法未命三分支。 + /// + public class OnlineMatchDomainMultiModeTests + { + /// 区服标识。 + private const long ServerId = 100; + + /// 玩家一。 + private const long PlayerOne = 1001; + + /// 玩家二。 + private const long PlayerTwo = 1002; + + /// 第二玩法注册键(票据模式同值精确命中)。 + private const int SecondGameMode = 2; + + [Fact] + public async Task CreateFromTicket_MultiGameRegistered_MatchModeShouldFollowTicketMode() + { + var harness = await Harness.StartedMatchedAsync(SecondGameMode); + foreach (var playerId in new[] { PlayerOne, PlayerTwo }) + { + var entered = await harness.Domain.EnterAsync(harness.ScopeOf(playerId), harness.MatchId); + Assert.True(entered.IsSuccess, entered.Message); + } + + var actor = harness.Runtime.SnapshotActors().Single(); + var snapshot = actor.GetSnapshot(); + + // 票据模式 2 + 玩法 2 在册 → 对局 Mode 必须是玩法 2 的注册键(回归断言:旧实现恒写首个注册玩法的模式)。 + Assert.Equal(SecondGameMode, snapshot.Mode); + } + + [Fact] + public void ResolveGameForTicketMode_ExactRegistration_ShouldReturnThatGame() + { + var runtime = BuildRuntime(new StubMatchGame(1), new StubMatchGame(SecondGameMode)); + + var game = runtime.ResolveGameForTicketMode(SecondGameMode); + + Assert.NotNull(game); + Assert.Equal(SecondGameMode, game.Mode); + } + + [Fact] + public void ResolveGameForTicketMode_SingleGameRegistered_ShouldFallBackForAnyTicketMode() + { + var runtime = BuildRuntime(new StubMatchGame(1)); + + var game = runtime.ResolveGameForTicketMode(SecondGameMode); + + Assert.NotNull(game); + Assert.Equal(1, game.Mode); + } + + [Fact] + public void ResolveGameForTicketMode_MultiGameUnregisteredTicketMode_ShouldReturnNull() + { + var runtime = BuildRuntime(new StubMatchGame(1), new StubMatchGame(SecondGameMode)); + + Assert.Null(runtime.ResolveGameForTicketMode(9)); + } + + /// + /// 测试基座:双玩法(模式 1 + 指定模式)注册 + 票据域 + 运行时 + 域服务, + /// 两名玩家按指定票据模式入队并完成一次撮合(对局已创建)。 + /// + private sealed class Harness + { + public OnlineMatchTicketService Tickets { get; } + + public OnlineMatchmakerCoordinator Coordinator { get; } + + public OnlineMatchRuntime Runtime { get; } + + public OnlineMatchDomainService Domain { get; } + + private Harness(OnlineMatchTicketService tickets, OnlineMatchmakerCoordinator coordinator, OnlineMatchRuntime runtime, OnlineMatchDomainService domain) + { + Tickets = tickets; + Coordinator = coordinator; + Runtime = runtime; + Domain = domain; + } + + public OnlineScope ScopeOf(long playerId) + { + return new OnlineScope(ServerId, playerId); + } + + public static async Task StartedMatchedAsync(int ticketMode) + { + var publisher = new OnlineEventRecorder(); + var ticketStore = new InMemoryOnlineMatchTicketStore(); + var matchmakerOptions = new OnlineMatchmakerOptions(); + var tickets = new OnlineMatchTicketService(ticketStore, publisher, matchmakerOptions); + var coordinator = new OnlineMatchmakerCoordinator(ticketStore, tickets, publisher, matchmakerOptions); + var runtime = new OnlineMatchRuntime(new InMemoryOnlineMatchActorStore(), publisher, new OnlineMatchRuntimeOptions()); + var firstGame = new StubMatchGame(1); + var secondGame = new StubMatchGame(ticketMode); + runtime.RegisterGame(firstGame); + runtime.RegisterGame(secondGame); + var domain = new OnlineMatchDomainService(ticketStore, tickets, runtime, secondGame, new OnlineMatchRegistryOptions()); + var harness = new Harness(tickets, coordinator, runtime, domain); + + foreach (var playerId in new[] { PlayerOne, PlayerTwo }) + { + var enqueued = await domain.EnqueueAsync(harness.ScopeOf(playerId), ticketMode, 1000); + Assert.True(enqueued.IsSuccess, enqueued.Message); + } + + var matched = await coordinator.RunOnceAsync(); + Assert.True(matched.IsSuccess, matched.Message); + Assert.Single(matched.Data.AssignmentIds); + + var firstStatus = await domain.GetStatusAsync(harness.ScopeOf(PlayerOne)); + Assert.True(firstStatus.IsSuccess, firstStatus.Message); + Assert.True(firstStatus.Data.Matched); + harness.MatchId = firstStatus.Data.MatchId; + return harness; + } + + public long MatchId { get; private set; } + } + + + /// 构造指定注册键的最小玩法桩(纯裁决零状态:不开局、不出结果)。 + private sealed class StubMatchGame : IOnlineMatchGame + { + public StubMatchGame(int mode) + { + Mode = mode; + } + + public int Mode { get; } + + public int MinPlayers + { + get { return 2; } + } + + public int MaxPlayers + { + get { return 2; } + } + + public byte[] CreateInitialState(OnlineMatch match) + { + return new byte[0]; + } + + public OnlineMatchGameStepResult ApplyInput(OnlineMatch match, OnlineMatchMember member, OnlineMatchInput input) + { + return new OnlineMatchGameStepResult { Accepted = false }; + } + + public bool Advance(OnlineMatch match, long nowUnixMilliseconds, List emittedEvents) + { + return false; + } + + public bool IsCompleted(OnlineMatch match) + { + return false; + } + + public OnlineMatchBridgeGameView BuildBridgeView(long roomId, OnlineMatchSnapshot snapshot, IReadOnlyList events) + { + return null; + } + + public OnlineMatchResult BuildResult(OnlineMatch match) + { + return null; + } + } + + private static OnlineMatchRuntime BuildRuntime(params IOnlineMatchGame[] games) + { + var runtime = new OnlineMatchRuntime(new InMemoryOnlineMatchActorStore(), new OnlineEventRecorder(), new OnlineMatchRuntimeOptions()); + foreach (var game in games) + { + runtime.RegisterGame(game); + } + + return runtime; + } + } +} From 7a3d2c8ae88e558ed242a7d106a2f163926339a7 Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 17:45:53 +0800 Subject: [PATCH 09/13] =?UTF-8?q?doc(online-match):=20=E4=BF=AE=E6=AD=A3?= =?UTF-8?q?=E5=A4=B1=E6=95=88=E7=9A=84=E7=8E=A9=E6=B3=95=E6=B3=A8=E5=85=A5?= =?UTF-8?q?=20cref?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OnlineMatchOptions 无 Games 成员,XML 注释引用改为实际存在的 AddGame(PR #964 评审 Minor)。 --- .../OnlineMatchCapabilityModule.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs index ca3fea4f9..87b97b56e 100644 --- a/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs +++ b/Capability/GameFrameX.Capability.Online.Match/OnlineMatchCapabilityModule.cs @@ -49,7 +49,7 @@ namespace GameFrameX.Capability.Online.Match; /// 撮合成功通知订阅迁 Register 期机制事件总线(域服务在场才订阅并持有退订句柄): /// 订阅体只入队不做异步 I/O,通知由 match-assignment-notification-tick 任务异步推送(C407); /// 停用收口 = 关闭入队 + 退订 + 清空待处理 + 等待在途,返回后旧模块零通知。 -/// 玩法经 由宿主 Configure 回调注入(能力包零具体玩法; +/// 玩法经 由宿主 Configure 回调注入(能力包零具体玩法; /// 零玩法形态 = 运行时与结算管线照常、桥与域服务不装配——最小宿主语义)。 /// /// From 4a497bdb464878582a4c2bab7dd365b9ace8335a Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 17:45:53 +0800 Subject: [PATCH 10/13] =?UTF-8?q?fix(analyzers):=20GFX0023=20=E6=B6=88?= =?UTF-8?q?=E6=81=AF=E6=A8=A1=E6=9D=BF=E5=8E=BB=E9=99=A4=20HTML=20?= =?UTF-8?q?=E8=BD=AC=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 诊断消息按字面输出,< 会原样展示为乱码,改为 <(PR #964 评审 Minor)。 --- .../Analyzers/Architecture/CapabilityPackageLayeringAnalyzer.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityPackageLayeringAnalyzer.cs b/GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityPackageLayeringAnalyzer.cs index b4b3a8e3c..f9f7d9de1 100644 --- a/GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityPackageLayeringAnalyzer.cs +++ b/GameFrameX.Architecture.Analyzers/Analyzers/Architecture/CapabilityPackageLayeringAnalyzer.cs @@ -51,7 +51,7 @@ public sealed class CapabilityPackageLayeringAnalyzer : DiagnosticAnalyzer private static readonly DiagnosticDescriptor LayerMonotonicRule = new( "GFX0023", "包分层必须单调(同层禁互引)", - "程序集 '{0}'({1})引用了 '{2}'({3}):只准高层引低层(Ln→Lm, m<n)、同层禁互引;请把公共面下沉到更低层或调整包边界", + "程序集 '{0}'({1})引用了 '{2}'({3}):只准高层引低层(Ln→Lm, m Date: Mon, 2 Nov 2026 17:46:01 +0800 Subject: [PATCH 11/13] =?UTF-8?q?fix(golden-path):=20=E9=87=91=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E9=80=82=E9=85=8D=E5=8C=85=E7=BB=93=E6=9E=84=E6=94=B6?= =?UTF-8?q?=E6=95=9B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit main 侧 C460 金路径测试在拆包后需要适配:启用清单补必选依赖 online-leaderboard;Hotfix 金链经 OnlineMatchOptions.AddGame 注入 RPS 夹具玩法并补对应工程引用(能力包已零具体玩法);顺带废止单键 化后不再产生的跨租户/跨应用守卫用例(保留跨服 3004 断言)。 --- .../GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj | 3 +++ Tests/GameFrameX.Hotfix.Tests/GoldenPathBridgeChainTests.cs | 4 +++- Tests/GameFrameX.Tests/Online/GoldenPathDefaultOnTests.cs | 2 +- .../Online/OnlineAdminApiDispatcherTests.cs | 6 ++---- 4 files changed, 9 insertions(+), 6 deletions(-) diff --git a/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj b/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj index b6bc776f6..8e5c856d5 100644 --- a/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj +++ b/Tests/GameFrameX.Hotfix.Tests/GameFrameX.Hotfix.Tests.csproj @@ -29,6 +29,9 @@ + + + diff --git a/Tests/GameFrameX.Hotfix.Tests/GoldenPathBridgeChainTests.cs b/Tests/GameFrameX.Hotfix.Tests/GoldenPathBridgeChainTests.cs index 05c7131a3..31044e8fb 100644 --- a/Tests/GameFrameX.Hotfix.Tests/GoldenPathBridgeChainTests.cs +++ b/Tests/GameFrameX.Hotfix.Tests/GoldenPathBridgeChainTests.cs @@ -35,6 +35,7 @@ using GameFrameX.Capability.Hosting.Abstractions; using GameFrameX.Capability.Hosting.Core; using GameFrameX.Capability.Online.Abstractions; +using GameFrameX.Capability.Online.Match; using GameFrameX.Capability.Online.Operations.HotfixRollback; using GameFrameX.Capability.Online.Abstractions.Contracts; using GameFrameX.Capability.Online.Competition.Leaderboard; @@ -86,10 +87,11 @@ public async Task GoldenPath_ZeroSettings_FriendBridge_MatchBridge_RpsMatch_Proj var options = new CapabilityCompositionOptions(section, new HotfixBridgeAssemblyLog()) { HostOptions = new CapabilityHostOptions { ServerId = ServerId, SchedulerIntervalMilliseconds = 3600000, }, - Filter = new CapabilityAssemblyFilter(new[] { "online-foundation", "online-social", "online-matchmaking", "online-match", "online-assets", "online-competition" }), + Filter = new CapabilityAssemblyFilter(new[] { "online-foundation", "online-social", "online-matchmaking", "online-match", "online-assets", "online-leaderboard", "online-competition" }), }; options.Override(new EmptyPlayerDirectoryStub()); options.Override(new NoopHotfixRollbackExecutorStub()); + options.Configure(match => match.AddGame(new OnlineRockPaperScissorsGame())); runtime = CapabilityComposition.Compose(new OnlineCapabilityFamily(), options); await runtime.Host.StartAsync(); diff --git a/Tests/GameFrameX.Tests/Online/GoldenPathDefaultOnTests.cs b/Tests/GameFrameX.Tests/Online/GoldenPathDefaultOnTests.cs index 12d220169..30bf3929a 100644 --- a/Tests/GameFrameX.Tests/Online/GoldenPathDefaultOnTests.cs +++ b/Tests/GameFrameX.Tests/Online/GoldenPathDefaultOnTests.cs @@ -126,7 +126,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => 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.Filter = new CapabilityAssemblyFilter(new[] { "online-foundation", "online-social", "online-matchmaking", "online-match", "online-assets", "online-leaderboard", "online-competition" }); options.HostOptions.SchedulerIntervalMilliseconds = 3600000; }); } diff --git a/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs index 823d972e3..190dc0c49 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs @@ -190,14 +190,12 @@ await WithDispatcherAsync(async dispatcher => } /// - /// 验证跨租户 / 跨应用 / 跨区服分别返回 3002 / 3003 / 3004。 + /// 验证跨区服返回 3004(单键化 D4 后租户位 / App 位不复存在,跨租户 / 跨应用用例废止)。 /// /// 请求体。 /// 期望业务码。 [Theory] - [InlineData("{\"TenantId\":2,\"AppId\":1,\"ServerId\":1001}", OnlineErrorCode.CrossTenantDenied)] - [InlineData("{\"TenantId\":1,\"AppId\":2,\"ServerId\":1001}", OnlineErrorCode.CrossAppDenied)] - [InlineData("{\"TenantId\":1,\"AppId\":1,\"ServerId\":2002}", OnlineErrorCode.ServerScopeDenied)] + [InlineData("{\"ServerId\":2002}", OnlineErrorCode.ServerScopeDenied)] public async Task Dispatch_ScopeMismatch_ShouldReturnGuardCode(string body, OnlineErrorCode expectedCode) { await WithDispatcherAsync(async dispatcher => From 591236390ea796182d599d3925590ced70e92fd1 Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 17:46:01 +0800 Subject: [PATCH 12/13] =?UTF-8?q?build(docker):=20=E8=A1=A5=E9=BD=90=20res?= =?UTF-8?q?tore=20=E5=B1=82=E6=96=B0=E5=8C=85=20COPY?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Launcher 新引用 Online.Leaderboard 与 Apps.Sample,Dockerfile restore 层补两个 csproj COPY,否则 restore 阶段解析失败 (PR #964 评审 Major)。 --- Dockerfile | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Dockerfile b/Dockerfile index 05ca3bfcc..52da75095 100644 --- a/Dockerfile +++ b/Dockerfile @@ -14,6 +14,7 @@ COPY Capability/GameFrameX.Capability.Hosting.Core/GameFrameX.Capability.Hosting COPY Capability/GameFrameX.Capability.Online.Abstractions/GameFrameX.Capability.Online.Abstractions.csproj Capability/GameFrameX.Capability.Online.Abstractions/ COPY Capability/GameFrameX.Capability.Online.Assets/GameFrameX.Capability.Online.Assets.csproj Capability/GameFrameX.Capability.Online.Assets/ COPY Capability/GameFrameX.Capability.Online.Competition/GameFrameX.Capability.Online.Competition.csproj Capability/GameFrameX.Capability.Online.Competition/ +COPY Capability/GameFrameX.Capability.Online.Leaderboard/GameFrameX.Capability.Online.Leaderboard.csproj Capability/GameFrameX.Capability.Online.Leaderboard/ COPY Capability/GameFrameX.Capability.Online.Foundation/GameFrameX.Capability.Online.Foundation.csproj Capability/GameFrameX.Capability.Online.Foundation/ COPY Capability/GameFrameX.Capability.Online.Match/GameFrameX.Capability.Online.Match.csproj Capability/GameFrameX.Capability.Online.Match/ COPY Capability/GameFrameX.Capability.Online.Matchmaking/GameFrameX.Capability.Online.Matchmaking.csproj Capability/GameFrameX.Capability.Online.Matchmaking/ @@ -21,6 +22,7 @@ COPY Capability/GameFrameX.Capability.Online.Operations/GameFrameX.Capability.On COPY Capability/GameFrameX.Capability.Online.Persistence/GameFrameX.Capability.Online.Persistence.csproj Capability/GameFrameX.Capability.Online.Persistence/ COPY Capability/GameFrameX.Capability.Online.Social/GameFrameX.Capability.Online.Social.csproj Capability/GameFrameX.Capability.Online.Social/ COPY GameFrameX.Apps/GameFrameX.Apps.csproj GameFrameX.Apps/ +COPY GameFrameX.Apps.Sample/GameFrameX.Apps.Sample.csproj GameFrameX.Apps.Sample/ COPY GameFrameX.Architecture.Analyzers/GameFrameX.Architecture.Analyzers.csproj GameFrameX.Architecture.Analyzers/ COPY GameFrameX.Client/GameFrameX.Client.csproj GameFrameX.Client/ COPY GameFrameX.Config/GameFrameX.Config.csproj GameFrameX.Config/ From 3b2c4788bc0d8d15c89b8a1623bf8cdb8afa9026 Mon Sep 17 00:00:00 2001 From: Blank Date: Mon, 2 Nov 2026 17:46:01 +0800 Subject: [PATCH 13/13] =?UTF-8?q?doc(legacy):=20=E6=97=A7=E9=93=BE?= =?UTF-8?q?=E8=BF=81=E7=A7=BB=E5=AD=98=E6=A1=A3=E5=AF=B9=E9=BD=90=E5=8D=95?= =?UTF-8?q?=E9=94=AE=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 存档内容取 D4 单键化后的终版(MigrateAsync 只留 ServerId), 避免存档停留在已废止的三元组签名。 --- scripts/legacy/OnlineFriendLegacyMigration.cs | 34 +++++++------------ 1 file changed, 12 insertions(+), 22 deletions(-) diff --git a/scripts/legacy/OnlineFriendLegacyMigration.cs b/scripts/legacy/OnlineFriendLegacyMigration.cs index f68a7693f..8dd19c682 100644 --- a/scripts/legacy/OnlineFriendLegacyMigration.cs +++ b/scripts/legacy/OnlineFriendLegacyMigration.cs @@ -59,20 +59,18 @@ public static class OnlineFriendLegacyMigration /// 执行旧好友数据迁移(社交能力模块在激活期、好友域桥发布后调用)。 /// /// 好友域服务(真实写路径的唯一属主)。 - /// 租户标识(宿主 OnlineScope 三元组)。 - /// App 标识。 /// 区服标识。 /// 取消令牌。 /// 迁移汇总(已建立关系数 / 待答申请数 / 失败数)。 - public static async Task<(int Established, int Pending, int Failed)> MigrateAsync(OnlineFriendService friends, long tenantId, long appId, long serverId, CancellationToken cancellationToken = default) + public static async Task<(int Established, int Pending, int Failed)> MigrateAsync(OnlineFriendService friends, long serverId, CancellationToken cancellationToken = default) { var domain = new OnlineFriendDomainFace(friends); // ① 域 120 旧链:FriendRelationState Status=0 → 已建立关系(Establish = 申请 + 立即接受,幂等收敛)。 - var (established, relationFailed) = await MigrateEstablishedRelationsAsync(domain, tenantId, appId, serverId, cancellationToken).ConfigureAwait(false); + var (established, relationFailed) = await MigrateEstablishedRelationsAsync(domain, serverId, cancellationToken).ConfigureAwait(false); // ② 域 660 旧链:FriendState 档案 Outgoing → 待答申请(对已建立的对幂等无效果)。 - var (pending, profileFailed) = await MigratePendingRequestsAsync(domain, tenantId, appId, serverId, cancellationToken).ConfigureAwait(false); + var (pending, profileFailed) = await MigratePendingRequestsAsync(domain, serverId, cancellationToken).ConfigureAwait(false); var failed = relationFailed + profileFailed; return (established, pending, failed); @@ -83,12 +81,10 @@ public static class OnlineFriendLegacyMigration /// (Establish = 申请 + 立即接受,幂等收敛);单条失败计数并继续(containment)。 /// /// Online 好友域契约面。 - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 取消令牌。 /// (已建立关系数,失败数)。 - private static async Task<(int Established, int Failed)> MigrateEstablishedRelationsAsync(OnlineFriendDomainFace domain, long tenantId, long appId, long serverId, CancellationToken cancellationToken) + private static async Task<(int Established, int Failed)> MigrateEstablishedRelationsAsync(OnlineFriendDomainFace domain, long serverId, CancellationToken cancellationToken) { var established = 0; var failed = 0; @@ -102,7 +98,7 @@ public static class OnlineFriendLegacyMigration continue; } - var result = await domain.EstablishAsync(PlayerScope(tenantId, appId, serverId, low), high, cancellationToken).ConfigureAwait(false); + var result = await domain.EstablishAsync(PlayerScope(serverId, low), high, cancellationToken).ConfigureAwait(false); if (result.IsSuccess && result.Data.After == OnlineFriendRelationKind.Friend) { established++; @@ -121,12 +117,10 @@ public static class OnlineFriendLegacyMigration /// (对已建立的对幂等无效果)。 /// /// Online 好友域契约面。 - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 取消令牌。 /// (待答申请数,失败数)。 - private static async Task<(int Pending, int Failed)> MigratePendingRequestsAsync(OnlineFriendDomainFace domain, long tenantId, long appId, long serverId, CancellationToken cancellationToken) + private static async Task<(int Pending, int Failed)> MigratePendingRequestsAsync(OnlineFriendDomainFace domain, long serverId, CancellationToken cancellationToken) { var pending = 0; var failed = 0; @@ -145,7 +139,7 @@ public static class OnlineFriendLegacyMigration continue; } - var (entryPending, entryFailed) = await MigrateOutgoingRequestsAsync(domain, tenantId, appId, serverId, profile, cancellationToken).ConfigureAwait(false); + var (entryPending, entryFailed) = await MigrateOutgoingRequestsAsync(domain, serverId, profile, cancellationToken).ConfigureAwait(false); pending += entryPending; failed += entryFailed; } @@ -159,13 +153,11 @@ public static class OnlineFriendLegacyMigration /// 单条失败计数并继续(containment)。 /// /// Online 好友域契约面。 - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 旧 660 好友档案。 /// 取消令牌。 /// (待答申请数,失败数)。 - private static async Task<(int Pending, int Failed)> MigrateOutgoingRequestsAsync(OnlineFriendDomainFace domain, long tenantId, long appId, long serverId, FriendProfileState profile, CancellationToken cancellationToken) + private static async Task<(int Pending, int Failed)> MigrateOutgoingRequestsAsync(OnlineFriendDomainFace domain, long serverId, FriendProfileState profile, CancellationToken cancellationToken) { var pending = 0; var failed = 0; @@ -176,7 +168,7 @@ public static class OnlineFriendLegacyMigration continue; } - var result = await domain.RequestAsync(PlayerScope(tenantId, appId, serverId, profile.PlayerId), targetPlayerId, cancellationToken).ConfigureAwait(false); + var result = await domain.RequestAsync(PlayerScope(serverId, profile.PlayerId), targetPlayerId, cancellationToken).ConfigureAwait(false); if (result.IsSuccess) { pending++; @@ -191,15 +183,13 @@ public static class OnlineFriendLegacyMigration } /// - /// 构造玩家作用域(三元组取宿主 OnlineScope 值,玩家位为迁移主体)。 + /// 构造玩家作用域(区服键取宿主 OnlineScope 值,玩家位为迁移主体)。 /// - /// 租户标识。 - /// App 标识。 /// 区服标识。 /// 玩家标识。 /// 生效作用域。 - private static OnlineScope PlayerScope(long tenantId, long appId, long serverId, long playerId) + private static OnlineScope PlayerScope(long serverId, long playerId) { - return new OnlineScope(tenantId, appId, serverId, playerId); + return new OnlineScope(serverId, playerId); } }