diff --git a/Capability/GameFrameX.Capability.Online.Persistence/GameFrameX.Capability.Online.Persistence.csproj b/Capability/GameFrameX.Capability.Online.Persistence/GameFrameX.Capability.Online.Persistence.csproj index b88ea5b51..03263903a 100644 --- a/Capability/GameFrameX.Capability.Online.Persistence/GameFrameX.Capability.Online.Persistence.csproj +++ b/Capability/GameFrameX.Capability.Online.Persistence/GameFrameX.Capability.Online.Persistence.csproj @@ -19,6 +19,7 @@ + diff --git a/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/GameDbOnlineServerCalendarStore.cs b/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/GameDbOnlineServerCalendarStore.cs new file mode 100644 index 000000000..a1f176ae2 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/GameDbOnlineServerCalendarStore.cs @@ -0,0 +1,182 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 legal rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any disputes or liabilities arising from secondary development based on this project +// 本项目组织与贡献者概不承担。 +// shall be borne 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.Persistence; + +using System; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.ServerLifecycle; +using GameFrameX.DataBase; + +/// +/// 开服锚点存储 GameDb 持久化实现( 行;跨进程 / 跨运行生命周期可回读—— +/// CLI 一次进程登记锚点、另一次进程合服执行的前置;部署侧亦可作为在线宿主的锚点存储绑定)。 +/// +/// 语义与内存实现一致:登记幂等(已登记返回既有锚点,不改写首登开服时刻);标记归并幂等 +/// (同目标重复标记 = no-op);未登记 / 已合入其他目标的标记请求抛 +///(与 同口径,合服参与者的前置校验依赖该失败面)。 +/// 标记归并走 CAS 条件写(读-改-写窗口不覆盖并发更新)。 +/// +/// +public sealed class GameDbOnlineServerCalendarStore : IOnlineServerCalendarStore +{ + /// + /// 行 Id 共享序列名(与既有持久化行同口径,按类型隔离计数)。 + /// + private const string RowIdSequence = "row-id"; + + /// + /// 单行 CAS 条件写失配后的最大重试次数(重读最新档后再试)。 + /// + private const int MarkMergedMaxAttempts = 3; + + /// + /// 初始化存储(GameDb 须已由宿主初始化)。 + /// + public GameDbOnlineServerCalendarStore() + { + } + + /// + public async Task<(OnlineServerAnchor Anchor, bool Registered)> TryRegisterAsync(OnlineServerAnchor anchor, CancellationToken cancellationToken = default) + { + if (anchor == null) + { + throw new ArgumentNullException(nameof(anchor)); + } + + if (anchor.ServerId <= 0) + { + throw new ArgumentOutOfRangeException(nameof(anchor), "ServerId must be positive."); + } + + if (anchor.OpenedAtUnixMilliseconds <= 0) + { + throw new ArgumentOutOfRangeException(nameof(anchor), "OpenedAtUnixMilliseconds must be positive."); + } + + var existing = await FindStateAsync(anchor.ServerId, cancellationToken).ConfigureAwait(false); + if (existing != null) + { + return (ToAnchor(existing), false); + } + + var state = new OnlineServerAnchorState + { + ServerId = anchor.ServerId, + OpenedAtUnixMilliseconds = anchor.OpenedAtUnixMilliseconds, + RegisteredAtUnixMilliseconds = anchor.RegisteredAtUnixMilliseconds > 0 ? anchor.RegisteredAtUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + MergedIntoServerId = 0, + }; + state.Id = await GameDb.NextSequenceAsync(RowIdSequence, cancellationToken).ConfigureAwait(false); + if (await GameDb.TryAddUniqueAsync(state, candidate => candidate.ServerId == anchor.ServerId, cancellationToken).ConfigureAwait(false)) + { + return (ToAnchor(state), true); + } + + // 唯一插入冲突(并发窗口落者):回读胜者行——登记幂等,保留首登开服时刻。 + var winner = await FindStateAsync(anchor.ServerId, cancellationToken).ConfigureAwait(false); + if (winner == null) + { + throw new InvalidOperationException("Server anchor unique-insert conflict but no existing row found: " + anchor.ServerId); + } + + return (ToAnchor(winner), false); + } + + /// + public async Task FindAsync(long serverId, CancellationToken cancellationToken = default) + { + var state = await FindStateAsync(serverId, cancellationToken).ConfigureAwait(false); + return state == null ? null : ToAnchor(state); + } + + /// + public async Task MarkMergedAsync(long serverId, long targetServerId, CancellationToken cancellationToken = default) + { + if (targetServerId <= 0) + { + throw new ArgumentOutOfRangeException(nameof(targetServerId), "TargetServerId must be positive."); + } + + for (var attempt = 0; attempt < MarkMergedMaxAttempts; attempt++) + { + var state = await FindStateAsync(serverId, cancellationToken).ConfigureAwait(false); + if (state == null) + { + throw new InvalidOperationException("Server anchor not registered: " + serverId); + } + + if (state.MergedIntoServerId == targetServerId) + { + return; + } + + if (state.MergedIntoServerId != 0) + { + throw new InvalidOperationException("Server " + serverId + " already merged into " + state.MergedIntoServerId + "; cannot retarget to " + targetServerId + "."); + } + + state.MergedIntoServerId = targetServerId; + var written = state.RowVersion == null + ? await GameDb.UpdateIfRowVersionIsNullAsync(state.Id, state, cancellationToken).ConfigureAwait(false) + : await GameDb.UpdateIfRowVersionAsync(state.Id, state.RowVersion.Value, state, cancellationToken).ConfigureAwait(false); + if (written) + { + return; + } + } + + // 持续 CAS 失配(并发写者高频竞争):按已合入他服的失败面收口,调用方重试即重新校验。 + throw new InvalidOperationException("Server anchor " + serverId + " mark-merged lost too many row-version races; retry the merge."); + } + + /// + /// 按 ServerId 查行(不存在返回 null)。 + /// + private static Task FindStateAsync(long serverId, CancellationToken cancellationToken) + { + return GameDb.FindAsync(state => state.ServerId == serverId, isCreateIfNotExists: false, cancellationToken: cancellationToken); + } + + /// + /// 行 → 锚点实体。 + /// + private static OnlineServerAnchor ToAnchor(OnlineServerAnchorState state) + { + return new OnlineServerAnchor + { + ServerId = state.ServerId, + OpenedAtUnixMilliseconds = state.OpenedAtUnixMilliseconds, + RegisteredAtUnixMilliseconds = state.RegisteredAtUnixMilliseconds, + MergedIntoServerId = state.MergedIntoServerId, + }; + } +} diff --git a/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/GameDbOnlineServerMergeRowRewriter.cs b/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/GameDbOnlineServerMergeRowRewriter.cs new file mode 100644 index 000000000..9c4304ea9 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/GameDbOnlineServerMergeRowRewriter.cs @@ -0,0 +1,266 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.Persistence; + +using System; +using System.Collections.Generic; +using System.Linq.Expressions; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Persistence.Assets; +using GameFrameX.Capability.Online.ServerLifecycle.ServerMerge; +using GameFrameX.DataBase; + +/// +/// 区服域行键重写 GameDb 适配(资产归属列 HomeServerId 单列重写:账本行 OnlineLedgerEntryState + +/// 交易行 OnlineAssetTransactionRowState;行键本身为全局域玩家键(C462),键零改动、只重写归属快照列)。 +/// +/// 红线:① 只重写区服维度快照列,不触碰任何全局域行键(好友/身份/玩家存储/钱包/库存——合服零操作); +/// ② 幂等可重入——按 HomeServerId == 源服 过滤重写,重跑批次为空;③ dry-run 只统计不落写 +/// (SQL COUNT,零行物化);④ 读取与写入同界——键集分页按 逐页读取逐页重写 +/// (每页即读即写,不整表物化);⑤ 单行落写为 CAS 条件写(仅当行版本一致才写入),读取后发生并发写 +/// 不会整档回写覆盖,失配有界重读重试。 +/// +/// +/// 运维语义:合服为离线管理操作,执行窗口内源服应停写(编排由运营台负责);CAS 条件写是并发防御底线 +/// 而非许可——窗口内残留并发写会触发失配重试;对账明细区分 -skipped(CAS 超限仍滞留源服, +/// 同一计划重跑走幂等回放不再重写,补救 = 停写后人工修复或换源集合重执行)与 -moved(被并发方 +/// 迁出 / 删除,非本次重写责任面)。 +/// +/// +public sealed class GameDbOnlineServerMergeRowRewriter : IOnlineServerMergeRowRewriter +{ + /// + /// 账本行类别名(报告明细键)。 + /// + public const string LedgerCategory = "ledger-entries"; + + /// + /// 交易行类别名(报告明细键)。 + /// + public const string TransactionCategory = "asset-transactions"; + + /// + /// 单行 CAS 条件写失配后的最大重试次数(重读最新档后再试;超限跳过该行,如实少计)。 + /// + public const int RowRewriteMaxAttempts = 3; + + /// + public async Task> CountServerDomainRowsAsync(IReadOnlyList sourceServerIds, CancellationToken cancellationToken) + { + var counts = new Dictionary(); + foreach (var (category, count) in await CountCoreAsync(sourceServerIds, cancellationToken).ConfigureAwait(false)) + { + counts[category] = count; + } + + return counts; + } + + /// + public async Task> RewriteServerDomainRowsAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, int batchSize, CancellationToken cancellationToken) + { + if (sourceServerIds == null) + { + throw new ArgumentNullException(nameof(sourceServerIds)); + } + + if (targetServerId <= 0) + { + throw new ArgumentOutOfRangeException(nameof(targetServerId), "TargetServerId must be positive."); + } + + if (batchSize <= 0) + { + throw new ArgumentOutOfRangeException(nameof(batchSize), "BatchSize must be positive."); + } + + var counts = new Dictionary(); + foreach (var sourceServerId in sourceServerIds) + { + // dry-run 零物化:CountAsync 走 SQL COUNT,不反序列化任何行。 + if (dryRun) + { + counts[LedgerCategory] = counts.GetValueOrDefault(LedgerCategory) + await GameDb.CountAsync(state => state.HomeServerId == sourceServerId, cancellationToken).ConfigureAwait(false); + counts[TransactionCategory] = counts.GetValueOrDefault(TransactionCategory) + await GameDb.CountAsync(state => state.HomeServerId == sourceServerId, cancellationToken).ConfigureAwait(false); + continue; + } + + var ledgerOutcome = await RewriteRowsAsync(sourceServerId, batchSize, cursor => state => state.HomeServerId == sourceServerId && state.Id > cursor, state => state.HomeServerId, state => state.HomeServerId = targetServerId, cancellationToken).ConfigureAwait(false); + counts[LedgerCategory] = counts.GetValueOrDefault(LedgerCategory) + ledgerOutcome.Rewritten; + AddReconciliationDetails(counts, LedgerCategory, ledgerOutcome.Skipped, ledgerOutcome.Moved); + var transactionOutcome = await RewriteRowsAsync(sourceServerId, batchSize, cursor => state => state.HomeServerId == sourceServerId && state.Id > cursor, state => state.HomeServerId, state => state.HomeServerId = targetServerId, cancellationToken).ConfigureAwait(false); + counts[TransactionCategory] = counts.GetValueOrDefault(TransactionCategory) + transactionOutcome.Rewritten; + AddReconciliationDetails(counts, TransactionCategory, transactionOutcome.Skipped, transactionOutcome.Moved); + } + + return counts; + } + + /// + /// 统计各区服域类别待重写行数(SQL COUNT,零行物化)。 + /// + private static async Task> CountCoreAsync(IReadOnlyList sourceServerIds, CancellationToken cancellationToken) + { + var ledgerCount = 0L; + var transactionCount = 0L; + foreach (var sourceServerId in sourceServerIds) + { + ledgerCount += await GameDb.CountAsync(state => state.HomeServerId == sourceServerId, cancellationToken).ConfigureAwait(false); + transactionCount += await GameDb.CountAsync(state => state.HomeServerId == sourceServerId, cancellationToken).ConfigureAwait(false); + } + + return new List<(string, long)> { (LedgerCategory, ledgerCount), (TransactionCategory, transactionCount) }; + } + + /// + /// 键集分页重写归属列(单列 CAS 条件写)。 + /// + /// 分页推进不变式:每页按 Id 升序读取(过滤 归属列 == 源服 && Id > 游标, + /// 页大小 = ),读后立即重写整页——已重写行离开过滤集,但游标只按页内 + /// 最大 Id 严格递增推进,重写与推进互不干扰;页空即终止。中断后重跑从未重写行续写(幂等可重入)。 + /// + /// + private static async Task<(long Rewritten, long Skipped, long Moved)> RewriteRowsAsync(long sourceServerId, int batchSize, Func>> buildPageFilter, Func getHomeServerId, Action setHomeServerId, CancellationToken cancellationToken) where TState : BaseCacheState, new() + { + long rewritten = 0; + long skipped = 0; + long moved = 0; + long cursor = 0; + while (true) + { + var page = await GameDb.FindPageAsync( + buildPageFilter(cursor), + state => state.Id, + false, + 0, + batchSize, + cancellationToken).ConfigureAwait(false); + if (page.Items.Count == 0) + { + break; + } + + foreach (var row in page.Items) + { + var outcome = await TryRewriteRowAsync(row, sourceServerId, getHomeServerId, setHomeServerId, cancellationToken).ConfigureAwait(false); + if (outcome == RowRewriteOutcome.Rewritten) + { + rewritten++; + } + else if (outcome == RowRewriteOutcome.CasExhausted) + { + skipped++; + } + else + { + moved++; + } + } + + cursor = page.Items[page.Items.Count - 1].Id; + } + + return (rewritten, skipped, moved); + } + + /// + /// 追加对账明细键(仅非零时出现):<category>-skipped = CAS 失配超限仍滞留源服的行; + /// <category>-moved = 读取后被并发方迁出 / 删除、已不在源服的行(非本次重写责任面)。 + /// + private static void AddReconciliationDetails(Dictionary counts, string category, long skipped, long moved) + { + if (skipped > 0) + { + counts[category + "-skipped"] = counts.GetValueOrDefault(category + "-skipped") + skipped; + } + + if (moved > 0) + { + counts[category + "-moved"] = counts.GetValueOrDefault(category + "-moved") + moved; + } + } + + /// + /// 单行重写结局。 + /// + private enum RowRewriteOutcome + { + /// + /// 已条件写成功(归属列已重写为目标服)。 + /// + Rewritten, + + /// + /// CAS 失配超限——行仍属源服,归属列停留未改(对账须计入 skipped)。 + /// + CasExhausted, + + /// + /// 读取后被并发方迁出源服或删除(不属于本次重写责任面)。 + /// + LeftSource, + } + + /// + /// 单行归属列 CAS 条件写:仅当存量行版本与读取时一致才写入(消除读-改-写整档回写覆盖并发更新的窗口)。 + /// + /// 版本失配 = 读取后发生过并发写:重读最新档,仍属源服则以最新档重试(保留并发方的字段更新), + /// 已离开源服(并发迁移 / 删除)按 LeftSource 记入 moved 明细; + /// 次仍失配按 CasExhausted 记入 skipped 明细(行仍滞留源服)。遗留行版本缺失(null)走 + /// UpdateIfRowVersionIsNullAsync 存量回填原语(同为条件写)。 + /// + /// + private static async Task TryRewriteRowAsync(TState row, long sourceServerId, Func getHomeServerId, Action setHomeServerId, CancellationToken cancellationToken) where TState : BaseCacheState, new() + { + var current = row; + for (var attempt = 0; attempt < RowRewriteMaxAttempts; attempt++) + { + setHomeServerId(current); + var written = current.RowVersion == null + ? await GameDb.UpdateIfRowVersionIsNullAsync(current.Id, current, cancellationToken).ConfigureAwait(false) + : await GameDb.UpdateIfRowVersionAsync(current.Id, current.RowVersion.Value, current, cancellationToken).ConfigureAwait(false); + if (written) + { + return RowRewriteOutcome.Rewritten; + } + + var fresh = await GameDb.FindAsync(current.Id, filter: null, isCreateIfNotExists: false, cancellationToken: cancellationToken).ConfigureAwait(false); + if (fresh == null || getHomeServerId(fresh) != sourceServerId) + { + return RowRewriteOutcome.LeftSource; + } + + current = fresh; + } + + return RowRewriteOutcome.CasExhausted; + } +} diff --git a/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/GameDbOnlineServerMergeStore.cs b/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/GameDbOnlineServerMergeStore.cs new file mode 100644 index 000000000..9a033f0bb --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/GameDbOnlineServerMergeStore.cs @@ -0,0 +1,278 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 legal rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any disputes or liabilities arising from secondary development based on this project +// 本项目组织与贡献者概不承担。 +// shall be borne 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.Persistence; + +using System; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.ServerLifecycle.ServerMerge; +using GameFrameX.DataBase; + +/// +/// 归并计划存储 GameDb 持久化实现( 单行整存整取: +/// 计划幂等登记 + dry-run 报告留存 + 执行落定 + 事件发布记账,跨进程 / 跨运行生命周期可回读—— +/// CLI 一次进程 dry-run、另一次进程 --execute 的前置)。 +/// +/// 幂等语义:建行走 TryAddUniqueAsync(PlanId 全表唯一索引列,并发首插唯一胜出,落者回读胜者行); +/// 报告落定 / 事件记账为单字段变更的 CAS 条件写(失配在最新行上重放本字段变更,不整行盲覆盖)。 +/// +/// +public sealed class GameDbOnlineServerMergeStore : IOnlineServerMergeStore +{ + /// + /// 行 Id 共享序列名(与既有持久化行同口径,按类型隔离计数)。 + /// + private const string RowIdSequence = "row-id"; + + /// + /// 报告 / 记账字段变更的 CAS 失配最大重试次数(在最新行上重放本字段变更)。 + /// + private const int MarkMutationMaxAttempts = 3; + + /// + /// 初始化存储(GameDb 须已由宿主初始化)。 + /// + public GameDbOnlineServerMergeStore() + { + } + + /// + public async Task<(OnlineServerMergePlan Plan, bool Planned)> TryPlanAsync(OnlineServerMergePlan plan, CancellationToken cancellationToken = default) + { + if (plan == null) + { + throw new ArgumentNullException(nameof(plan)); + } + + var planId = plan.BuildPlanId(); + var existing = await FindStateAsync(planId, cancellationToken).ConfigureAwait(false); + if (existing != null) + { + return (DeserializePlan(existing), false); + } + + var state = new OnlineServerMergePlanState + { + PlanId = planId, + PlanJson = JsonSerializer.Serialize(plan), + }; + state.Id = await GameDb.NextSequenceAsync(RowIdSequence, cancellationToken).ConfigureAwait(false); + if (await GameDb.TryAddUniqueAsync(state, candidate => candidate.PlanId == planId, cancellationToken).ConfigureAwait(false)) + { + return (plan, true); + } + + // 唯一插入冲突(并发窗口落者):回读胜者行,返回既有计划。 + var winner = await FindStateAsync(planId, cancellationToken).ConfigureAwait(false); + if (winner == null) + { + throw new InvalidOperationException("Server merge plan unique-insert conflict but no existing row found: " + planId); + } + + return (DeserializePlan(winner), false); + } + + /// + public async Task FindPlanAsync(string planId, CancellationToken cancellationToken = default) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + var state = await FindStateAsync(planId, cancellationToken).ConfigureAwait(false); + return state == null ? null : DeserializePlan(state); + } + + /// + public Task RecordDryRunReportAsync(string planId, OnlineServerMergeReport report, CancellationToken cancellationToken = default) + { + if (report == null) + { + throw new ArgumentNullException(nameof(report)); + } + + return MutateStateAsync(planId, nameof(RecordDryRunReportAsync), state => + { + state.DryRunReportJson = JsonSerializer.Serialize(report); + return true; + }, cancellationToken); + } + + /// + public async Task FindDryRunReportAsync(string planId, CancellationToken cancellationToken = default) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + var state = await FindStateAsync(planId, cancellationToken).ConfigureAwait(false); + return state != null && HasPayload(state.DryRunReportJson) ? DeserializeReport(state.DryRunReportJson) : null; + } + + /// + public async Task FindExecutedReportAsync(string planId, CancellationToken cancellationToken = default) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + var state = await FindStateAsync(planId, cancellationToken).ConfigureAwait(false); + return state != null && HasPayload(state.ExecutedReportJson) ? DeserializeReport(state.ExecutedReportJson) : null; + } + + /// + public Task MarkExecutedAsync(string planId, OnlineServerMergeReport report, CancellationToken cancellationToken = default) + { + if (report == null) + { + throw new ArgumentNullException(nameof(report)); + } + + return MutateStateAsync(planId, nameof(MarkExecutedAsync), state => + { + state.ExecutedReportJson = JsonSerializer.Serialize(report); + return true; + }, cancellationToken); + } + + /// + public async Task IsMergedEventPublishedAsync(string planId, CancellationToken cancellationToken = default) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + var state = await FindStateAsync(planId, cancellationToken).ConfigureAwait(false); + return state != null && state.MergedEventPublishedAtUnixMilliseconds > 0; + } + + /// + public Task MarkMergedEventPublishedAsync(string planId, CancellationToken cancellationToken = default) + { + return MutateStateAsync( + planId, + nameof(MarkMergedEventPublishedAsync), + state => + { + if (state.MergedEventPublishedAtUnixMilliseconds != 0) + { + return false; + } + + state.MergedEventPublishedAtUnixMilliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + return true; + }, + cancellationToken); + } + + /// + /// 读-改-写单行载荷(CAS 条件写 + 失配重读重试,避免并发操作者互相整行覆盖;语义 = 在最新行上重放本字段的变更)。 + /// + /// 变更回调返回 false = 幂等无变化,直接跳过(不产生冗余条件写)。 + /// + /// + private static async Task MutateStateAsync(string planId, string operationName, Func applyMutation, CancellationToken cancellationToken) + { + for (var attempt = 0; attempt < MarkMutationMaxAttempts; attempt++) + { + var state = await RequireStateAsync(planId, operationName, cancellationToken).ConfigureAwait(false); + if (!applyMutation(state)) + { + return; + } + + var written = state.RowVersion == null + ? await GameDb.UpdateIfRowVersionIsNullAsync(state.Id, state, cancellationToken).ConfigureAwait(false) + : await GameDb.UpdateIfRowVersionAsync(state.Id, state.RowVersion.Value, state, cancellationToken).ConfigureAwait(false); + if (written) + { + return; + } + } + + throw new InvalidOperationException("Server merge plan row " + planId + " lost too many row-version races during " + operationName + "; retry the operation."); + } + + /// + /// 按 PlanId 查行(不存在返回 null)。 + /// + private static Task FindStateAsync(string planId, CancellationToken cancellationToken) + { + return GameDb.FindAsync(state => state.PlanId == planId, isCreateIfNotExists: false, cancellationToken: cancellationToken); + } + + /// + /// 按 PlanId 取必需行(计划未登记即抛 ——报告 / 记账均以已登记计划为前提)。 + /// + private static async Task RequireStateAsync(string planId, string operationName, CancellationToken cancellationToken) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + var state = await FindStateAsync(planId, cancellationToken).ConfigureAwait(false); + if (state == null) + { + throw new InvalidOperationException("Server merge plan not registered: " + planId + " (operation: " + operationName + ")."); + } + + return state; + } + + /// + /// 载荷空串判定(空 = 对应报告未留存)。 + /// + private static bool HasPayload(string json) + { + return !string.IsNullOrEmpty(json); + } + + /// + /// 计划载荷反序列化。 + /// + private static OnlineServerMergePlan DeserializePlan(OnlineServerMergePlanState state) + { + return JsonSerializer.Deserialize(state.PlanJson); + } + + /// + /// 报告载荷反序列化。 + /// + private static OnlineServerMergeReport DeserializeReport(string json) + { + return JsonSerializer.Deserialize(json); + } +} diff --git a/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/OnlineServerAnchorState.cs b/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/OnlineServerAnchorState.cs new file mode 100644 index 000000000..74097469d --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/OnlineServerAnchorState.cs @@ -0,0 +1,62 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 legal rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any disputes or liabilities arising from secondary development based on this project +// 本项目组织与贡献者概不承担。 +// shall be borne 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.Persistence; + +using GameFrameX.Foundation.Orm.Attribute; +using GameFrameX.DataBase; + + +/// +/// 开服锚点持久化行(键 = ServerId 全表唯一;登记幂等保留首登开服时刻, +/// MergedIntoServerId 为合服归并目标(0 = 未合服))。 +/// +public sealed class OnlineServerAnchorState : BaseCacheState +{ + /// + /// 区服标识(全表唯一,唯一插入谓词键)。 + /// + [EntityIndex("ux_online_server_anchor_server_id", Unique = true)] + public long ServerId { get; set; } + + /// + /// 开服时刻(UTC 毫秒;首登后不改写)。 + /// + public long OpenedAtUnixMilliseconds { get; set; } + + /// + /// 登记时刻(UTC 毫秒)。 + /// + public long RegisteredAtUnixMilliseconds { get; set; } + + /// + /// 合服归并目标区服标识(0 = 未合服)。 + /// + public long MergedIntoServerId { get; set; } +} diff --git a/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/OnlineServerMergePlanState.cs b/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/OnlineServerMergePlanState.cs new file mode 100644 index 000000000..36c9b80a4 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.Persistence/ServerMerge/OnlineServerMergePlanState.cs @@ -0,0 +1,72 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 legal rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any disputes or liabilities arising from secondary development based on this project +// 本项目组织与贡献者概不承担。 +// shall be borne 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.Persistence; + +using GameFrameX.DataBase; +using GameFrameX.Foundation.Orm.Attribute; + +/// +/// 合服计划持久化行(键 = PlanId 唯一;计划与 dry-run / 执行报告以 JSON 载荷整存整取, +/// 行键为全局域自增 Id,不携带任何区服维度)。 +/// +/// 载荷语义:PlanJson 建行时写入不再变更(等价集合同 PlanId,幂等登记回读既有行); +/// DryRunReportJson 为最近一次预演报告(真实执行的强制前置凭据); +/// ExecutedReportJson 为执行落定报告(幂等回放凭据); +/// MergedEventPublishedAtUnixMilliseconds 为合服完成事件发布记账(0 = 未发布,重试回放据此补发)。 +/// +/// +public sealed class OnlineServerMergePlanState : BaseCacheState +{ + /// + /// 归并计划标识(merge-{target}:{sources 升序};全表唯一,唯一插入谓词键)。 + /// + [EntityIndex("ux_online_server_merge_plan_plan_id", Unique = true)] + public string PlanId { get; set; } = string.Empty; + + /// + /// 归并计划 JSON 载荷。 + /// + public string PlanJson { get; set; } = string.Empty; + + /// + /// 最近一次 dry-run 报告 JSON 载荷(空串 = 未预演)。 + /// + public string DryRunReportJson { get; set; } = string.Empty; + + /// + /// 执行落定报告 JSON 载荷(空串 = 未执行)。 + /// + public string ExecutedReportJson { get; set; } = string.Empty; + + /// + /// 合服完成事件发布时刻(UTC 毫秒;0 = 未发布)。 + /// + public long MergedEventPublishedAtUnixMilliseconds { get; set; } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle.Cli/GameFrameX.Capability.Online.ServerLifecycle.Cli.csproj b/Capability/GameFrameX.Capability.Online.ServerLifecycle.Cli/GameFrameX.Capability.Online.ServerLifecycle.Cli.csproj new file mode 100644 index 000000000..e9428e110 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle.Cli/GameFrameX.Capability.Online.ServerLifecycle.Cli.csproj @@ -0,0 +1,17 @@ + + + + + Exe + false + GameFrameX.Capability.Online.ServerLifecycle.Cli,GFX Online 合服行键重写自托管 CLI(dry-run 先行 + 幂等可重入;与 AdminApi action 双入口共用同一合服服务原语)。Self-hosted server-merge row-rewrite CLI for the GFX Online family. Documentation: https://gameframex.doc.alianblank.com + GameFrameX,Capability,Online,ServerMerge,Cli,GameServer + + + + + + + + + diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle.Cli/Program.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle.Cli/Program.cs new file mode 100644 index 000000000..fc728387c --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle.Cli/Program.cs @@ -0,0 +1,186 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.Cli; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Persistence; +using GameFrameX.Capability.Online.ServerLifecycle; +using GameFrameX.Capability.Online.ServerLifecycle.ServerMerge; +using GameFrameX.DataBase; +using GameFrameX.DataBase.Abstractions; +using GameFrameX.DataBase.Sqlite; + +/// +/// 合服行键重写 CLI 入口(自托管):装配 ServerLifecycle 合服服务(缺省 dry-run 先行), +/// GameDb 绑定经 SERVER_MERGE_DB_PROVIDER(sqlite)+ SERVER_MERGE_DB_CONNECTION_STRING 环境变量注入; +/// sqlite 模式下归并计划存储走 GameDb 持久化——一次进程 dry-run 留存报告,另一次进程 --execute +/// 可凭该报告通过执行门禁(跨进程可回读)。未配置数据库时以空端口 + 进程内存储运行(仅参数演练, +/// --execute 因报告随进程丢失而恒被门禁拒绝);配置了不支持的 provider 值直接报错退出(不静默回退)。 +/// +public static class Program +{ + /// + /// CLI 入口(参数:--target=<serverId> --sources=<id1,id2,...> [--execute];缺省 dry-run; + /// --register-open=<id1,id2,...> 先登记开服锚点(sqlite 模式持久化,幂等保留首登开服时刻)后继续, + /// 单独使用时登记完即退出)。 + /// + /// 命令行参数。 + /// 进程退出码。 + public static async Task Main(string[] args) + { + var provider = Environment.GetEnvironmentVariable("SERVER_MERGE_DB_PROVIDER"); + var connectionString = Environment.GetEnvironmentVariable("SERVER_MERGE_DB_CONNECTION_STRING"); + var isSqliteProvider = string.Equals(provider, "sqlite", StringComparison.OrdinalIgnoreCase); + if (!string.IsNullOrWhiteSpace(provider) && !isSqliteProvider) + { + Console.WriteLine("ERROR: unsupported SERVER_MERGE_DB_PROVIDER '" + provider + "'. Supported: sqlite."); + return 2; + } + + if (isSqliteProvider) + { + var opened = await GameDb.InitAsync(new DbOptions + { + ConnectionString = string.IsNullOrWhiteSpace(connectionString) ? "Data Source=server_merge_cli.db" : connectionString, + Name = "server-merge-cli", + }).ConfigureAwait(false); + if (!opened) + { + Console.WriteLine("ERROR: GameDb sqlite initialization failed."); + return 3; + } + } + + try + { + IOnlineServerCalendarStore calendarStore = isSqliteProvider + ? new GameDbOnlineServerCalendarStore() + : new InMemoryOnlineServerCalendarStore(); + string[] mergeArguments; + try + { + mergeArguments = await RegisterOpenAnchorsAsync(args, calendarStore, isSqliteProvider).ConfigureAwait(false); + } + catch (ArgumentException exception) + { + Console.WriteLine("ERROR: " + exception.Message); + return 2; + } + catch (Exception exception) when (exception is InvalidOperationException) + { + Console.WriteLine("ERROR: " + exception.Message); + return 3; + } + + if (mergeArguments == null) + { + return 0; + } + + IOnlineServerMergeRowRewriter rowRewriter = isSqliteProvider + ? new GameDbOnlineServerMergeRowRewriter() + : new NullOnlineServerMergeRowRewriter(); + IOnlineServerMergeStore mergeStore = isSqliteProvider + ? new GameDbOnlineServerMergeStore() + : new InMemoryOnlineServerMergeStore(); + var participants = new List + { + new OnlineServerAnchorMergeParticipant(calendarStore), + new OnlineLeaderboardSealMergeParticipant(new NullOnlineLeaderboardSealTarget()), + new OnlineInFlightMatchSettlementMergeParticipant(new NullOnlineInFlightMatchSettler()), + new OnlinePlayerRouteMergeParticipant(new NullOnlinePlayerRouteRewriter()), + new OnlineServerRowKeyRewriteParticipant(rowRewriter, 500), + }; + var mergeService = new OnlineServerMergeService(mergeStore, participants, new OnlineServerMergeOptions()); + return await OnlineServerMergeCli.RunAsync(mergeArguments, mergeService, Console.Out).ConfigureAwait(false); + } + finally + { + if (isSqliteProvider) + { + await GameDb.CloseAsync().ConfigureAwait(false); + } + } + } + + /// + /// 处理 --register-open=<id1,id2,...>:按当前时刻登记开服锚点(幂等)。 + /// + /// 原始命令行参数。 + /// 开服锚点存储。 + /// 锚点是否持久化(sqlite 模式 true;进程内存储的登记不跨进程)。 + /// 剔除 register-open 后的合服参数;本次调用只登记不开融合服时返回 null(调用方直接退出 0)。 + /// register-open 的 id 段非法(非正整数)时抛出(按参数错误 exit 2 收口)。 + /// 锚点登记被拒绝时抛出(按业务拒绝 exit 3 收口)。 + private static async Task RegisterOpenAnchorsAsync(string[] args, IOnlineServerCalendarStore calendarStore, bool persisted) + { + var mergeArguments = new List(); + var registerOpenSegments = new List(); + foreach (var argument in args ?? Array.Empty()) + { + if (argument != null && argument.StartsWith("--register-open=", StringComparison.Ordinal)) + { + registerOpenSegments.AddRange(argument.Substring("--register-open=".Length).Split(',')); + } + else + { + mergeArguments.Add(argument); + } + } + + if (registerOpenSegments.Count == 0) + { + return mergeArguments.ToArray(); + } + + var registerOpenServerIds = new List(); + foreach (var segment in registerOpenSegments) + { + if (!long.TryParse(segment.Trim(), out var serverId) || serverId <= 0) + { + throw new ArgumentException("invalid --register-open segment '" + segment + "'. Expected: --register-open= with positive integer ids."); + } + + registerOpenServerIds.Add(serverId); + } + + var openedAtUnixMilliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + foreach (var serverId in registerOpenServerIds) + { + await calendarStore.TryRegisterAsync(new OnlineServerAnchor { ServerId = serverId, OpenedAtUnixMilliseconds = openedAtUnixMilliseconds }).ConfigureAwait(false); + Console.WriteLine("Registered open anchor for server " + serverId + (persisted ? "." : " (in-memory store, not persisted across runs).")); + } + + return mergeArguments.Count == 0 ? null : mergeArguments.ToArray(); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/AdminApi/OnlineAdminServerLifecycleHandlers.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/AdminApi/OnlineAdminServerLifecycleHandlers.cs new file mode 100644 index 000000000..9b00b0f1e --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/AdminApi/OnlineAdminServerLifecycleHandlers.cs @@ -0,0 +1,279 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.AdminApi; + +using System; +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.ServerLifecycle.ServerMerge; + +/// +/// 区服生命周期 admin handlers(开服登记 / 日历查询 / 合服计划 / 预演 / 执行)。 +/// +public static class OnlineAdminServerLifecycleHandlers +{ + /// + /// 注册全部区服生命周期 actions。 + /// + /// 动作注册表。 + /// 开服日历服务。 + /// 合服服务。 + public static void RegisterServerLifecycleActions(AdminActionRegistry registry, OnlineServerLifecycleService calendar, OnlineServerMergeService mergeService) + { + if (registry == null) + { + throw new ArgumentNullException(nameof(registry)); + } + + registry.Register("register_server_open", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => RegisterServerOpenAsync(request, cancellationToken, calendar)), true); + registry.Register("query_server_calendar", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => QueryServerCalendarAsync(request, cancellationToken, calendar)), false); + registry.Register("plan_server_merge", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => PlanServerMergeAsync(request, cancellationToken, mergeService)), true); + registry.Register("dry_run_server_merge", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => DryRunServerMergeAsync(request, cancellationToken, mergeService)), true); + registry.Register("execute_server_merge", OnlineAdminApiAdapters.Wrap((request, scope, cancellationToken) => ExecuteServerMergeAsync(request, cancellationToken, mergeService)), true); + } + + /// + /// register_server_open:登记开服锚点(幂等;首次登记发布 ServerOpened 能力事件)。 + /// + private static async Task RegisterServerOpenAsync(AdminApiRequest request, CancellationToken cancellationToken, OnlineServerLifecycleService calendar) + { + var serverId = RequireInt64(request, "ServerId"); + var openedAt = request.ReadNullableInt64("OpenedAtUnixMilliseconds") ?? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var outcome = await calendar.TryRegisterOpenAsync(serverId, openedAt, cancellationToken).ConfigureAwait(false); + return new ServerOpenResponse + { + ServerId = outcome.Anchor.ServerId, + OpenedAtUnixMilliseconds = outcome.Anchor.OpenedAtUnixMilliseconds, + FirstRegistration = outcome.Registered, + }; + } + + /// + /// query_server_calendar:开服锚点 + 当前开服天数。 + /// + private static async Task QueryServerCalendarAsync(AdminApiRequest request, CancellationToken cancellationToken, OnlineServerLifecycleService calendar) + { + var serverId = RequireInt64(request, "ServerId"); + var now = request.ReadNullableInt64("NowUnixMilliseconds") ?? DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); + var anchor = await calendar.GetAnchorAsync(serverId, cancellationToken).ConfigureAwait(false); + return new ServerCalendarResponse + { + ServerId = serverId, + Registered = anchor != null, + OpenedAtUnixMilliseconds = anchor == null ? 0 : anchor.OpenedAtUnixMilliseconds, + MergedIntoServerId = anchor == null ? 0 : anchor.MergedIntoServerId, + OpenServerDay = await calendar.GetOpenServerDayAsync(serverId, now, cancellationToken).ConfigureAwait(false), + }; + } + + /// + /// plan_server_merge:登记归并计划(幂等;仅计划不执行)。 + /// + private static async Task PlanServerMergeAsync(AdminApiRequest request, CancellationToken cancellationToken, OnlineServerMergeService mergeService) + { + var (targetServerId, sourceServerIds) = ReadMergeRequest(request); + var outcome = await mergeService.PlanAsync(targetServerId, sourceServerIds, cancellationToken).ConfigureAwait(false); + return new MergePlanResponse { PlanId = outcome.PlanId, TargetServerId = targetServerId, SourceServerIds = new List(sourceServerIds) }; + } + + /// + /// dry_run_server_merge:dry-run 预演(零写入;报告留存为执行前置)。 + /// + private static async Task DryRunServerMergeAsync(AdminApiRequest request, CancellationToken cancellationToken, OnlineServerMergeService mergeService) + { + var (targetServerId, sourceServerIds) = ReadMergeRequest(request); + var report = await mergeService.DryRunAsync(targetServerId, sourceServerIds, cancellationToken).ConfigureAwait(false); + return MergeReportResponse.From(report, alreadyExecuted: false); + } + + /// + /// execute_server_merge:真实执行归并(幂等;无 dry-run 报告时拒绝)。 + /// + private static async Task ExecuteServerMergeAsync(AdminApiRequest request, CancellationToken cancellationToken, OnlineServerMergeService mergeService) + { + var (targetServerId, sourceServerIds) = ReadMergeRequest(request); + var outcome = await mergeService.ExecuteAsync(targetServerId, sourceServerIds, cancellationToken).ConfigureAwait(false); + return MergeReportResponse.From(outcome.Report, outcome.AlreadyExecuted); + } + + /// + /// 读取合服请求参数(TargetServerId + SourceServerIds 逗号分隔串)。 + /// + private static (long TargetServerId, IReadOnlyList SourceServerIds) ReadMergeRequest(AdminApiRequest request) + { + var targetServerId = RequireInt64(request, "TargetServerId"); + var rawSources = OnlineAdminApiContract.RequireString(request, "SourceServerIds"); + var sources = new List(); + foreach (var segment in rawSources.Split(',')) + { + if (!long.TryParse(segment.Trim(), out var sourceServerId)) + { + throw new OnlineServiceException(OnlineErrorCode.ParameterInvalid, "SourceServerIds contains an invalid server id: '" + segment + "'."); + } + + sources.Add(sourceServerId); + } + + return (targetServerId, sources); + } + + /// 开服登记响应。 + private sealed class ServerOpenResponse + { + /// 区服标识。 + public long ServerId { get; set; } + + /// 开服时刻(UTC 毫秒)。 + public long OpenedAtUnixMilliseconds { get; set; } + + /// 是否本次首次登记。 + public bool FirstRegistration { get; set; } + } + + + /// + /// 读取必填 int64 参数(缺失 / 非法时 ParameterInvalid)。 + /// + private static long RequireInt64(AdminApiRequest request, string name) + { + if (request.TryReadInt64(name, out var value)) + { + return value; + } + + throw new OnlineServiceException(OnlineErrorCode.ParameterInvalid, "Required parameter missing or invalid: " + name + "."); + } + /// 日历查询响应。 + private sealed class ServerCalendarResponse + { + /// 区服标识。 + public long ServerId { get; set; } + + /// 是否已登记锚点。 + public bool Registered { get; set; } + + /// 开服时刻(UTC 毫秒)。 + public long OpenedAtUnixMilliseconds { get; set; } + + /// 合服归入目标(0 = 未合入)。 + public long MergedIntoServerId { get; set; } + + /// 当前开服天数(未登记 = 0)。 + public int OpenServerDay { get; set; } + } + + /// 合服计划响应。 + private sealed class MergePlanResponse + { + /// 计划标识。 + public string PlanId { get; set; } + + /// 目标区服标识。 + public long TargetServerId { get; set; } + + /// 源区服标识集合。 + public List SourceServerIds { get; set; } + } + + /// 合服报告响应(dry-run / 执行共用)。 + private sealed class MergeReportResponse + { + /// 计划标识。 + public string PlanId { get; set; } + + /// 目标区服标识。 + public long TargetServerId { get; set; } + + /// 源区服标识集合。 + public List SourceServerIds { get; set; } + + /// 是否 dry-run 预演。 + public bool DryRun { get; set; } + + /// 是否既有执行的幂等回放。 + public bool AlreadyExecuted { get; set; } + + /// 行键模式版本快照。 + public int RowKeySchemaVersion { get; set; } + + /// 全局域触碰行数(恒 0 断言面)。 + public long GlobalDomainRowsTouched { get; set; } + + /// 分步报告。 + public List Steps { get; set; } + + /// + /// 由域报告构造响应。 + /// + public static MergeReportResponse From(OnlineServerMergeReport report, bool alreadyExecuted) + { + var steps = new List(); + foreach (var step in report.Steps) + { + var details = new Dictionary(); + foreach (var pair in step.Details) + { + details[pair.Key] = pair.Value; + } + + steps.Add(new MergeStepView { Step = step.Step, AffectedCount = step.AffectedCount, Details = details }); + } + + return new MergeReportResponse + { + PlanId = report.PlanId, + TargetServerId = report.TargetServerId, + SourceServerIds = new List(report.SourceServerIds), + DryRun = report.DryRun, + AlreadyExecuted = alreadyExecuted, + RowKeySchemaVersion = report.RowKeySchemaVersion, + GlobalDomainRowsTouched = report.GlobalDomainRowsTouched, + Steps = steps, + }; + } + } + + /// 分步报告视图。 + private sealed class MergeStepView + { + /// 步骤名。 + public string Step { get; set; } + + /// 受影响计数。 + public long AffectedCount { get; set; } + + /// 明细。 + public Dictionary Details { get; set; } + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/GameFrameX.Capability.Online.ServerLifecycle.csproj b/Capability/GameFrameX.Capability.Online.ServerLifecycle/GameFrameX.Capability.Online.ServerLifecycle.csproj new file mode 100644 index 000000000..ab40c49c2 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/GameFrameX.Capability.Online.ServerLifecycle.csproj @@ -0,0 +1,14 @@ + + + + + GameFrameX.Capability.Online.ServerLifecycle,GFX Online 区服生命周期能力包:开服锚点(ServerId 登记/开服日历/ServerOpened 能力事件)+ 合服原语(幂等可 dry-run 的归并计划/PlayerRoute 重指向/区服域行键重写/榜单封档/在途对局强制结算/资产归属列重写 + IServerMergeParticipant 玩法钩子)+ admin handlers(register_server_open/query_server_calendar/plan_server_merge/dry_run_server_merge/execute_server_merge). Server lifecycle capability package for the GFX Online family: server-open anchors with calendar and the ServerOpened capability event, plus idempotent dry-run-first server-merge primitives (merge plan, player-route repointing, server-domain row-key rewrite, leaderboard sealing, in-flight match settlement, asset home-server column rewrite) with the IServerMergeParticipant gameplay hook and admin handlers. Documentation: https://gameframex.doc.alianblank.com + GameFrameX,Capability,Online,ServerLifecycle,ServerMerge,GameServer + + + + + + + + diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/IOnlineServerCalendar.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/IOnlineServerCalendar.cs new file mode 100644 index 000000000..76e453d37 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/IOnlineServerCalendar.cs @@ -0,0 +1,67 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 by the developer; the project organization and contributors assume no responsibility. +// 侵犯他人合法权益等法律法规所禁止的行为! +// 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.ServerLifecycle; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +/// +/// 开服日历(按 ServerId 查询开服天数;扩展自 ICrossDay(openServerDay) 的锚点化裁决)。 +/// +public interface IOnlineServerCalendar +{ + /// + /// 登记开服锚点(幂等;首次登记发布 能力事件)。 + /// + /// 区服标识。 + /// 开服时刻(UTC 毫秒)。 + /// 取消令牌。 + /// 生效锚点与是否本次首次登记。 + Task<(OnlineServerAnchor Anchor, bool Registered)> TryRegisterOpenAsync(long serverId, long openedAtUnixMilliseconds, CancellationToken cancellationToken = default); + + /// + /// 查找开服锚点。 + /// + /// 区服标识。 + /// 取消令牌。 + /// 锚点;未登记返回 null。 + Task GetAnchorAsync(long serverId, CancellationToken cancellationToken = default); + + /// + /// 计算开服天数(边界:开服当日 = 第 1 天;锚点未登记返回 0 = 未知,调用方不得以 0 驱动跨天)。 + /// + /// 区服标识。 + /// 当前时刻(UTC 毫秒)。 + /// 取消令牌。 + /// 开服天数(第 1 天起算);未登记锚点返回 0。 + Task GetOpenServerDayAsync(long serverId, long nowUnixMilliseconds, CancellationToken cancellationToken = default); +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/IOnlineServerCalendarStore.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/IOnlineServerCalendarStore.cs new file mode 100644 index 000000000..fe35c1230 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/IOnlineServerCalendarStore.cs @@ -0,0 +1,66 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 by the developer; the project organization and contributors assume no responsibility. +// 侵犯他人合法权益等法律法规所禁止的行为! +// 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.ServerLifecycle; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +/// +/// 开服锚点存储契约(登记幂等:重复登记返回既有锚点,绝不改写开服时刻)。 +/// +public interface IOnlineServerCalendarStore +{ + /// + /// 登记开服锚点(幂等:ServerId 已登记时返回既有锚点且 registered=false,传入开服时刻被忽略)。 + /// + /// 待登记锚点(ServerId / OpenedAtUnixMilliseconds 必填)。 + /// 取消令牌。 + /// 生效锚点与是否本次首次登记。 + Task<(OnlineServerAnchor Anchor, bool Registered)> TryRegisterAsync(OnlineServerAnchor anchor, CancellationToken cancellationToken = default); + + /// + /// 查找锚点。 + /// + /// 区服标识。 + /// 取消令牌。 + /// 锚点;未登记返回 null。 + Task FindAsync(long serverId, CancellationToken cancellationToken = default); + + /// + /// 标记区服已合入目标区服(幂等:重复标记同一目标为 no-op;改标不同目标抛异常)。 + /// + /// 源区服标识。 + /// 目标区服标识。 + /// 取消令牌。 + /// 完成通知。 + Task MarkMergedAsync(long serverId, long targetServerId, CancellationToken cancellationToken = default); +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/InMemoryOnlineServerCalendarStore.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/InMemoryOnlineServerCalendarStore.cs new file mode 100644 index 000000000..a1320b009 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/InMemoryOnlineServerCalendarStore.cs @@ -0,0 +1,128 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 by the developer; the project organization and contributors assume no responsibility. +// 侵犯他人合法权益等法律法规所禁止的行为! +// 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.ServerLifecycle; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +/// +/// 开服锚点内存存储(默认实现;部署侧可覆盖为持久化实现)。 +/// +public sealed class InMemoryOnlineServerCalendarStore : IOnlineServerCalendarStore +{ + /// + /// 锚点表守卫锁。 + /// + private readonly object _lock = new(); + + /// + /// 锚点表(键 = ServerId)。 + /// + private readonly Dictionary _anchors = new(); + + /// + public Task<(OnlineServerAnchor Anchor, bool Registered)> TryRegisterAsync(OnlineServerAnchor anchor, CancellationToken cancellationToken = default) + { + if (anchor == null) + { + throw new ArgumentNullException(nameof(anchor)); + } + + if (anchor.ServerId <= 0) + { + throw new ArgumentOutOfRangeException(nameof(anchor), "ServerId must be positive."); + } + + if (anchor.OpenedAtUnixMilliseconds <= 0) + { + throw new ArgumentOutOfRangeException(nameof(anchor), "OpenedAtUnixMilliseconds must be positive."); + } + + lock (_lock) + { + if (_anchors.TryGetValue(anchor.ServerId, out var existing)) + { + return Task.FromResult((existing, false)); + } + + var stored = new OnlineServerAnchor + { + ServerId = anchor.ServerId, + OpenedAtUnixMilliseconds = anchor.OpenedAtUnixMilliseconds, + RegisteredAtUnixMilliseconds = anchor.RegisteredAtUnixMilliseconds > 0 ? anchor.RegisteredAtUnixMilliseconds : DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + MergedIntoServerId = 0, + }; + _anchors[stored.ServerId] = stored; + return Task.FromResult((stored, true)); + } + } + + /// + public Task FindAsync(long serverId, CancellationToken cancellationToken = default) + { + lock (_lock) + { + _anchors.TryGetValue(serverId, out var anchor); + return Task.FromResult(anchor); + } + } + + /// + public Task MarkMergedAsync(long serverId, long targetServerId, CancellationToken cancellationToken = default) + { + if (targetServerId <= 0) + { + throw new ArgumentOutOfRangeException(nameof(targetServerId), "TargetServerId must be positive."); + } + + lock (_lock) + { + if (!_anchors.TryGetValue(serverId, out var anchor)) + { + throw new InvalidOperationException("Server anchor not registered: " + serverId); + } + + if (anchor.MergedIntoServerId == targetServerId) + { + return Task.CompletedTask; + } + + if (anchor.MergedIntoServerId != 0) + { + throw new InvalidOperationException("Server " + serverId + " already merged into " + anchor.MergedIntoServerId + "; cannot retarget to " + targetServerId + "."); + } + + anchor.MergedIntoServerId = targetServerId; + return Task.CompletedTask; + } + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerAnchor.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerAnchor.cs new file mode 100644 index 000000000..dfa4c0954 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerAnchor.cs @@ -0,0 +1,73 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 by the developer; the project organization and contributors assume no responsibility. +// 侵犯他人合法权益等法律法规所禁止的行为! +// 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.ServerLifecycle; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +/// +/// 开服锚点(区服生命周期的第一等事实:ServerId 登记 + 开服时刻)。 +/// +/// +/// 开服天数全部由此锚点推导(), +/// 合服后源服锚点保留并登记 (历史锚点只读,供追溯与跨服对账)。 +/// +public sealed class OnlineServerAnchor +{ + /// + /// 区服标识(正数)。 + /// + public long ServerId { get; set; } + + /// + /// 开服时刻(UTC 毫秒;开服天数推导基准)。 + /// + public long OpenedAtUnixMilliseconds { get; set; } + + /// + /// 锚点登记时刻(UTC 毫秒)。 + /// + public long RegisteredAtUnixMilliseconds { get; set; } + + /// + /// 合服归入的目标区服标识(0 = 未合入)。 + /// + public long MergedIntoServerId { get; set; } + + /// + /// 是否已被合服归并( 非 0)。 + /// + public bool IsMerged + { + get { return MergedIntoServerId != 0; } + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleCapabilityModule.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleCapabilityModule.cs new file mode 100644 index 000000000..01cf1b2ef --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleCapabilityModule.cs @@ -0,0 +1,162 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle; + +using System; +using GameFrameX.Capability.Hosting.AdminApi; +using System.Threading.Tasks; +using GameFrameX.Capability.Hosting.Abstractions; +using GameFrameX.Capability.Online.Abstractions.Events; +using GameFrameX.Capability.Online.ServerLifecycle; +using GameFrameX.Capability.Online.ServerLifecycle.AdminApi; +using GameFrameX.Capability.Online.ServerLifecycle.ServerMerge; + +/// +/// 区服生命周期能力(开服锚点 / 开服日历 / ServerOpened 事件 / 合服原语)的自装配模块 +/// (Standard 第 12 席:单职责、按需引入——不要合服的部署不装本包)。 +/// +/// 维护约束(服务共享协议):模块无参构造(扫描可发现); 自装配本域—— +/// 开服锚点 store、归并计划 store、PlayerRoute 重指向端口、区服域行键重写端口、榜单封档端口、 +/// 在途对局强制结算端口均以懒默认描述符注册(族 / 宿主覆盖恒胜出:发现层 / 持久化层 / 榜单域 / +/// 对局域部署绑定直接覆盖默认空实现);合服参与者 = 内置五步 + 玩法侧经 +/// AddService<IServerMergeParticipant>(name, instance) 追加, +/// 期枚举聚合进本模块装配的合服服务(GetServices 仅 Activate 期可用;执行序 = 注册序, +/// admin 面 handler 与运行面消费方持同一服务实例,聚合对两面同时生效)。 +/// +/// +/// 边界如实声明: 在组合期(先于 Activate)被调用且签名只传入动作注册表, +/// 模块此时拿不到宿主最终服务表——直接以宿主 / 族覆盖注册 OnlineServerMergeService +/// 只对经服务解析的运行面消费方生效,admin 面五 action 固定绑定本模块装配的默认实例; +/// 玩法扩展请走上述命名参与者注册(对两面同时生效),不要覆盖合服服务类型。 +/// +/// +/// 运维约束:开服锚点缺省存储为进程内实现(重启即失)——需要跨进程 / 重启保留锚点的部署应绑定 +/// 持久化实现(如 Online.Persistence 包的 GameDbOnlineServerCalendarStore);锚点前置校验会使 +/// 未登记锚点的合服 dry-run 直接失败。 +/// +/// +public sealed class OnlineServerLifecycleCapabilityModule : ICapabilityModule, IAdminActionContributor +{ + /// + /// 区服生命周期能力清单(Id 冻结 = 终态包名;admin actions:register_server_open / + /// query_server_calendar / plan_server_merge / dry_run_server_merge / execute_server_merge)。 + /// + public static readonly CapabilityManifest ManifestInstance = new( + "online-server-lifecycle", + "1.0.0", + new[] { "register_server_open", "query_server_calendar", "plan_server_merge", "dry_run_server_merge", "execute_server_merge" }, + null, + null, + typeof(OnlineServerLifecycleOptions)); + + /// + /// 合服服务(Register 期构造;admin 面 handler 取用)。 + /// + private OnlineServerMergeService _mergeService; + + /// + /// 开服日历服务(Register 期构造;admin 面 handler 取用)。 + /// + private OnlineServerLifecycleService _calendarService; + + /// + /// 获取区服生命周期能力清单,固定返回静态实例 。 + /// + public CapabilityManifest Manifest + { + get { return ManifestInstance; } + } + + /// + /// 读取选项,懒默认注册本域 store / 端口并解析生效实例,构造开服日历服务与合服服务, + /// 聚合内置参与者与玩法侧命名注册的 。 + /// + /// 能力注册上下文。 + public void Register(CapabilityRegistrationContext context) + { + var options = context.GetOptions(); + var eventPublisher = context.GetService(); + + // 懒默认描述符(族 / 宿主覆盖恒胜出)。 + context.AddService(static _ => new InMemoryOnlineServerCalendarStore()); + context.AddService(static _ => new InMemoryOnlineServerMergeStore()); + context.AddService(static _ => new NullOnlinePlayerRouteRewriter()); + context.AddService(static _ => new NullOnlineServerMergeRowRewriter()); + context.AddService(static _ => new NullOnlineLeaderboardSealTarget()); + context.AddService(static _ => new NullOnlineInFlightMatchSettler()); + + var calendarStore = context.GetService(); + var lifecycleService = new OnlineServerLifecycleService(calendarStore, eventPublisher); + context.AddService(lifecycleService); + context.AddService(lifecycleService); + _calendarService = lifecycleService; + + var participants = new List + { + new OnlineServerAnchorMergeParticipant(calendarStore), + new OnlineLeaderboardSealMergeParticipant(context.GetService()), + new OnlineInFlightMatchSettlementMergeParticipant(context.GetService()), + new OnlinePlayerRouteMergeParticipant(context.GetService()), + new OnlineServerRowKeyRewriteParticipant(context.GetService(), options.Merge.RowRewriteBatchSize), + }; + // 玩法侧扩展走命名参与者注册(Activate 期聚合,见 ActivateAsync);本默认实例为 admin 面绑定形态。 + var mergeService = new OnlineServerMergeService(context.GetService(), participants, options.Merge, eventPublisher); + _mergeService = mergeService; + context.AddService(mergeService); + } + + /// + /// 激活期聚合玩法侧命名注册的 (锚点登记由部署 / admin 驱动,不预建)。 + /// + public Task ActivateAsync(CapabilityActivationContext context, CancellationToken cancellationToken) + { + // 玩法参与者扩展点:named 注册只能 Activate 期枚举(Register 期 GetServices 不可用), + // 聚合进模块默认合服服务——admin 面 handler 持同一实例,聚合对两面同时生效。 + _mergeService.AttachParticipants(context.Services.GetServices()); + return Task.CompletedTask; + } + + /// + /// 停用期无动作(本域无后台 job / 无外部资源)。 + /// + public Task DeactivateAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } + + /// + /// 注册区服生命周期 admin actions(开服登记 / 日历查询 / 合服计划 / 预演 / 执行)。 + /// + /// 动作注册表。 + public void RegisterAdminActions(AdminActionRegistry registry) + { + OnlineAdminServerLifecycleHandlers.RegisterServerLifecycleActions(registry, _calendarService, _mergeService); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleEvents.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleEvents.cs new file mode 100644 index 000000000..4bc3e6896 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleEvents.cs @@ -0,0 +1,144 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle; + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Events; + +/// +/// 区服生命周期事件工厂(事件是事实不是状态:载荷只放锚点标识与时刻)。 +/// +public static class OnlineServerLifecycleEvents +{ + /// 区服开服事件(首次登记开服锚点时发布;订阅方据此初始化区服维度玩法状态)。 + public const string ServerOpened = "online.server.opened"; + + /// 区服合服完成事件(归并计划真实执行成功后发布)。 + public const string ServerMerged = "online.server.merged"; + + /// + /// 事件来源标识。 + /// + public const string Source = "online-server-lifecycle"; + + /// + /// 构造区服开服事件。 + /// + /// 区服标识。 + /// 开服时刻(UTC 毫秒)。 + /// 事件信封实例。 + public static OnlineEvent CreateServerOpened(long serverId, long openedAtUnixMilliseconds) + { + var payload = new ServerOpenedPayload + { + ServerId = serverId, + OpenedAtUnixMilliseconds = openedAtUnixMilliseconds, + }; + var auditFields = new Dictionary + { + { "ServerId", serverId.ToString(CultureInfo.InvariantCulture) }, + { "OpenedAtUnixMilliseconds", openedAtUnixMilliseconds.ToString(CultureInfo.InvariantCulture) }, + }; + return new OnlineEvent + { + EventId = "evt-" + Guid.NewGuid().ToString("N"), + EventType = ServerOpened, + OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + SchemaVersion = 1, + ServerId = serverId, + PlayerId = 0, + Source = Source, + CorrelationId = string.Empty, + Payload = JsonSerializer.SerializeToUtf8Bytes(payload), + PayloadAuditFields = auditFields, + }; + } + + /// + /// 构造区服合服完成事件。 + /// + /// 目标区服标识。 + /// 源区服标识集合。 + /// 归并计划标识。 + /// 事件信封实例。 + public static OnlineEvent CreateServerMerged(long targetServerId, IReadOnlyList sourceServerIds, string planId) + { + var payload = new ServerMergedPayload + { + PlanId = planId ?? string.Empty, + SourceServerIds = sourceServerIds == null ? new List() : new List(sourceServerIds), + }; + var auditFields = new Dictionary + { + { "PlanId", payload.PlanId }, + { "TargetServerId", targetServerId.ToString(CultureInfo.InvariantCulture) }, + { "SourceServerCount", payload.SourceServerIds.Count.ToString(CultureInfo.InvariantCulture) }, + }; + return new OnlineEvent + { + // EventId 为计划派生稳定值(非随机 GUID):发布失败重试补发时订阅方可据此幂等去重。 + EventId = "evt-merge-" + payload.PlanId, + EventType = ServerMerged, + OccurredTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + SchemaVersion = 1, + ServerId = targetServerId, + PlayerId = 0, + Source = Source, + CorrelationId = string.Empty, + Payload = JsonSerializer.SerializeToUtf8Bytes(payload), + PayloadAuditFields = auditFields, + }; + } + + /// 开服事件载荷。 + private sealed class ServerOpenedPayload + { + /// 区服标识。 + public long ServerId { get; set; } + + /// 开服时刻(UTC 毫秒)。 + public long OpenedAtUnixMilliseconds { get; set; } + } + + /// 合服完成事件载荷。 + private sealed class ServerMergedPayload + { + /// 归并计划标识。 + public string PlanId { get; set; } + + /// 源区服标识集合。 + public List SourceServerIds { get; set; } + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleOptions.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleOptions.cs new file mode 100644 index 000000000..c3d28848f --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleOptions.cs @@ -0,0 +1,58 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle; + +using System; +using GameFrameX.Capability.Hosting.Abstractions; + +/// +/// 区服生命周期能力选项(装配期 一次报全 fail-fast)。 +/// +public sealed class OnlineServerLifecycleOptions : ICapabilityOptions +{ + /// + /// 合服参数段。 + /// + public OnlineServerMergeOptions Merge { get; set; } = new OnlineServerMergeOptions(); + + /// + /// 装配期校验:问题一次报全(合服参数段全部校验委托 )。 + /// + /// 校验收集器。 + public void Validate(CapabilityOptionsValidation validation) + { + if (validation == null) + { + throw new ArgumentNullException(nameof(validation)); + } + + Merge.Validate(validation); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleService.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleService.cs new file mode 100644 index 000000000..2dfccf828 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerLifecycleService.cs @@ -0,0 +1,118 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle; + +using System; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Events; + +/// +/// 区服生命周期服务( 实现:锚点登记幂等 + 首次登记发布开服事件)。 +/// +public sealed class OnlineServerLifecycleService : IOnlineServerCalendar +{ + /// + /// 一天的毫秒数(开服天数推导常数)。 + /// + public const long MillisecondsPerDay = 86400000L; + + /// + /// 开服锚点存储。 + /// + private readonly IOnlineServerCalendarStore _store; + + /// + /// 能力事件发布器(可为 null:无总线环境下的离线工具场景静默跳过发布)。 + /// + private readonly IOnlineEventPublisher _eventPublisher; + + /// + /// 初始化服务。 + /// + /// 开服锚点存储。 + /// 能力事件发布器(可空)。 + public OnlineServerLifecycleService(IOnlineServerCalendarStore store, IOnlineEventPublisher eventPublisher = null) + { + _store = store ?? throw new ArgumentNullException(nameof(store)); + _eventPublisher = eventPublisher; + } + + /// + public async Task<(OnlineServerAnchor Anchor, bool Registered)> TryRegisterOpenAsync(long serverId, long openedAtUnixMilliseconds, CancellationToken cancellationToken = default) + { + if (serverId <= 0) + { + throw new ArgumentOutOfRangeException(nameof(serverId), "ServerId must be positive."); + } + + if (openedAtUnixMilliseconds <= 0) + { + throw new ArgumentOutOfRangeException(nameof(openedAtUnixMilliseconds), "OpenedAtUnixMilliseconds must be positive."); + } + + var outcome = await _store.TryRegisterAsync(new OnlineServerAnchor + { + ServerId = serverId, + OpenedAtUnixMilliseconds = openedAtUnixMilliseconds, + }, cancellationToken).ConfigureAwait(false); + + if (outcome.Registered && _eventPublisher != null) + { + await _eventPublisher.PublishAsync(OnlineServerLifecycleEvents.CreateServerOpened(serverId, outcome.Anchor.OpenedAtUnixMilliseconds), cancellationToken).ConfigureAwait(false); + } + + return outcome; + } + + /// + public Task GetAnchorAsync(long serverId, CancellationToken cancellationToken = default) + { + return _store.FindAsync(serverId, cancellationToken); + } + + /// + public async Task GetOpenServerDayAsync(long serverId, long nowUnixMilliseconds, CancellationToken cancellationToken = default) + { + var anchor = await _store.FindAsync(serverId, cancellationToken).ConfigureAwait(false); + if (anchor == null) + { + return 0; + } + + if (nowUnixMilliseconds < anchor.OpenedAtUnixMilliseconds) + { + return 1; + } + + var elapsedDays = (nowUnixMilliseconds - anchor.OpenedAtUnixMilliseconds) / MillisecondsPerDay; + return checked((int)(elapsedDays + 1)); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerMergeOptions.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerMergeOptions.cs new file mode 100644 index 000000000..1adea1192 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/OnlineServerMergeOptions.cs @@ -0,0 +1,61 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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 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.ServerLifecycle; + +using System; +using GameFrameX.Capability.Hosting.Abstractions; + +/// +/// 合服参数段。 +/// +public sealed class OnlineServerMergeOptions +{ + /// + /// 区服域行键重写批大小(默认 500;每批一批落库,批间让出)。 + /// + public int RowRewriteBatchSize { get; set; } = 500; + + /// + /// 是否强制 dry-run 先行(默认 true:未对该归并计划产出过 dry-run 报告前拒绝真实执行)。 + /// + /// + /// 关闭该门禁 = 部署方显式承担跳过预演的数据风险;生产环境禁止关闭。 + /// + public bool RequireDryRunBeforeExecute { get; set; } = true; + + /// + /// 校验:批大小必须为正。 + /// + /// 校验收集器。 + public void Validate(CapabilityOptionsValidation validation) + { + validation.RequirePositive(nameof(RowRewriteBatchSize), RowRewriteBatchSize); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineInFlightMatchSettler.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineInFlightMatchSettler.cs new file mode 100644 index 000000000..c4d89cd62 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineInFlightMatchSettler.cs @@ -0,0 +1,53 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 在途对局强制结算端口(对局域绑定:合服前对源服在途对局强制结算;框架默认为空实现)。 +/// +public interface IOnlineInFlightMatchSettler +{ + /// + /// 强制结算源服在途对局(幂等:已结算对局回放不重复发奖;dry-run = 只统计不结算)。 + /// + /// 源区服标识集合。 + /// 目标区服标识。 + /// 是否 dry-run 预演。 + /// 取消令牌。 + /// 强制结算对局数。 + Task ForceSettleAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, CancellationToken cancellationToken); +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineLeaderboardSealTarget.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineLeaderboardSealTarget.cs new file mode 100644 index 000000000..7198059f2 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineLeaderboardSealTarget.cs @@ -0,0 +1,53 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 榜单封档端口(榜单域绑定:合服前对源服榜单做快照封档;框架默认为空实现)。 +/// +public interface IOnlineLeaderboardSealTarget +{ + /// + /// 封档源服榜单(幂等:已封档不再计数;dry-run = 只统计不落档)。 + /// + /// 源区服标识集合。 + /// 目标区服标识。 + /// 是否 dry-run 预演。 + /// 取消令牌。 + /// 封档榜单条目数。 + Task SealAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, CancellationToken cancellationToken); +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlinePlayerRouteRewriter.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlinePlayerRouteRewriter.cs new file mode 100644 index 000000000..fc3cb4023 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlinePlayerRouteRewriter.cs @@ -0,0 +1,53 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// PlayerRoute 重指向端口(发现层绑定:按源服批量改写玩家路由归属;框架默认为空实现)。 +/// +public interface IOnlinePlayerRouteRewriter +{ + /// + /// 改写玩家路由归属(幂等:已指向目标服的路由不再计数)。 + /// + /// 源区服标识集合。 + /// 目标区服标识。 + /// 是否 dry-run 预演。 + /// 取消令牌。 + /// 受影响路由数。 + Task RewriteRoutesAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, CancellationToken cancellationToken); +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineServerMergeRowRewriter.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineServerMergeRowRewriter.cs new file mode 100644 index 000000000..621d06da0 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineServerMergeRowRewriter.cs @@ -0,0 +1,63 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 区服域行键重写端口(持久化层绑定:对区服维度的行(如资产归属列 HomeServerId、 +/// 对局结算 ServerId 快照列)做单列 UPDATE 重写;框架默认为空实现,GameDb 实现见 Persistence 包)。 +/// +public interface IOnlineServerMergeRowRewriter +{ + /// + /// 统计区服域待重写行数(dry-run 报告数据面)。 + /// + /// 源区服标识集合。 + /// 取消令牌。 + /// 待重写行数(按表 / 类别分项)。 + Task> CountServerDomainRowsAsync(IReadOnlyList sourceServerIds, CancellationToken cancellationToken); + + /// + /// 重写区服域行归属(幂等:已指向目标服的行不再计数;dry-run = 只统计不落写)。 + /// + /// 源区服标识集合。 + /// 目标区服标识。 + /// 是否 dry-run 预演。 + /// 批大小。 + /// 取消令牌。 + /// 受影响行数(按表 / 类别分项)。 + Task> RewriteServerDomainRowsAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, int batchSize, CancellationToken cancellationToken); +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineServerMergeStore.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineServerMergeStore.cs new file mode 100644 index 000000000..7a924ba33 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IOnlineServerMergeStore.cs @@ -0,0 +1,107 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +/// +/// 归并计划存储契约(计划幂等登记 + dry-run 报告留存 + 执行落定记录)。 +/// +public interface IOnlineServerMergeStore +{ + /// + /// 登记归并计划(幂等:同 PlanId 已存在时返回既有计划且 planned=false)。 + /// + /// 归并计划。 + /// 取消令牌。 + /// 生效计划与是否本次首次登记。 + Task<(OnlineServerMergePlan Plan, bool Planned)> TryPlanAsync(OnlineServerMergePlan plan, CancellationToken cancellationToken = default); + + /// + /// 查找归并计划。 + /// + /// 计划标识。 + /// 取消令牌。 + /// 归并计划;不存在返回 null。 + Task FindPlanAsync(string planId, CancellationToken cancellationToken = default); + + /// + /// 留存 dry-run 报告(真实执行的强制前置凭据)。 + /// + /// 计划标识。 + /// dry-run 报告。 + /// 取消令牌。 + /// 完成通知。 + Task RecordDryRunReportAsync(string planId, OnlineServerMergeReport report, CancellationToken cancellationToken = default); + + /// + /// 查找最近一次 dry-run 报告。 + /// + /// 计划标识。 + /// 取消令牌。 + /// dry-run 报告;未预演回 null。 + Task FindDryRunReportAsync(string planId, CancellationToken cancellationToken = default); + + /// + /// 查找执行落定报告(幂等回放凭据)。 + /// + /// 计划标识。 + /// 取消令牌。 + /// 执行报告;未执行过返回 null。 + Task FindExecutedReportAsync(string planId, CancellationToken cancellationToken = default); + + /// + /// 落定执行报告(标记计划已执行;重复落定同 PlanId = no-op)。 + /// + /// 计划标识。 + /// 执行报告。 + /// 取消令牌。 + /// 完成通知。 + Task MarkExecutedAsync(string planId, OnlineServerMergeReport report, CancellationToken cancellationToken = default); + + /// + /// 合服完成事件是否已发布(at-least-once 补发记账:发布失败后重试回放时据此补发)。 + /// + /// 计划标识。 + /// 取消令牌。 + /// 已发布返回 true;未发布或计划不存在返回 false。 + Task IsMergedEventPublishedAsync(string planId, CancellationToken cancellationToken = default); + + /// + /// 记账合服完成事件已发布(幂等:重复记账 = no-op)。 + /// + /// 计划标识。 + /// 取消令牌。 + /// 完成通知。 + Task MarkMergedEventPublishedAsync(string planId, CancellationToken cancellationToken = default); +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IServerMergeParticipant.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IServerMergeParticipant.cs new file mode 100644 index 000000000..ecac4a706 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/IServerMergeParticipant.cs @@ -0,0 +1,60 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 合服参与者钩子(玩法 / 数据域归并扩展点;框架内置参与者之外,玩法包按需实现并注册)。 +/// +/// +/// 红线:① 参与者必须幂等可重入(同一计划重复执行 = no-op 或回放);② +/// 为 true 时零写入;③ 不得触碰全局域行(好友/身份/玩家存储/钱包/账本/库存/排行投影——合服零操作铁律)。 +/// +public interface IServerMergeParticipant +{ + /// + /// 参与者名(步骤报告与排序观测面)。 + /// + string Name { get; } + + /// + /// 执行本域归并步骤(dry-run = 预估不落写)。 + /// + /// 合服执行上下文。 + /// 取消令牌。 + /// 本步报告。 + Task MergeAsync(OnlineServerMergeContext context, CancellationToken cancellationToken); +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/InMemoryOnlinePlayerRouteRewriter.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/InMemoryOnlinePlayerRouteRewriter.cs new file mode 100644 index 000000000..72de1ea30 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/InMemoryOnlinePlayerRouteRewriter.cs @@ -0,0 +1,105 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 内存实现 PlayerRoute 重指向端口(单进程自托管 / 演练夹具:路由表按 (playerId → serverId) 承载)。 +/// +public sealed class InMemoryOnlinePlayerRouteRewriter : IOnlinePlayerRouteRewriter +{ + /// + /// 路由表守卫锁。 + /// + private readonly object _lock = new(); + + /// + /// 路由表(键 = 玩家标识,值 = 归属区服标识)。 + /// + private readonly Dictionary _routesByPlayer = new(); + + /// + /// 登记一条玩家路由(演练夹具数据面)。 + /// + /// 玩家标识。 + /// 归属区服标识。 + public void RegisterRoute(long playerId, long serverId) + { + lock (_lock) + { + _routesByPlayer[playerId] = serverId; + } + } + + /// + /// 查询玩家路由归属。 + /// + /// 玩家标识。 + /// 归属区服标识;未登记返回 0。 + public long FindRoute(long playerId) + { + lock (_lock) + { + return _routesByPlayer.TryGetValue(playerId, out var serverId) ? serverId : 0; + } + } + + /// + public Task RewriteRoutesAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, CancellationToken cancellationToken) + { + if (sourceServerIds == null) + { + throw new ArgumentNullException(nameof(sourceServerIds)); + } + + var sourceSet = new HashSet(sourceServerIds); + long affected = 0; + lock (_lock) + { + affected = _routesByPlayer.Values.Count(sourceSet.Contains); + + if (!dryRun && affected > 0) + { + foreach (var playerId in _routesByPlayer.Keys.ToList().Where(playerId => sourceSet.Contains(_routesByPlayer[playerId]))) + { + _routesByPlayer[playerId] = targetServerId; + } + } + } + + return Task.FromResult(affected); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/InMemoryOnlineServerMergeStore.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/InMemoryOnlineServerMergeStore.cs new file mode 100644 index 000000000..6b4f61edc --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/InMemoryOnlineServerMergeStore.cs @@ -0,0 +1,201 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +/// +/// 内存实现归并计划存储(默认实现;部署侧可覆盖为持久化实现)。 +/// +public sealed class InMemoryOnlineServerMergeStore : IOnlineServerMergeStore +{ + /// + /// 存储守卫锁。 + /// + private readonly object _lock = new(); + + /// + /// 计划表(键 = PlanId)。 + /// + private readonly Dictionary _plans = new(); + + /// + /// dry-run 报告表(键 = PlanId)。 + /// + private readonly Dictionary _dryRunReports = new(); + + /// + /// 执行报告表(键 = PlanId)。 + /// + private readonly Dictionary _executedReports = new(); + + /// + /// 合服完成事件已发布标记表(键 = PlanId;at-least-once 补发记账)。 + /// + private readonly HashSet _mergedEventPublishedPlanIds = new(); + + /// + public Task<(OnlineServerMergePlan Plan, bool Planned)> TryPlanAsync(OnlineServerMergePlan plan, CancellationToken cancellationToken = default) + { + if (plan == null) + { + throw new ArgumentNullException(nameof(plan)); + } + + lock (_lock) + { + var planId = plan.BuildPlanId(); + if (_plans.TryGetValue(planId, out var existing)) + { + return Task.FromResult((existing, false)); + } + + _plans[planId] = plan; + return Task.FromResult((plan, true)); + } + } + + /// + public Task FindPlanAsync(string planId, CancellationToken cancellationToken = default) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + lock (_lock) + { + _plans.TryGetValue(planId, out var plan); + return Task.FromResult(plan); + } + } + + /// + public Task RecordDryRunReportAsync(string planId, OnlineServerMergeReport report, CancellationToken cancellationToken = default) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + if (report == null) + { + throw new ArgumentNullException(nameof(report)); + } + + lock (_lock) + { + _dryRunReports[planId] = report; + return Task.CompletedTask; + } + } + + /// + public Task FindDryRunReportAsync(string planId, CancellationToken cancellationToken = default) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + lock (_lock) + { + _dryRunReports.TryGetValue(planId, out var report); + return Task.FromResult(report); + } + } + + /// + public Task FindExecutedReportAsync(string planId, CancellationToken cancellationToken = default) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + lock (_lock) + { + _executedReports.TryGetValue(planId, out var report); + return Task.FromResult(report); + } + } + + /// + public Task MarkExecutedAsync(string planId, OnlineServerMergeReport report, CancellationToken cancellationToken = default) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + if (report == null) + { + throw new ArgumentNullException(nameof(report)); + } + + lock (_lock) + { + _executedReports[planId] = report; + return Task.CompletedTask; + } + } + + /// + public Task IsMergedEventPublishedAsync(string planId, CancellationToken cancellationToken = default) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + lock (_lock) + { + return Task.FromResult(_mergedEventPublishedPlanIds.Contains(planId)); + } + } + + /// + public Task MarkMergedEventPublishedAsync(string planId, CancellationToken cancellationToken = default) + { + if (planId == null) + { + throw new ArgumentNullException(nameof(planId)); + } + + lock (_lock) + { + _mergedEventPublishedPlanIds.Add(planId); + return Task.CompletedTask; + } + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlineInFlightMatchSettler.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlineInFlightMatchSettler.cs new file mode 100644 index 000000000..b0f09d4fd --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlineInFlightMatchSettler.cs @@ -0,0 +1,49 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 空实现在途对局强制结算端口(未绑定对局域实现时的缺省)。 +/// +public sealed class NullOnlineInFlightMatchSettler : IOnlineInFlightMatchSettler +{ + /// + public Task ForceSettleAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, CancellationToken cancellationToken) + { + return Task.FromResult(0L); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlineLeaderboardSealTarget.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlineLeaderboardSealTarget.cs new file mode 100644 index 000000000..3ec7b293c --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlineLeaderboardSealTarget.cs @@ -0,0 +1,49 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 空实现榜单封档端口(未绑定榜单域实现时的缺省)。 +/// +public sealed class NullOnlineLeaderboardSealTarget : IOnlineLeaderboardSealTarget +{ + /// + public Task SealAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, CancellationToken cancellationToken) + { + return Task.FromResult(0L); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlinePlayerRouteRewriter.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlinePlayerRouteRewriter.cs new file mode 100644 index 000000000..f8390c2fe --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlinePlayerRouteRewriter.cs @@ -0,0 +1,49 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 空实现 PlayerRoute 重指向端口(未绑定发现层实现时的缺省:零路由可改写,报告如实计数 0)。 +/// +public sealed class NullOnlinePlayerRouteRewriter : IOnlinePlayerRouteRewriter +{ + /// + public Task RewriteRoutesAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, CancellationToken cancellationToken) + { + return Task.FromResult(0L); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlineServerMergeRowRewriter.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlineServerMergeRowRewriter.cs new file mode 100644 index 000000000..1ba77da38 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/NullOnlineServerMergeRowRewriter.cs @@ -0,0 +1,55 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 空实现区服域行键重写端口(未绑定持久化层实现时的缺省:零行可重写)。 +/// +public sealed class NullOnlineServerMergeRowRewriter : IOnlineServerMergeRowRewriter +{ + /// + public Task> CountServerDomainRowsAsync(IReadOnlyList sourceServerIds, CancellationToken cancellationToken) + { + return Task.FromResult>(new Dictionary()); + } + + /// + public Task> RewriteServerDomainRowsAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, int batchSize, CancellationToken cancellationToken) + { + return Task.FromResult>(new Dictionary()); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineInFlightMatchSettlementMergeParticipant.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineInFlightMatchSettlementMergeParticipant.cs new file mode 100644 index 000000000..f03841b25 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineInFlightMatchSettlementMergeParticipant.cs @@ -0,0 +1,69 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +/// +/// 内置参与者:在途对局强制结算(经对局域绑定端口;未绑定时如实计数 0)。 +/// +public sealed class OnlineInFlightMatchSettlementMergeParticipant : IServerMergeParticipant +{ + /// + /// 在途对局强制结算端口。 + /// + private readonly IOnlineInFlightMatchSettler _settler; + + /// + /// 初始化参与者。 + /// + /// 在途对局强制结算端口。 + public OnlineInFlightMatchSettlementMergeParticipant(IOnlineInFlightMatchSettler settler) + { + _settler = settler ?? throw new ArgumentNullException(nameof(settler)); + } + + /// + public string Name + { + get { return "in-flight-match-settlement"; } + } + + /// + public async Task MergeAsync(OnlineServerMergeContext context, CancellationToken cancellationToken) + { + var affected = await _settler.ForceSettleAsync(context.Plan.SourceServerIds, context.Plan.TargetServerId, context.DryRun, cancellationToken).ConfigureAwait(false); + var details = new Dictionary { { "matches", affected } }; + return new OnlineServerMergeStepReport("match:force-settle", affected, details); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineLeaderboardSealMergeParticipant.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineLeaderboardSealMergeParticipant.cs new file mode 100644 index 000000000..24fff16ca --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineLeaderboardSealMergeParticipant.cs @@ -0,0 +1,69 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +/// +/// 内置参与者:榜单封档(经榜单域绑定端口;未绑定时如实计数 0)。 +/// +public sealed class OnlineLeaderboardSealMergeParticipant : IServerMergeParticipant +{ + /// + /// 榜单封档端口。 + /// + private readonly IOnlineLeaderboardSealTarget _sealTarget; + + /// + /// 初始化参与者。 + /// + /// 榜单封档端口。 + public OnlineLeaderboardSealMergeParticipant(IOnlineLeaderboardSealTarget sealTarget) + { + _sealTarget = sealTarget ?? throw new ArgumentNullException(nameof(sealTarget)); + } + + /// + public string Name + { + get { return "leaderboard-seal"; } + } + + /// + public async Task MergeAsync(OnlineServerMergeContext context, CancellationToken cancellationToken) + { + var affected = await _sealTarget.SealAsync(context.Plan.SourceServerIds, context.Plan.TargetServerId, context.DryRun, cancellationToken).ConfigureAwait(false); + var details = new Dictionary { { "entries", affected } }; + return new OnlineServerMergeStepReport("leaderboard:seal", affected, details); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlinePlayerRouteMergeParticipant.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlinePlayerRouteMergeParticipant.cs new file mode 100644 index 000000000..46fcab7e8 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlinePlayerRouteMergeParticipant.cs @@ -0,0 +1,69 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +/// +/// 内置参与者:PlayerRoute 重指向(经发现层绑定端口;未绑定时如实计数 0)。 +/// +public sealed class OnlinePlayerRouteMergeParticipant : IServerMergeParticipant +{ + /// + /// PlayerRoute 重指向端口。 + /// + private readonly IOnlinePlayerRouteRewriter _rewriter; + + /// + /// 初始化参与者。 + /// + /// PlayerRoute 重指向端口。 + public OnlinePlayerRouteMergeParticipant(IOnlinePlayerRouteRewriter rewriter) + { + _rewriter = rewriter ?? throw new ArgumentNullException(nameof(rewriter)); + } + + /// + public string Name + { + get { return "player-route"; } + } + + /// + public async Task MergeAsync(OnlineServerMergeContext context, CancellationToken cancellationToken) + { + var affected = await _rewriter.RewriteRoutesAsync(context.Plan.SourceServerIds, context.Plan.TargetServerId, context.DryRun, cancellationToken).ConfigureAwait(false); + var details = new Dictionary { { "routes", affected } }; + return new OnlineServerMergeStepReport("player-route:rewrite", affected, details); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerAnchorMergeParticipant.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerAnchorMergeParticipant.cs new file mode 100644 index 000000000..d5d0c108c --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerAnchorMergeParticipant.cs @@ -0,0 +1,103 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Contracts; + +/// +/// 内置参与者:开服锚点合服标记(源服锚点 MergedIntoServerId 置目标服;幂等)。 +/// +/// 前置全量校验(dry-run 与真实执行共用):任一源服锚点未登记或已合入其他目标即整体拒绝 +/// ()——dry-run 即暴露执行期失败, +/// 真实执行不会出现部分源服已标记的半途状态。 +/// +/// +public sealed class OnlineServerAnchorMergeParticipant : IServerMergeParticipant +{ + /// + /// 开服锚点存储。 + /// + private readonly IOnlineServerCalendarStore _calendarStore; + + /// + /// 初始化参与者。 + /// + /// 开服锚点存储。 + public OnlineServerAnchorMergeParticipant(IOnlineServerCalendarStore calendarStore) + { + _calendarStore = calendarStore ?? throw new ArgumentNullException(nameof(calendarStore)); + } + + /// + public string Name + { + get { return "server-anchor"; } + } + + /// + public async Task MergeAsync(OnlineServerMergeContext context, CancellationToken cancellationToken) + { + var details = new Dictionary(); + long affected = 0; + foreach (var sourceServerId in context.Plan.SourceServerIds) + { + var anchor = await _calendarStore.FindAsync(sourceServerId, cancellationToken).ConfigureAwait(false); + if (anchor == null) + { + throw new OnlineServiceException(OnlineErrorCode.StateOperationForbidden, "Server anchor not registered: " + sourceServerId + "; register the open anchor before merging."); + } + + if (anchor.MergedIntoServerId != 0 && anchor.MergedIntoServerId != context.Plan.TargetServerId) + { + throw new OnlineServiceException(OnlineErrorCode.StateOperationForbidden, "Server " + sourceServerId + " already merged into " + anchor.MergedIntoServerId + "; cannot retarget to " + context.Plan.TargetServerId + "."); + } + + if (anchor.MergedIntoServerId != context.Plan.TargetServerId) + { + affected++; + } + } + + if (!context.DryRun) + { + foreach (var sourceServerId in context.Plan.SourceServerIds) + { + await _calendarStore.MarkMergedAsync(sourceServerId, context.Plan.TargetServerId, cancellationToken).ConfigureAwait(false); + } + } + + details["anchors"] = affected; + return new OnlineServerMergeStepReport("server-anchor:mark-merged", affected, details); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeCli.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeCli.cs new file mode 100644 index 000000000..764a1f9ae --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeCli.cs @@ -0,0 +1,248 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using System.Text.Json; +using System.Threading; +using System.Threading.Tasks; + +/// +/// 合服行键重写 CLI 运行器(自托管入口;AdminApi action 为另一入口,双入口共用同一合服服务原语)。 +/// +/// +/// 用法:--target=<serverId> --sources=<id1,id2,...> [--execute](名字与值以等号分隔)——缺省 dry-run 预演 +/// (零写入,输出 JSON 报告);--execute 真实执行(受 dry-run 先行门禁约束,幂等可重入; +/// 计划存储持久化时跨进程有效,进程内存储时报告随进程丢失)。 +/// +public static class OnlineServerMergeCli +{ + /// + /// 运行 CLI(对注入的合服服务执行 dry-run 或真实执行;报告 JSON 输出到 )。 + /// + /// 参数(--target/--sources/--execute)。 + /// 合服服务(由 CLI 宿主按部署形态装配)。 + /// 报告输出流。 + /// 取消令牌。 + /// 进程退出码(0 = 成功;2 = 参数错误;3 = 业务拒绝)。 + public static async Task RunAsync(string[] args, OnlineServerMergeService mergeService, TextWriter output, CancellationToken cancellationToken = default) + { + if (mergeService == null) + { + throw new ArgumentNullException(nameof(mergeService)); + } + + if (output == null) + { + throw new ArgumentNullException(nameof(output)); + } + + var options = await ParseArgumentsAsync(args, output).ConfigureAwait(false); + if (options == null) + { + return 2; + } + + if (options.TargetServerId <= 0 || options.SourceServerIds.Count == 0) + { + await output.WriteLineAsync("ERROR: --target and --sources are required. Usage: --target= --sources= [--execute]").ConfigureAwait(false); + return 2; + } + + OnlineServerMergeReport report; + bool alreadyExecuted = false; + try + { + if (options.Execute) + { + var outcome = await mergeService.ExecuteAsync(options.TargetServerId, options.SourceServerIds, cancellationToken).ConfigureAwait(false); + report = outcome.Report; + alreadyExecuted = outcome.AlreadyExecuted; + } + else + { + report = await mergeService.DryRunAsync(options.TargetServerId, options.SourceServerIds, cancellationToken).ConfigureAwait(false); + } + } + catch (Exception exception) when (exception is ArgumentException || exception is InvalidOperationException || exception is OperationCanceledException || exception is OnlineServiceException) + { + await output.WriteLineAsync("ERROR: " + exception.Message).ConfigureAwait(false); + return 3; + } + + + var document = JsonSerializer.Serialize(new CliReport + { + PlanId = report.PlanId, + TargetServerId = report.TargetServerId, + SourceServerIds = new List(report.SourceServerIds), + DryRun = report.DryRun, + AlreadyExecuted = alreadyExecuted, + RowKeySchemaVersion = report.RowKeySchemaVersion, + GlobalDomainRowsTouched = report.GlobalDomainRowsTouched, + Steps = ToStepViews(report.Steps), + }, new JsonSerializerOptions { WriteIndented = true }); + await output.WriteLineAsync(document).ConfigureAwait(false); + return 0; + } + + /// + /// 解析 CLI 参数(--target/--sources/--execute);非法参数输出错误并返回 null。 + /// + private static async Task ParseArgumentsAsync(string[] args, TextWriter output) + { + var options = new OnlineServerMergeCliOptions(); + foreach (var arg in args ?? Array.Empty()) + { + if (arg == "--execute") + { + options.Execute = true; + continue; + } + + var separatorIndex = arg.IndexOf('='); + if (separatorIndex <= 0) + { + await output.WriteLineAsync("ERROR: unknown argument '" + arg + "'. Usage: --target= --sources= [--execute]").ConfigureAwait(false); + return null; + } + + var name = arg.Substring(0, separatorIndex); + var value = arg.Substring(separatorIndex + 1); + if (name == "--target") + { + if (!long.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var targetServerId)) + { + await output.WriteLineAsync("ERROR: invalid --target value '" + value + "'.").ConfigureAwait(false); + return null; + } + + options.TargetServerId = targetServerId; + } + else if (name == "--sources") + { + foreach (var segment in value.Split(',')) + { + if (!long.TryParse(segment.Trim(), NumberStyles.Integer, CultureInfo.InvariantCulture, out var sourceServerId)) + { + await output.WriteLineAsync("ERROR: invalid --sources segment '" + segment + "'.").ConfigureAwait(false); + return null; + } + + options.SourceServerIds.Add(sourceServerId); + } + } + else + { + await output.WriteLineAsync("ERROR: unknown argument '" + arg + "'. Usage: --target= --sources= [--execute]").ConfigureAwait(false); + return null; + } + } + + return options; + } + + /// + /// CLI 参数解析结果(target/sources/execute)。 + /// + private sealed class OnlineServerMergeCliOptions + { + public long TargetServerId { get; set; } + + public List SourceServerIds { get; } = new List(); + + public bool Execute { get; set; } + } + + /// + /// 分步报告转 CLI 视图。 + /// + private static List ToStepViews(IReadOnlyList steps) + { + var views = new List(); + foreach (var step in steps) + { + var details = new Dictionary(); + foreach (var pair in step.Details) + { + details[pair.Key] = pair.Value; + } + + views.Add(new CliStepView { Step = step.Step, AffectedCount = step.AffectedCount, Details = details }); + } + + return views; + } + + /// CLI 报告视图。 + private sealed class CliReport + { + /// 计划标识。 + public string PlanId { get; set; } + + /// 目标区服标识。 + public long TargetServerId { get; set; } + + /// 源区服标识集合。 + public List SourceServerIds { get; set; } + + /// 是否 dry-run 预演。 + public bool DryRun { get; set; } + + /// 是否既有执行的幂等回放。 + public bool AlreadyExecuted { get; set; } + + /// 行键模式版本快照。 + public int RowKeySchemaVersion { get; set; } + + /// 全局域触碰行数(恒 0 断言面)。 + public long GlobalDomainRowsTouched { get; set; } + + /// 分步报告。 + public List Steps { get; set; } + } + + /// CLI 分步报告视图。 + private sealed class CliStepView + { + /// 步骤名。 + public string Step { get; set; } + + /// 受影响计数。 + public long AffectedCount { get; set; } + + /// 明细。 + public Dictionary Details { get; set; } + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeContext.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeContext.cs new file mode 100644 index 000000000..330d1519c --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeContext.cs @@ -0,0 +1,86 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 合服执行上下文(参与者可见面:计划 + 预演标记 + 全域触碰记账)。 +/// +public sealed class OnlineServerMergeContext +{ + /// + /// 初始化上下文。 + /// + /// 归并计划。 + /// 是否 dry-run 预演。 + /// 行键模式版本快照。 + public OnlineServerMergeContext(OnlineServerMergePlan plan, bool dryRun, int rowKeySchemaVersion) + { + Plan = plan ?? throw new ArgumentNullException(nameof(plan)); + DryRun = dryRun; + RowKeySchemaVersion = rowKeySchemaVersion; + } + + /// + /// 归并计划。 + /// + public OnlineServerMergePlan Plan { get; } + + /// + /// 是否 dry-run 预演(true 时参与者必须零写入,仅产出预估报告)。 + /// + public bool DryRun { get; } + + /// + /// 行键模式版本快照(重写器按版本感知:键形升级 = 重写逻辑需随版本迁移)。 + /// + public int RowKeySchemaVersion { get; } + + /// + /// 参与者登记的全局域触碰计数(铁律断言面:执行结束必须为 0)。 + /// + public long GlobalDomainRowsTouched { get; private set; } + + /// + /// 登记全局域触碰行数(仅测试性参与者可调用;生产参与者触碰全局域 = 违反 C462 键形铁律, + /// 合服服务会以非零计数拒绝落定执行结果)。 + /// + /// 触碰行数。 + public void RecordGlobalDomainRowsTouched(long count) + { + GlobalDomainRowsTouched += count; + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergePlan.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergePlan.cs new file mode 100644 index 000000000..7ed8304f4 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergePlan.cs @@ -0,0 +1,114 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 合服归并计划(幂等键 = BuildPlanId();同一计划重复提交为 no-op 回放)。 +/// +/// +/// 计划语义:全部 归并入 。 +/// 源服集合登记时去重排序冻结(等价集合 ⇒ 同一 PlanId ⇒ 幂等)。 +/// +public sealed class OnlineServerMergePlan +{ + /// + /// 目标区服标识(正数)。 + /// + public long TargetServerId { get; set; } + + /// + /// 源区服标识集合(登记时去重排序冻结)。 + /// + public IReadOnlyList SourceServerIds { get; set; } = new List(); + + /// + /// 计划创建时刻(UTC 毫秒)。 + /// + public long CreatedAtUnixMilliseconds { get; set; } + + /// + /// 构造归并计划(源集合去重 + 升序排序冻结)。 + /// + /// 目标区服标识。 + /// 源区服标识集合。 + /// 计划创建时刻(UTC 毫秒)。 + /// 归并计划。 + public static OnlineServerMergePlan Create(long targetServerId, IEnumerable sourceServerIds, long createdAtUnixMilliseconds) + { + if (targetServerId <= 0) + { + throw new ArgumentOutOfRangeException(nameof(targetServerId), "TargetServerId must be positive."); + } + + if (sourceServerIds == null) + { + throw new ArgumentNullException(nameof(sourceServerIds)); + } + + var sources = sourceServerIds.Distinct().OrderBy(id => id).ToList(); + if (sources.Count == 0) + { + throw new ArgumentException("SourceServerIds must not be empty.", nameof(sourceServerIds)); + } + + if (sources.Any(id => id <= 0)) + { + throw new ArgumentException("SourceServerIds must be positive.", nameof(sourceServerIds)); + } + + if (sources.Contains(targetServerId)) + { + throw new ArgumentException("TargetServerId must not appear in SourceServerIds.", nameof(sourceServerIds)); + } + + return new OnlineServerMergePlan + { + TargetServerId = targetServerId, + SourceServerIds = sources, + CreatedAtUnixMilliseconds = createdAtUnixMilliseconds, + }; + } + + /// + /// 计划标识(幂等键:merge-{target}:{sources 升序连字符连接})。 + /// + /// 计划标识。 + public string BuildPlanId() + { + return "merge-" + TargetServerId.ToString(System.Globalization.CultureInfo.InvariantCulture) + "-" + string.Join("-", SourceServerIds.Select(id => id.ToString(System.Globalization.CultureInfo.InvariantCulture))); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeReport.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeReport.cs new file mode 100644 index 000000000..c252a2f70 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeReport.cs @@ -0,0 +1,84 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 合服报告(dry-run 预演与真实执行共用形态;dry-run 报告是真实执行的强制前置)。 +/// +public sealed class OnlineServerMergeReport +{ + /// + /// 归并计划标识。 + /// + public string PlanId { get; set; } = string.Empty; + + /// + /// 目标区服标识。 + /// + public long TargetServerId { get; set; } + + /// + /// 源区服标识集合。 + /// + public IReadOnlyList SourceServerIds { get; set; } = new List(); + + /// + /// 是否 dry-run 预演。 + /// + public bool DryRun { get; set; } + + /// + /// 报告产出时刻(UTC 毫秒)。 + /// + public long ReportedAtUnixMilliseconds { get; set; } + + /// + /// 行键模式版本快照(;重写器按版本感知键形)。 + /// + public int RowKeySchemaVersion { get; set; } + + /// + /// 分步报告集合。 + /// + public IReadOnlyList Steps { get; set; } = new List(); + + /// + /// 全局域触碰行数(C462 键形铁律:好友/身份/玩家存储/钱包/账本/库存/排行投影为全局域, + /// 键内无 ServerId 位,合服零操作——本计数恒为 0,非 0 = 实现缺陷,服务层拒绝落定)。 + /// + public long GlobalDomainRowsTouched { get; set; } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeService.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeService.cs new file mode 100644 index 000000000..56221ea6c --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeService.cs @@ -0,0 +1,244 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Linq; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Events; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 合服归并服务(框架原语面:计划幂等登记 → dry-run 预演留存 → 参与者编排执行 → 幂等回放)。 +/// +/// +/// 红线:① 一切真实执行 dry-run 先行( +/// 默认开启:无该计划 dry-run 报告时拒绝执行);② 幂等可重入——同一计划重复执行返回既有执行报告回放 +/// (AlreadyExecuted=true),参与者自身也必须幂等;③ 全局域零操作铁律——参与者上报的全域触碰计数 +/// 非 0 时执行拒绝落定()。 +/// +public sealed class OnlineServerMergeService +{ + /// + /// 内置参与者顺序(锚点标记 → 榜单封档 → 在途对局强制结算 → PlayerRoute 重指向 → 区服域行键重写), + /// 玩法参与者追加其后。 + /// + private readonly List _participants; + + /// + /// 归并计划存储。 + /// + private readonly IOnlineServerMergeStore _mergeStore; + + /// + /// 合服参数。 + /// + private readonly OnlineServerMergeOptions _options; + + /// + /// 能力事件发布器(可空:离线工具场景静默跳过)。 + /// + private readonly IOnlineEventPublisher _eventPublisher; + + /// + /// 初始化服务。 + /// + /// 归并计划存储。 + /// 参与者集合(含内置与玩法参与者,按传入顺序执行)。 + /// 合服参数。 + /// 能力事件发布器(可空)。 + public OnlineServerMergeService(IOnlineServerMergeStore mergeStore, IEnumerable participants, OnlineServerMergeOptions options = null, IOnlineEventPublisher eventPublisher = null) + { + _mergeStore = mergeStore ?? throw new ArgumentNullException(nameof(mergeStore)); + if (participants == null) + { + throw new ArgumentNullException(nameof(participants)); + } + + _participants = new List(participants); + _options = options ?? new OnlineServerMergeOptions(); + _eventPublisher = eventPublisher; + } + + /// + /// 追加玩法侧合服参与者(内置五步之后、按追加顺序执行;Activate 期由能力模块聚合命名注册后调用)。 + /// + /// 追加的参与者集合(null 或空集合 = 无操作)。 + /// + /// 仅约定在宿主 Activate 完成前调用(合服执行开始前聚合完毕);实例方法线程安全(内部加锁)。 + /// + public void AttachParticipants(IEnumerable participants) + { + if (participants == null) + { + return; + } + + lock (_participants) + { + foreach (var participant in participants.Where(participant => participant != null)) + { + _participants.Add(participant); + } + } + } + + /// + /// 登记归并计划(幂等:等价集合重复登记返回既有计划)。 + /// + /// 目标区服标识。 + /// 源区服标识集合。 + /// 取消令牌。 + /// 生效计划与计划标识。 + public async Task<(OnlineServerMergePlan Plan, string PlanId)> PlanAsync(long targetServerId, IReadOnlyList sourceServerIds, CancellationToken cancellationToken = default) + { + var plan = OnlineServerMergePlan.Create(targetServerId, sourceServerIds, DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()); + var outcome = await _mergeStore.TryPlanAsync(plan, cancellationToken).ConfigureAwait(false); + return (outcome.Plan, outcome.Plan.BuildPlanId()); + } + + /// + /// dry-run 预演(不落任何写入;报告留存为真实执行的前置凭据;计划未登记时自动登记)。 + /// + /// 目标区服标识。 + /// 源区服标识集合。 + /// 取消令牌。 + /// dry-run 报告。 + public async Task DryRunAsync(long targetServerId, IReadOnlyList sourceServerIds, CancellationToken cancellationToken = default) + { + var (_, planId) = await PlanAsync(targetServerId, sourceServerIds, cancellationToken).ConfigureAwait(false); + var plan = await _mergeStore.FindPlanAsync(planId, cancellationToken).ConfigureAwait(false); + var report = await RunParticipantsAsync(plan, true, cancellationToken).ConfigureAwait(false); + await _mergeStore.RecordDryRunReportAsync(planId, report, cancellationToken).ConfigureAwait(false); + return report; + } + + /// + /// 真实执行归并(幂等:已执行计划返回既有报告回放且不再触发任何写入)。 + /// + /// 事件投递语义(at-least-once):落定后发布 online.server.merged 并在存储记账发布状态; + /// 发布失败时合服实际已完成,重试走幂等回放并补发未发布事件(EventId 为计划派生稳定值, + /// 订阅方可据此去重)。 + /// + /// + /// 目标区服标识。 + /// 源区服标识集合。 + /// 取消令牌。 + /// 执行报告与是否为既有执行的幂等回放。 + public async Task<(OnlineServerMergeReport Report, bool AlreadyExecuted)> ExecuteAsync(long targetServerId, IReadOnlyList sourceServerIds, CancellationToken cancellationToken = default) + { + var (_, planId) = await PlanAsync(targetServerId, sourceServerIds, cancellationToken).ConfigureAwait(false); + var plan = await _mergeStore.FindPlanAsync(planId, cancellationToken).ConfigureAwait(false); + + var executed = await _mergeStore.FindExecutedReportAsync(planId, cancellationToken).ConfigureAwait(false); + if (executed != null) + { + await PublishMergedEventIfNeededAsync(plan, planId, cancellationToken).ConfigureAwait(false); + return (executed, true); + } + + if (_options.RequireDryRunBeforeExecute) + { + var dryRun = await _mergeStore.FindDryRunReportAsync(planId, cancellationToken).ConfigureAwait(false); + if (dryRun == null) + { + throw new OnlineServiceException(OnlineErrorCode.StateOperationForbidden, "Server merge plan '" + planId + "' has no dry-run report; run dry-run first."); + } + } + + var report = await RunParticipantsAsync(plan, false, cancellationToken).ConfigureAwait(false); + await _mergeStore.MarkExecutedAsync(planId, report, cancellationToken).ConfigureAwait(false); + + await PublishMergedEventIfNeededAsync(plan, planId, cancellationToken).ConfigureAwait(false); + + return (report, false); + } + + /// + /// 补发未发布的合服完成事件并记账(无发布器或已发布 = 无操作;发布失败异常上抛,重试回放时再补发)。 + /// + /// 归并计划。 + /// 计划标识。 + /// 取消令牌。 + /// 完成通知。 + private async Task PublishMergedEventIfNeededAsync(OnlineServerMergePlan plan, string planId, CancellationToken cancellationToken) + { + if (_eventPublisher == null || await _mergeStore.IsMergedEventPublishedAsync(planId, cancellationToken).ConfigureAwait(false)) + { + return; + } + + await _eventPublisher.PublishAsync(OnlineServerLifecycleEvents.CreateServerMerged(plan.TargetServerId, plan.SourceServerIds, planId), cancellationToken).ConfigureAwait(false); + await _mergeStore.MarkMergedEventPublishedAsync(planId, cancellationToken).ConfigureAwait(false); + } + + /// + /// 编排全部参与者(dry-run 与真实执行共用;结束后校验全局域零操作铁律)。 + /// + /// 归并计划。 + /// 是否 dry-run 预演。 + /// 取消令牌。 + /// 聚合报告。 + private async Task RunParticipantsAsync(OnlineServerMergePlan plan, bool dryRun, CancellationToken cancellationToken) + { + var context = new OnlineServerMergeContext(plan, dryRun, OnlineRowKey.RowKeySchemaVersion); + var steps = new List(); + IServerMergeParticipant[] participantsSnapshot; + lock (_participants) + { + participantsSnapshot = _participants.ToArray(); + } + + foreach (var participant in participantsSnapshot) + { + steps.Add(await participant.MergeAsync(context, cancellationToken).ConfigureAwait(false)); + } + + if (context.GlobalDomainRowsTouched != 0) + { + throw new OnlineServiceException(OnlineErrorCode.StateOperationForbidden, "Server merge participant touched " + context.GlobalDomainRowsTouched + " global-domain rows; global domain requires zero merge operations (C462 row-key rule)."); + } + + return new OnlineServerMergeReport + { + PlanId = plan.BuildPlanId(), + TargetServerId = plan.TargetServerId, + SourceServerIds = new List(plan.SourceServerIds), + DryRun = dryRun, + ReportedAtUnixMilliseconds = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(), + RowKeySchemaVersion = OnlineRowKey.RowKeySchemaVersion, + Steps = steps, + GlobalDomainRowsTouched = 0, + }; + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeStepReport.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeStepReport.cs new file mode 100644 index 000000000..241d64079 --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerMergeStepReport.cs @@ -0,0 +1,71 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Keys; + +/// +/// 合服单步报告(一个参与者一步的产物)。 +/// +public sealed class OnlineServerMergeStepReport +{ + /// + /// 步骤名(参与者名 + 动作)。 + /// + public string Step { get; set; } + + /// + /// 受影响行数 / 条目数。 + /// + public long AffectedCount { get; set; } + + /// + /// 明细(键值观测面:表名 / 类别名 → 计数)。 + /// + public IReadOnlyDictionary Details { get; set; } = new Dictionary(); + + /// + /// 构造步骤报告。 + /// + /// 步骤名。 + /// 受影响计数。 + /// 明细。 + public OnlineServerMergeStepReport(string step, long affectedCount, IReadOnlyDictionary details = null) + { + Step = step; + AffectedCount = affectedCount; + Details = details ?? new Dictionary(); + } +} diff --git a/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerRowKeyRewriteParticipant.cs b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerRowKeyRewriteParticipant.cs new file mode 100644 index 000000000..8b45394ee --- /dev/null +++ b/Capability/GameFrameX.Capability.Online.ServerLifecycle/ServerMerge/OnlineServerRowKeyRewriteParticipant.cs @@ -0,0 +1,92 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.ServerLifecycle.ServerMerge; + +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +/// +/// 内置参与者:区服域行键重写(经持久化层绑定端口,单列 UPDATE 批处理;未绑定时如实计数 0)。 +/// +public sealed class OnlineServerRowKeyRewriteParticipant : IServerMergeParticipant +{ + /// + /// 区服域行键重写端口。 + /// + private readonly IOnlineServerMergeRowRewriter _rewriter; + + /// + /// 重写批大小。 + /// + private readonly int _batchSize; + + /// + /// 初始化参与者。 + /// + /// 区服域行键重写端口。 + /// 重写批大小(正数)。 + public OnlineServerRowKeyRewriteParticipant(IOnlineServerMergeRowRewriter rewriter, int batchSize) + { + _rewriter = rewriter ?? throw new ArgumentNullException(nameof(rewriter)); + if (batchSize <= 0) + { + throw new ArgumentOutOfRangeException(nameof(batchSize), "BatchSize must be positive."); + } + + _batchSize = batchSize; + } + + /// + public string Name + { + get { return "row-key-rewrite"; } + } + + /// + public async Task MergeAsync(OnlineServerMergeContext context, CancellationToken cancellationToken) + { + var counts = await _rewriter.RewriteServerDomainRowsAsync(context.Plan.SourceServerIds, context.Plan.TargetServerId, context.DryRun, _batchSize, cancellationToken).ConfigureAwait(false); + long affected = 0; + foreach (var pair in counts) + { + // skipped 明细是运营对账信息(CAS 失配超限跳过),不计入受影响行数。 + if (pair.Key.EndsWith("-skipped", StringComparison.Ordinal)) + { + continue; + } + + affected += pair.Value; + } + + return new OnlineServerMergeStepReport("row-key-rewrite:server-domain", affected, counts); + } +} diff --git a/Server.slnx b/Server.slnx index 8faf39d9e..fcf7d639f 100644 --- a/Server.slnx +++ b/Server.slnx @@ -24,6 +24,8 @@ + + diff --git a/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj b/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj index a81139a4d..fc8e0e9bb 100644 --- a/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj +++ b/Tests/GameFrameX.Tests/GameFrameX.Tests.csproj @@ -71,6 +71,8 @@ + + diff --git a/Tests/GameFrameX.Tests/Online/CapabilityPackageStructureTests.cs b/Tests/GameFrameX.Tests/Online/CapabilityPackageStructureTests.cs index c5bd2a190..b9d57ee90 100644 --- a/Tests/GameFrameX.Tests/Online/CapabilityPackageStructureTests.cs +++ b/Tests/GameFrameX.Tests/Online/CapabilityPackageStructureTests.cs @@ -58,7 +58,8 @@ public class CapabilityPackageStructureTests ["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.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" }, + ["GameFrameX.Capability.Online.ServerLifecycle"] = new[] { "GameFrameX.Capability.Online.Abstractions", "GameFrameX.Capability.Hosting.Abstractions" }, + ["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.Online.ServerLifecycle", "GameFrameX.Capability.Hosting.Core", "GameFrameX.DataBase" }, }; /// @@ -75,6 +76,7 @@ private static readonly (string PackageName, string CapabilityId, GameFrameX.Cap ("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), + ("GameFrameX.Capability.Online.ServerLifecycle", "online-server-lifecycle", GameFrameX.Capability.Online.ServerLifecycle.OnlineServerLifecycleCapabilityModule.ManifestInstance), }; /// diff --git a/Tests/GameFrameX.Tests/Online/GameDbOnlineServerMergeRowRewriterTests.cs b/Tests/GameFrameX.Tests/Online/GameDbOnlineServerMergeRowRewriterTests.cs new file mode 100644 index 000000000..2ec925dc2 --- /dev/null +++ b/Tests/GameFrameX.Tests/Online/GameDbOnlineServerMergeRowRewriterTests.cs @@ -0,0 +1,220 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.Tests.Online; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Keys; +using GameFrameX.Capability.Online.Persistence; +using GameFrameX.Capability.Online.Persistence.Assets; +using GameFrameX.Capability.Online.ServerLifecycle; +using GameFrameX.Capability.Online.ServerLifecycle.ServerMerge; +using GameFrameX.DataBase; +using GameFrameX.DataBase.Abstractions; +using GameFrameX.DataBase.Sqlite; +using Xunit; + +/// +/// GameDb 区服域行键重写持久化回归:账本 / 交易行 HomeServerId 单列重写幂等可重入、 +/// dry-run 零写入、行键(全局域玩家键)零改动。 +/// +[Collection("GameDbStaticStateCollection")] +public sealed class GameDbOnlineServerMergeRowRewriterTests +{ + /// + /// SQLite 内存库门面(静态门面串行集合保证独占)。 + /// + private static async Task WithSqliteFacadeAsync(Func action, string name) + { + var opened = await GameDb.InitAsync(new DbOptions + { + ConnectionString = "Data Source=:memory:", + Name = name, + }); + Assert.True(opened); + try + { + await action(); + } + finally + { + await GameDb.CloseAsync(); + GameDb.ResetForTesting(); + } + } + + [Fact] + public async Task Rewrite_HomeServerIdColumn_IsIdempotentAndRerunnable() + { + await WithSqliteFacadeAsync(async () => + { + await AddLedgerAsync(new OnlineLedgerEntryState + { + EntryId = "led-1", + PlayerId = 11, + HomeServerId = 1, + InitiatingServerId = 1, + AmountBefore = 0, + Delta = 10, + AmountAfter = 10, + SequenceNumber = 1, + }); + await AddTransactionAsync(new OnlineAssetTransactionRowState + { + TransactionId = "txn-1", + PlayerId = 11, + HomeServerId = 2, + InitiatingServerId = 2, + }); + + var rewriter = new GameDbOnlineServerMergeRowRewriter(); + + var dryRunCounts = await rewriter.RewriteServerDomainRowsAsync(new long[] { 1, 2 }, 3, true, 500, CancellationToken.None); + Assert.Equal(1, dryRunCounts[GameDbOnlineServerMergeRowRewriter.LedgerCategory]); + Assert.Equal(1, dryRunCounts[GameDbOnlineServerMergeRowRewriter.TransactionCategory]); + + // dry-run 零写入。 + var untouched = await GameDb.FindListAsync(state => state.HomeServerId == 1); + Assert.Single(untouched); + + var executedCounts = await rewriter.RewriteServerDomainRowsAsync(new long[] { 1, 2 }, 3, false, 500, CancellationToken.None); + Assert.Equal(1, executedCounts[GameDbOnlineServerMergeRowRewriter.LedgerCategory]); + Assert.Equal(1, executedCounts[GameDbOnlineServerMergeRowRewriter.TransactionCategory]); + + // 行键(全局域玩家键)零改动,只有归属列被重写。 + var ledgerRow = (await GameDb.FindListAsync(state => state.HomeServerId == 3)).Single(); + Assert.Equal("led-1", ledgerRow.EntryId); + Assert.Equal(11, ledgerRow.PlayerId); + var transactionRow = (await GameDb.FindListAsync(state => state.HomeServerId == 3)).Single(); + Assert.Equal("txn-1", transactionRow.TransactionId); + + // 重跑幂等:无行可重写。 + var rerunCounts = await rewriter.RewriteServerDomainRowsAsync(new long[] { 1, 2 }, 3, false, 500, CancellationToken.None); + Assert.Equal(0, rerunCounts[GameDbOnlineServerMergeRowRewriter.LedgerCategory]); + Assert.Equal(0, rerunCounts[GameDbOnlineServerMergeRowRewriter.TransactionCategory]); + }, "c466-row-rewriter-tests"); + } + + [Fact] + public async Task Rewrite_KeysetPagination_BatchSizeOneWalksAllRows() + { + await WithSqliteFacadeAsync(async () => + { + // 3 条账本行 + 2 条交易行归属源服 1:batchSize=1 强制多页推进(键集游标翻页 + 即读即写)。 + for (var index = 1; index <= 3; index++) + { + await AddLedgerAsync(new OnlineLedgerEntryState + { + EntryId = "led-page-" + index, + PlayerId = 20 + index, + HomeServerId = 1, + InitiatingServerId = 1, + AmountBefore = 0, + Delta = index, + AmountAfter = index, + SequenceNumber = index, + }); + } + + for (var index = 1; index <= 2; index++) + { + await AddTransactionAsync(new OnlineAssetTransactionRowState + { + TransactionId = "txn-page-" + index, + PlayerId = 30 + index, + HomeServerId = 1, + InitiatingServerId = 1, + }); + } + + var rewriter = new GameDbOnlineServerMergeRowRewriter(); + var counts = await rewriter.RewriteServerDomainRowsAsync(new long[] { 1 }, 7, false, 1, CancellationToken.None); + Assert.Equal(3, counts[GameDbOnlineServerMergeRowRewriter.LedgerCategory]); + Assert.Equal(2, counts[GameDbOnlineServerMergeRowRewriter.TransactionCategory]); + + // 全部行归属列已重写;重跑幂等(源服行数为 0)。 + var rewrittenLedger = await GameDb.FindListAsync(state => state.HomeServerId == 7); + Assert.Equal(3, rewrittenLedger.Count); + var rewrittenTransactions = await GameDb.FindListAsync(state => state.HomeServerId == 7); + Assert.Equal(2, rewrittenTransactions.Count); + + var rerunCounts = await rewriter.RewriteServerDomainRowsAsync(new long[] { 1 }, 7, false, 1, CancellationToken.None); + Assert.Equal(0, rerunCounts[GameDbOnlineServerMergeRowRewriter.LedgerCategory]); + Assert.Equal(0, rerunCounts[GameDbOnlineServerMergeRowRewriter.TransactionCategory]); + }, "c472-row-rewriter-pagination-tests"); + } + + [Fact] + public async Task CountServerDomainRows_MatchesRewriteCounts() + { + await WithSqliteFacadeAsync(async () => + { + await AddLedgerAsync(new OnlineLedgerEntryState + { + EntryId = "led-2", + PlayerId = 12, + HomeServerId = 1, + InitiatingServerId = 1, + AmountBefore = 0, + Delta = 5, + AmountAfter = 5, + SequenceNumber = 1, + }); + + var rewriter = new GameDbOnlineServerMergeRowRewriter(); + var counts = await rewriter.CountServerDomainRowsAsync(new long[] { 1 }, CancellationToken.None); + Assert.Equal(1, counts[GameDbOnlineServerMergeRowRewriter.LedgerCategory]); + Assert.Equal(0, counts[GameDbOnlineServerMergeRowRewriter.TransactionCategory]); + }, "c466-row-rewriter-count-tests"); + } + + /// + /// 按生产约定(行 Id 由序列分配,见资产库 ToState 路径)插入账本行。 + /// + private static async Task AddLedgerAsync(OnlineLedgerEntryState state) + { + state.Id = await GameDb.NextSequenceAsync("row-id"); + await GameDb.SaveOneAsync(state); + } + + /// + /// 按生产约定(行 Id 由序列分配)插入交易行。 + /// + private static async Task AddTransactionAsync(OnlineAssetTransactionRowState state) + { + state.Id = await GameDb.NextSequenceAsync("row-id"); + await GameDb.SaveOneAsync(state); + } + +} diff --git a/Tests/GameFrameX.Tests/Online/GameDbOnlineServerMergeStoreTests.cs b/Tests/GameFrameX.Tests/Online/GameDbOnlineServerMergeStoreTests.cs new file mode 100644 index 000000000..8d59776e0 --- /dev/null +++ b/Tests/GameFrameX.Tests/Online/GameDbOnlineServerMergeStoreTests.cs @@ -0,0 +1,127 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 legal rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any disputes or liabilities arising from secondary development based on this project +// 本项目组织与贡献者概不承担。 +// shall be borne 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.Tests.Online; + +using System; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Persistence; +using GameFrameX.Capability.Online.ServerLifecycle.ServerMerge; +using GameFrameX.DataBase; +using GameFrameX.DataBase.Abstractions; +using GameFrameX.DataBase.Sqlite; +using Xunit; + +/// +/// GameDb 合服计划存储持久化回归(PR #974 意见 #4 修复载体):计划幂等登记 / dry-run 报告留存 / +/// 执行落定 / 事件发布记账在全新存储实例上可回读(跨运行生命周期语义)。 +/// +[Collection("GameDbStaticStateCollection")] +public sealed class GameDbOnlineServerMergeStoreTests +{ + /// + /// SQLite 内存库门面(静态门面串行集合保证独占)。 + /// + private static async Task WithSqliteFacadeAsync(Func action, string name) + { + var opened = await GameDb.InitAsync(new DbOptions + { + ConnectionString = "Data Source=:memory:", + Name = name, + }); + Assert.True(opened); + try + { + await action(); + } + finally + { + await GameDb.CloseAsync(); + GameDb.ResetForTesting(); + } + } + + [Fact] + public async Task PlanAndReports_SurviveFreshStoreInstance() + { + await WithSqliteFacadeAsync(async () => + { + var plan = OnlineServerMergePlan.Create(3, new long[] { 1, 2 }, 1000); + var firstOutcome = await new GameDbOnlineServerMergeStore().TryPlanAsync(plan); + Assert.True(firstOutcome.Planned); + + // 等价集合重复登记:幂等返回既有计划。 + var equivalentPlan = OnlineServerMergePlan.Create(3, new long[] { 2, 1 }, 9999); + var secondOutcome = await new GameDbOnlineServerMergeStore().TryPlanAsync(equivalentPlan); + Assert.False(secondOutcome.Planned); + Assert.Equal(firstOutcome.Plan.BuildPlanId(), secondOutcome.Plan.BuildPlanId()); + + var planId = firstOutcome.Plan.BuildPlanId(); + var dryRunReport = new OnlineServerMergeReport + { + PlanId = planId, + TargetServerId = 3, + SourceServerIds = new System.Collections.Generic.List { 1, 2 }, + DryRun = true, + RowKeySchemaVersion = 1, + Steps = new System.Collections.Generic.List { new OnlineServerMergeStepReport("player-route:rewrite", 2) }, + }; + await new GameDbOnlineServerMergeStore().RecordDryRunReportAsync(planId, dryRunReport); + + // 全新存储实例(模拟另一进程)回读:计划与 dry-run 报告均在。 + var freshStore = new GameDbOnlineServerMergeStore(); + var loadedPlan = await freshStore.FindPlanAsync(planId); + Assert.Equal(new long[] { 1, 2 }, loadedPlan.SourceServerIds); + var loadedDryRun = await freshStore.FindDryRunReportAsync(planId); + Assert.True(loadedDryRun.DryRun); + Assert.Equal(2, loadedDryRun.Steps[0].AffectedCount); + + // 执行落定与事件发布记账:默认未发布;标记后新实例可见。 + Assert.False(await freshStore.IsMergedEventPublishedAsync(planId)); + var executedReport = new OnlineServerMergeReport { PlanId = planId, TargetServerId = 3, DryRun = false }; + await freshStore.MarkExecutedAsync(planId, executedReport); + await freshStore.MarkMergedEventPublishedAsync(planId); + + var anotherFreshStore = new GameDbOnlineServerMergeStore(); + Assert.NotNull(await anotherFreshStore.FindExecutedReportAsync(planId)); + Assert.True(await anotherFreshStore.IsMergedEventPublishedAsync(planId)); + }, "c472-merge-store-persistence-tests"); + } + + [Fact] + public async Task RecordDryRun_WithoutRegisteredPlan_Throws() + { + await WithSqliteFacadeAsync(async () => + { + var store = new GameDbOnlineServerMergeStore(); + await Assert.ThrowsAsync(() => store.RecordDryRunReportAsync("merge-9-1", new OnlineServerMergeReport { PlanId = "merge-9-1" }, CancellationToken.None)); + }, "c472-merge-store-unregistered-plan-tests"); + } +} diff --git a/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs b/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs index 190dc0c49..0ee2409ff 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineAdminApiDispatcherTests.cs @@ -96,7 +96,8 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => { var dispatcher = OnlineCapabilityTestHarness.CreateDispatcher(runtime.Host); - // 业务 action 30 = assets 7(grant_asset / revoke_asset / query_wallet_ledger / query_asset_audit / query_transaction_detail + // 业务 action 35 = server-lifecycle 5(register_server_open / query_server_calendar / plan_server_merge / dry_run_server_merge / execute_server_merge) + // + 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 / @@ -107,9 +108,9 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => // + 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(30, declaredActions.Count); + Assert.Equal(35, declaredActions.Count); Assert.Equal(declaredActions.Count + 3, dispatcher.ActionNames.Count); - Assert.Equal(33, dispatcher.ActionNames.Count); + Assert.Equal(38, dispatcher.ActionNames.Count); foreach (var action in declaredActions) { Assert.Contains(action, dispatcher.ActionNames); diff --git a/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs b/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs index 5a5711999..f084ce57e 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineCapabilityComposeTests.cs @@ -82,13 +82,13 @@ public class OnlineCapabilityComposeTests private static readonly HttpClient SharedHttpClient = new HttpClient(); /// - /// 八能力全装配的拓扑序(依赖边:social→foundation、matchmaking→social、match 可选 assets/matchmaking、 - /// leaderboard 可选 match、competition 必选 leaderboard 可选 assets、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、 + /// server-lifecycle 无能力依赖;同层按能力 Id Ordinal)。 /// private static readonly string[] ExpectedTopologicalOrder = { - "online-assets", "online-foundation", "online-social", "online-matchmaking", + "online-assets", "online-foundation", "online-server-lifecycle", "online-social", "online-matchmaking", "online-match", "online-leaderboard", "online-competition", "online-operations", }; @@ -200,7 +200,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => Assert.NotNull(runtime.Host); Assert.Null(runtime.AdminApi); Assert.Equal(ExpectedTopologicalOrder, runtime.Report.EnabledIdsInOrder); - Assert.Equal(8, runtime.Report.Entries.Count(entry => entry.State == CapabilityFilterState.Enabled)); + Assert.Equal(9, 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(); @@ -272,7 +272,7 @@ public async Task Compose_EmptyFilterLists_AssembleAll() { await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => { - Assert.Equal(8, runtime.Report.Entries.Count(entry => entry.State == CapabilityFilterState.Enabled)); + Assert.Equal(9, 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())); @@ -286,7 +286,7 @@ public async Task Compose_BlankEntries_TreatedAsUnfiltered() { await OnlineCapabilityTestHarness.WithRuntimeAsync(runtime => { - Assert.Equal(8, runtime.Report.Entries.Count(entry => entry.State == CapabilityFilterState.Enabled)); + Assert.Equal(9, runtime.Report.Entries.Count(entry => entry.State == CapabilityFilterState.Enabled)); return Task.CompletedTask; }, null, options => options.Filter = new CapabilityAssemblyFilter(new[] { string.Empty, " " }, new[] { string.Empty, " " })); } @@ -315,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(7, runtime.Report.EnabledIdsInOrder.Count); + Assert.Equal(8, runtime.Report.EnabledIdsInOrder.Count); Assert.DoesNotContain("online-operations", runtime.Report.EnabledIdsInOrder); return Task.CompletedTask; }, null, options => options.Filter = new CapabilityAssemblyFilter(null, new[] { "online-operations" })); @@ -337,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(7, installed.Length); + Assert.Equal(8, installed.Length); Assert.DoesNotContain("online-operations", installed); } }, null, options => options.Filter = new CapabilityAssemblyFilter(null, new[] { "online-operations" })); @@ -369,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(8, entries.Count); + Assert.Equal(9, entries.Count); Assert.Equal("ExcludedByDisableList", entries["online-assets"].GetProperty("State").GetString()); Assert.Equal("Enabled", entries["online-foundation"].GetProperty("State").GetString()); - Assert.Equal(7, data.GetProperty("EnabledIdsInOrder").GetArrayLength()); + Assert.Equal(8, data.GetProperty("EnabledIdsInOrder").GetArrayLength()); } using (var inner = ParseInner(await PostAsync("grant_asset", "{\"TenantId\":1,\"AppId\":1,\"ServerId\":1001,\"RequestId\":\"r2\"}"))) @@ -602,7 +602,7 @@ await OnlineCapabilityTestHarness.WithRuntimeAsync(async runtime => Assert.Equal(ExpectedTopologicalOrder, ReadStrings(data.GetProperty("EnabledIdsInOrder"))); var entries = IndexBy(data.GetProperty("Capabilities"), "Id"); - Assert.Equal(8, entries.Count); + Assert.Equal(9, entries.Count); var match = entries["online-match"]; Assert.Equal(new[] { "online-assets", "online-matchmaking" }, ReadStrings(match.GetProperty("OptionalCapabilityIds"))); @@ -734,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(6, runtime.Report.EnabledIdsInOrder.Count); + Assert.Equal(7, runtime.Report.EnabledIdsInOrder.Count); foreach (var absentId in new[] { "online-assets", "online-matchmaking" }) { diff --git a/Tests/GameFrameX.Tests/Online/OnlineServerLifecycleTests.cs b/Tests/GameFrameX.Tests/Online/OnlineServerLifecycleTests.cs new file mode 100644 index 000000000..5ad2c4100 --- /dev/null +++ b/Tests/GameFrameX.Tests/Online/OnlineServerLifecycleTests.cs @@ -0,0 +1,354 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.Tests.Online; + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Abstractions.Events; +using GameFrameX.Capability.Online.Abstractions.Keys; +using GameFrameX.Capability.Online.ServerLifecycle; +using GameFrameX.Capability.Online.ServerLifecycle.ServerMerge; +using Xunit; + +/// +/// 区服生命周期与合服原语回归:开服锚点幂等 / 开服天数边界 / ServerOpened 事件 / +/// dry-run 先行门禁 / 幂等回放 / 全局域零操作铁律。 +/// +public sealed class OnlineServerLifecycleTests +{ + private const long DayMilliseconds = 86400000L; + + [Fact] + public async Task TryRegisterOpen_Idempotent_ReturnsExistingAnchorAndKeepsFirstOpenTime() + { + var service = new OnlineServerLifecycleService(new InMemoryOnlineServerCalendarStore()); + var first = await service.TryRegisterOpenAsync(7, 1000); + var second = await service.TryRegisterOpenAsync(7, 999999); + + Assert.True(first.Registered); + Assert.False(second.Registered); + Assert.Equal(1000, second.Anchor.OpenedAtUnixMilliseconds); + } + + [Fact] + public async Task GetOpenServerDay_Boundary_OpenDayIsDayOneAndNextDayFlipsAtExactly24Hours() + { + var service = new OnlineServerLifecycleService(new InMemoryOnlineServerCalendarStore()); + await service.TryRegisterOpenAsync(7, 1000); + + Assert.Equal(1, await service.GetOpenServerDayAsync(7, 1000)); + Assert.Equal(1, await service.GetOpenServerDayAsync(7, 1000 + DayMilliseconds - 1)); + Assert.Equal(2, await service.GetOpenServerDayAsync(7, 1000 + DayMilliseconds)); + Assert.Equal(10, await service.GetOpenServerDayAsync(7, 1000 + 9 * DayMilliseconds)); + Assert.Equal(0, await service.GetOpenServerDayAsync(8, 1000)); + } + + [Fact] + public async Task TryRegisterOpen_FirstRegistration_PublishesServerOpenedOnce() + { + var publisher = new CollectingEventPublisher(); + var service = new OnlineServerLifecycleService(new InMemoryOnlineServerCalendarStore(), publisher); + await service.TryRegisterOpenAsync(7, 1000); + await service.TryRegisterOpenAsync(7, 2000); + + var opened = publisher.Events.Where(e => e.EventType == OnlineServerLifecycleEvents.ServerOpened).ToList(); + Assert.Single(opened); + Assert.Equal(7, opened[0].ServerId); + Assert.Equal("1000", opened[0].PayloadAuditFields["OpenedAtUnixMilliseconds"]); + } + + [Fact] + public async Task Plan_SameSourceSetDifferentOrder_CanonicalPlanIdIsIdempotent() + { + var mergeStore = new InMemoryOnlineServerMergeStore(); + var service = BuildMergeService(mergeStore); + + var first = await service.PlanAsync(3, new long[] { 1, 2 }); + var second = await service.PlanAsync(3, new long[] { 2, 1, 2 }); + + Assert.Equal(first.PlanId, second.PlanId); + Assert.Equal(new long[] { 1, 2 }, second.Plan.SourceServerIds); + } + + [Fact] + public async Task Plan_TargetInSources_IsRejected() + { + var service = BuildMergeService(new InMemoryOnlineServerMergeStore()); + await Assert.ThrowsAsync(() => service.PlanAsync(3, new long[] { 1, 3 })); + await Assert.ThrowsAsync(() => service.PlanAsync(3, new long[] { 0 })); + await Assert.ThrowsAsync(() => service.PlanAsync(3, new long[0])); + } + + [Fact] + public async Task Execute_WithoutDryRun_IsRejectedByDryRunFirstGate() + { + var service = BuildMergeService(new InMemoryOnlineServerMergeStore()); + + var exception = await Assert.ThrowsAsync(() => service.ExecuteAsync(3, new long[] { 1 })); + Assert.Equal(OnlineErrorCode.StateOperationForbidden, exception.Code); + } + + [Fact] + public async Task DryRun_ThenExecute_SecondExecuteReplaysWithoutDoubleWrite() + { + var calendarStore = new InMemoryOnlineServerCalendarStore(); + await calendarStore.TryRegisterAsync(new OnlineServerAnchor { ServerId = 1, OpenedAtUnixMilliseconds = 1000 }); + await calendarStore.TryRegisterAsync(new OnlineServerAnchor { ServerId = 2, OpenedAtUnixMilliseconds = 2000 }); + var routeRewriter = new InMemoryOnlinePlayerRouteRewriter(); + routeRewriter.RegisterRoute(101, 1); + routeRewriter.RegisterRoute(102, 1); + routeRewriter.RegisterRoute(201, 2); + routeRewriter.RegisterRoute(301, 9); + var mergeStore = new InMemoryOnlineServerMergeStore(); + var service = BuildMergeService(mergeStore, calendarStore, routeRewriter); + + var dryRun = await service.DryRunAsync(3, new long[] { 1, 2 }); + Assert.True(dryRun.DryRun); + Assert.Equal(0, dryRun.GlobalDomainRowsTouched); + Assert.Equal(3, dryRun.Steps.First(step => step.Step == "player-route:rewrite").AffectedCount); + Assert.Equal(0, routeRewriter.FindRoute(101) != 3 ? 0 : 1); // dry-run 零写入:路由仍指向源服 + Assert.Equal(1, routeRewriter.FindRoute(101)); + + var executed = await service.ExecuteAsync(3, new long[] { 1, 2 }); + Assert.False(executed.AlreadyExecuted); + Assert.Equal(3, executed.Report.Steps.First(step => step.Step == "player-route:rewrite").AffectedCount); + Assert.Equal(3, routeRewriter.FindRoute(101)); + var anchorOne = await calendarStore.FindAsync(1); + Assert.Equal(3, routeRewriter.FindRoute(201)); + Assert.Equal(9, routeRewriter.FindRoute(301)); + + Assert.True(anchorOne.IsMerged); + Assert.Equal(3, anchorOne.MergedIntoServerId); + + var replay = await service.ExecuteAsync(3, new long[] { 2, 1 }); + Assert.True(replay.AlreadyExecuted); + Assert.Equal(executed.Report.PlanId, replay.Report.PlanId); + } + + [Fact] + public async Task Execute_TwiceWithParticipantCounts_AnchorMarkMergedIsIdempotent() + { + var calendarStore = new InMemoryOnlineServerCalendarStore(); + await calendarStore.TryRegisterAsync(new OnlineServerAnchor { ServerId = 1, OpenedAtUnixMilliseconds = 1 }); + var service = BuildMergeService(new InMemoryOnlineServerMergeStore(), calendarStore); + + await service.DryRunAsync(3, new long[] { 1 }); + var first = await service.ExecuteAsync(3, new long[] { 1 }); + var anchorStep = first.Report.Steps.Single(step => step.Step == "server-anchor:mark-merged"); + Assert.Equal(1, anchorStep.AffectedCount); + + // 幂等回放:不重新执行参与者。 + var replay = await service.ExecuteAsync(3, new long[] { 1 }); + Assert.True(replay.AlreadyExecuted); + } + + [Fact] + public async Task Execute_ParticipantTouchedGlobalDomain_IsRefused() + { + var mergeStore = new InMemoryOnlineServerMergeStore(); + var participants = new List { new GlobalDomainViolatingParticipant() }; + var service = new OnlineServerMergeService(mergeStore, participants); + // 铁律断言面:dry-run 阶段即拒绝触碰全局域(预演也不允许改写全局域行),报告不落定。 + var dryRunException = await Assert.ThrowsAsync(() => service.DryRunAsync(3, new long[] { 1 })); + Assert.Equal(OnlineErrorCode.StateOperationForbidden, dryRunException.Code); + Assert.Null(await mergeStore.FindDryRunReportAsync("merge-3-1")); + Assert.Null(await mergeStore.FindExecutedReportAsync("merge-3-1")); + } + + [Fact] + public async Task MergeReport_CarriesRowKeySchemaVersionSnapshot() + { + var calendarStore = new InMemoryOnlineServerCalendarStore(); + await calendarStore.TryRegisterAsync(new OnlineServerAnchor { ServerId = 1, OpenedAtUnixMilliseconds = 1000 }); + var service = BuildMergeService(new InMemoryOnlineServerMergeStore(), calendarStore); + var report = await service.DryRunAsync(3, new long[] { 1 }); + Assert.Equal(OnlineRowKey.RowKeySchemaVersion, report.RowKeySchemaVersion); + } + + [Fact] + public async Task DryRun_UnregisteredSourceAnchor_IsRefusedUpfront() + { + // 前置全量校验:dry-run 即暴露执行期失败(未登记锚点不再被静默计入 affected)。 + var service = BuildMergeService(new InMemoryOnlineServerMergeStore()); + var exception = await Assert.ThrowsAsync(() => service.DryRunAsync(3, new long[] { 1 })); + Assert.Equal(OnlineErrorCode.StateOperationForbidden, exception.Code); + } + + [Fact] + public async Task DryRun_SourceAnchorMergedElsewhere_IsRefusedUpfront() + { + var calendarStore = new InMemoryOnlineServerCalendarStore(); + await calendarStore.TryRegisterAsync(new OnlineServerAnchor { ServerId = 1, OpenedAtUnixMilliseconds = 1000 }); + await calendarStore.MarkMergedAsync(1, 9); + var service = BuildMergeService(new InMemoryOnlineServerMergeStore(), calendarStore); + + var exception = await Assert.ThrowsAsync(() => service.DryRunAsync(3, new long[] { 1 })); + Assert.Equal(OnlineErrorCode.StateOperationForbidden, exception.Code); + } + + [Fact] + public async Task AttachParticipants_GameplayParticipants_AppendAfterBuiltInSteps() + { + var calendarStore = new InMemoryOnlineServerCalendarStore(); + await calendarStore.TryRegisterAsync(new OnlineServerAnchor { ServerId = 1, OpenedAtUnixMilliseconds = 1000 }); + var service = BuildMergeService(new InMemoryOnlineServerMergeStore(), calendarStore); + + service.AttachParticipants(new List { new RecordingParticipant("gameplay-migration") }); + + var dryRun = await service.DryRunAsync(3, new long[] { 1 }); + Assert.Equal(1, dryRun.Steps.Single(step => step.Step == "gameplay-migration").AffectedCount); + // 内置五步仍在,玩法参与者追加其后。 + Assert.Equal(6, dryRun.Steps.Count); + } + + [Fact] + public async Task Execute_PublishFailureAfterMarkExecuted_ReplayRepublishesWithStableEventId() + { + var calendarStore = new InMemoryOnlineServerCalendarStore(); + await calendarStore.TryRegisterAsync(new OnlineServerAnchor { ServerId = 1, OpenedAtUnixMilliseconds = 1000 }); + var publisher = new FailingOnceEventPublisher(); + var mergeStore = new InMemoryOnlineServerMergeStore(); + var service = new OnlineServerMergeService(mergeStore, new List(), new OnlineServerMergeOptions(), publisher); + + await service.DryRunAsync(3, new long[] { 1 }); + + // 第一次执行:参与者与落定成功,事件发布失败——合服实际已完成。 + await Assert.ThrowsAsync(() => service.ExecuteAsync(3, new long[] { 1 })); + Assert.NotNull(await mergeStore.FindExecutedReportAsync("merge-3-1")); + Assert.False(await mergeStore.IsMergedEventPublishedAsync("merge-3-1")); + + // 重试:幂等回放 + 补发未发布事件;EventId 为计划派生稳定值(订阅方可去重)。 + var replay = await service.ExecuteAsync(3, new long[] { 1 }); + Assert.True(replay.AlreadyExecuted); + Assert.True(await mergeStore.IsMergedEventPublishedAsync("merge-3-1")); + var mergedEvent = Assert.Single(publisher.PublishedEvents); + Assert.Equal(OnlineServerLifecycleEvents.ServerMerged, mergedEvent.EventType); + Assert.Equal("evt-merge-merge-3-1", mergedEvent.EventId); + + // 已发布后再次回放:不重复发布。 + await service.ExecuteAsync(3, new long[] { 1 }); + Assert.Single(publisher.PublishedEvents); + } + + internal static OnlineServerMergeService BuildMergeService(IOnlineServerMergeStore mergeStore, IOnlineServerCalendarStore calendarStore = null, IOnlinePlayerRouteRewriter routeRewriter = null) + { + calendarStore ??= new InMemoryOnlineServerCalendarStore(); + routeRewriter ??= new NullOnlinePlayerRouteRewriter(); + var participants = new List + { + new OnlineServerAnchorMergeParticipant(calendarStore), + new OnlineLeaderboardSealMergeParticipant(new NullOnlineLeaderboardSealTarget()), + new OnlineInFlightMatchSettlementMergeParticipant(new NullOnlineInFlightMatchSettler()), + new OnlinePlayerRouteMergeParticipant(routeRewriter), + new OnlineServerRowKeyRewriteParticipant(new NullOnlineServerMergeRowRewriter(), 500), + }; + return new OnlineServerMergeService(mergeStore, participants); + } + + /// + /// 记录执行次数的玩法参与者夹具。 + /// + private sealed class RecordingParticipant : IServerMergeParticipant + { + private readonly string _step; + + public RecordingParticipant(string step) + { + _step = step; + } + + public string Name + { + get { return _step; } + } + + public Task MergeAsync(OnlineServerMergeContext context, System.Threading.CancellationToken cancellationToken) + { + return Task.FromResult(new OnlineServerMergeStepReport(_step, 1)); + } + } + + /// + /// 首次发布抛异常的事件发布器(补发语义回归载体:发布失败后重试回放须补发)。 + /// + private sealed class FailingOnceEventPublisher : IOnlineEventPublisher + { + private bool _failedOnce; + + public List PublishedEvents { get; } = new(); + + public Task PublishAsync(OnlineEvent onlineEvent, CancellationToken cancellationToken = default) + { + if (!_failedOnce) + { + _failedOnce = true; + throw new InvalidOperationException("publish failure simulation"); + } + + PublishedEvents.Add(onlineEvent); + return Task.CompletedTask; + } + } + + /// + /// 触碰全局域的违规参与者(铁律回归载体:合服服务必须拒绝落定)。 + /// + private sealed class GlobalDomainViolatingParticipant : IServerMergeParticipant + { + public string Name + { + get { return "global-domain-violator"; } + } + + public Task MergeAsync(OnlineServerMergeContext context, CancellationToken cancellationToken) + { + context.RecordGlobalDomainRowsTouched(42); + return Task.FromResult(new OnlineServerMergeStepReport("violator:touch-global-domain", 42)); + } + } + + /// + /// 事件收集发布器。 + /// + private sealed class CollectingEventPublisher : IOnlineEventPublisher + { + public List Events { get; } = new(); + + public Task PublishAsync(OnlineEvent onlineEvent, CancellationToken cancellationToken = default) + { + Events.Add(onlineEvent); + return Task.CompletedTask; + } + } +} diff --git a/Tests/GameFrameX.Tests/Online/OnlineServerMergeAcceptanceTests.cs b/Tests/GameFrameX.Tests/Online/OnlineServerMergeAcceptanceTests.cs new file mode 100644 index 000000000..2a9a6c2b7 --- /dev/null +++ b/Tests/GameFrameX.Tests/Online/OnlineServerMergeAcceptanceTests.cs @@ -0,0 +1,303 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and other 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 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.Tests.Online; + +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading.Tasks; +using GameFrameX.Capability.Online.Abstractions.Events; +using GameFrameX.Capability.Online.ServerLifecycle; +using GameFrameX.Capability.Online.ServerLifecycle.Cli; +using GameFrameX.Capability.Online.ServerLifecycle.ServerMerge; +using GameFrameX.DataBase; +using Xunit; + +/// +/// N3 合服演练(acceptance 可重跑):双服构造数据 → 开服锚点 → dry-run 报告(零写入)→ 真实执行 → +/// 路由重指向 / 锚点归并断言 → 重跑幂等回放 → 全局域零操作断言;并覆盖 CLI 入口 dry-run 出口与 +/// Program.Main 双进程语义(登记 → 预演 → 跨进程执行)。 +/// +[Collection("GameDbStaticStateCollection")] +public sealed class OnlineServerMergeAcceptanceTests +{ + [Fact] + public async Task ServerMergeDrill_TwoServers_DryRunThenExecuteThenReplayAllGreen() + { + // —— 双服构造数据:开服锚点(服 1 早于服 2 开服)+ 玩家路由 + 榜单封档计数器。 + var calendarStore = new InMemoryOnlineServerCalendarStore(); + var publisher = new CollectingEventPublisher(); + var lifecycle = new OnlineServerLifecycleService(calendarStore, publisher); + await lifecycle.TryRegisterOpenAsync(1, 864000000L); + await lifecycle.TryRegisterOpenAsync(2, 2 * 864000000L); + + var routeRewriter = new InMemoryOnlinePlayerRouteRewriter(); + routeRewriter.RegisterRoute(101, 1); + routeRewriter.RegisterRoute(102, 1); + routeRewriter.RegisterRoute(201, 2); + + var sealTarget = new CountingSealTarget(5); + var settler = new CountingMatchSettler(2); + var mergeStore = new InMemoryOnlineServerMergeStore(); + var participants = new List + { + new OnlineServerAnchorMergeParticipant(calendarStore), + new OnlineLeaderboardSealMergeParticipant(sealTarget), + new OnlineInFlightMatchSettlementMergeParticipant(settler), + new OnlinePlayerRouteMergeParticipant(routeRewriter), + new OnlineServerRowKeyRewriteParticipant(new NullOnlineServerMergeRowRewriter(), 500), + }; + var mergeService = new OnlineServerMergeService(mergeStore, participants, new OnlineServerMergeOptions(), publisher); + + // —— dry-run:报告先行且零写入。 + var dryRun = await mergeService.DryRunAsync(2, new long[] { 1 }); + Assert.True(dryRun.DryRun); + Assert.Equal("merge-2-1", dryRun.PlanId); + Assert.Equal(0, dryRun.GlobalDomainRowsTouched); + Assert.Equal(1, StepCount(dryRun, "server-anchor:mark-merged")); + Assert.Equal(5, StepCount(dryRun, "leaderboard:seal")); + Assert.Equal(2, StepCount(dryRun, "match:force-settle")); + Assert.Equal(2, StepCount(dryRun, "player-route:rewrite")); + Assert.False(sealTarget.Sealed); + Assert.False(settler.Settled); + Assert.Equal(1, routeRewriter.FindRoute(101)); + + // —— 真实执行。 + var executed = await mergeService.ExecuteAsync(2, new long[] { 1 }); + Assert.False(executed.AlreadyExecuted); + Assert.Equal(0, executed.Report.GlobalDomainRowsTouched); + Assert.True(sealTarget.Sealed); + Assert.True(settler.Settled); + Assert.Equal(2, routeRewriter.FindRoute(101)); + Assert.Equal(2, routeRewriter.FindRoute(102)); + Assert.Equal(2, routeRewriter.FindRoute(201)); + + var sourceAnchor = await calendarStore.FindAsync(1); + Assert.True(sourceAnchor.IsMerged); + Assert.Equal(2, sourceAnchor.MergedIntoServerId); + + // 目标服锚点不受影响(开服时刻保留,合服不改写目标服日历)。 + var targetAnchor = await calendarStore.FindAsync(2); + Assert.False(targetAnchor.IsMerged); + Assert.Equal(2 * 864000000L, targetAnchor.OpenedAtUnixMilliseconds); + + // ServerOpened ×2(双服开服)+ ServerMerged ×1(合服完成)。 + Assert.Equal(2, publisher.Events.Count(e => e.EventType == OnlineServerLifecycleEvents.ServerOpened)); + Assert.Single(publisher.Events.Where(e => e.EventType == OnlineServerLifecycleEvents.ServerMerged)); + + // —— 重跑:幂等回放,不再触发任何写入。 + var replay = await mergeService.ExecuteAsync(2, new long[] { 1 }); + Assert.True(replay.AlreadyExecuted); + Assert.Equal(1, sealTarget.SealCalls); + Assert.Equal(1, settler.SettleCalls); + } + + [Fact] + public async Task ServerMergeCli_DryRunMode_PrintsJsonReport() + { + var calendarStore = new InMemoryOnlineServerCalendarStore(); + // 锚点前置校验:dry-run 也要求源服 / 目标服锚点已登记(未登记即预演失败)。 + await calendarStore.TryRegisterAsync(new OnlineServerAnchor { ServerId = 1, OpenedAtUnixMilliseconds = 864000000L }); + await calendarStore.TryRegisterAsync(new OnlineServerAnchor { ServerId = 3, OpenedAtUnixMilliseconds = 864000000L }); + var routeRewriter = new InMemoryOnlinePlayerRouteRewriter(); + routeRewriter.RegisterRoute(101, 1); + var mergeService = new OnlineServerMergeService( + new InMemoryOnlineServerMergeStore(), + new List + { + new OnlineServerAnchorMergeParticipant(calendarStore), + new OnlineLeaderboardSealMergeParticipant(new NullOnlineLeaderboardSealTarget()), + new OnlineInFlightMatchSettlementMergeParticipant(new NullOnlineInFlightMatchSettler()), + new OnlinePlayerRouteMergeParticipant(routeRewriter), + new OnlineServerRowKeyRewriteParticipant(new NullOnlineServerMergeRowRewriter(), 500), + }); + + using (var output = new StringWriter()) + { + var exitCode = await OnlineServerMergeCli.RunAsync(new[] { "--target=3", "--sources=1" }, mergeService, output); + + Assert.Equal(0, exitCode); + var report = output.ToString(); + Assert.Contains("\"PlanId\": \"merge-3-1\"", report); + Assert.Contains("\"DryRun\": true", report); + Assert.Contains("\"GlobalDomainRowsTouched\": 0", report); + Assert.Equal(1, routeRewriter.FindRoute(101)); // CLI 缺省 dry-run:零写入。 + } + } + + [Fact] + public async Task ServerMergeCli_ExecuteWithoutPriorDryRun_ExitCodeThree() + { + var mergeService = new OnlineServerMergeService(new InMemoryOnlineServerMergeStore(), new List()); + using (var output = new StringWriter()) + { + var exitCode = await OnlineServerMergeCli.RunAsync(new[] { "--target=3", "--sources=1,2", "--execute" }, mergeService, output); + + Assert.Equal(3, exitCode); + Assert.Contains("dry-run", output.ToString()); + } + } + + [Fact] + public async Task ProgramMain_UnsupportedProvider_ExitCodeTwo() + { + var previousProvider = Environment.GetEnvironmentVariable("SERVER_MERGE_DB_PROVIDER"); + var previousConnection = Environment.GetEnvironmentVariable("SERVER_MERGE_DB_CONNECTION_STRING"); + try + { + Environment.SetEnvironmentVariable("SERVER_MERGE_DB_PROVIDER", "postgres"); + Environment.SetEnvironmentVariable("SERVER_MERGE_DB_CONNECTION_STRING", null); + + var exitCode = await Program.Main(new[] { "--target=3", "--sources=1" }); + + Assert.Equal(2, exitCode); + } + finally + { + Environment.SetEnvironmentVariable("SERVER_MERGE_DB_PROVIDER", previousProvider); + Environment.SetEnvironmentVariable("SERVER_MERGE_DB_CONNECTION_STRING", previousConnection); + } + } + + [Fact] + public async Task ProgramMain_SqliteMode_DryRunThenExecuteAcrossSeparateRuns() + { + // 审查验收(PR #974 意见 #4):一次运行登记锚点 + dry-run 留存报告,另一次全新装配 --execute 成功—— + // 计划 / 报告 / 锚点均持久化,dry-run 先行门禁凭跨运行可回读的报告放行。 + var databaseFilePath = Path.Combine(Path.GetTempPath(), "c472-server-merge-cli-" + Guid.NewGuid().ToString("N") + ".db"); + var previousProvider = Environment.GetEnvironmentVariable("SERVER_MERGE_DB_PROVIDER"); + var previousConnection = Environment.GetEnvironmentVariable("SERVER_MERGE_DB_CONNECTION_STRING"); + try + { + Environment.SetEnvironmentVariable("SERVER_MERGE_DB_PROVIDER", "sqlite"); + Environment.SetEnvironmentVariable("SERVER_MERGE_DB_CONNECTION_STRING", "Data Source=" + databaseFilePath); + + var dryRunExitCode = await Program.Main(new[] { "--register-open=1,3", "--target=3", "--sources=1" }); + Assert.Equal(0, dryRunExitCode); + + var executeExitCode = await Program.Main(new[] { "--target=3", "--sources=1", "--execute" }); + Assert.Equal(0, executeExitCode); + + // 幂等:执行后的再次 dry-run 报告源服行数为 0(归属列已重写 / 锚点已标记)。 + var replayExitCode = await Program.Main(new[] { "--target=3", "--sources=1" }); + Assert.Equal(0, replayExitCode); + } + finally + { + Environment.SetEnvironmentVariable("SERVER_MERGE_DB_PROVIDER", previousProvider); + Environment.SetEnvironmentVariable("SERVER_MERGE_DB_CONNECTION_STRING", previousConnection); + GameDb.ResetForTesting(); + try + { + File.Delete(databaseFilePath); + } + catch (IOException) + { + // 临时库清理失败不影响断言结论。 + } + } + } + + private static long StepCount(OnlineServerMergeReport report, string step) + { + return report.Steps.Single(candidate => candidate.Step == step).AffectedCount; + } + + /// + /// 计数榜单封档端口(演练夹具:封档条目数固定,记录调用次数验证幂等)。 + /// + private sealed class CountingSealTarget : IOnlineLeaderboardSealTarget + { + private readonly long _entryCount; + + public CountingSealTarget(long entryCount) + { + _entryCount = entryCount; + } + + public int SealCalls { get; private set; } + + public bool Sealed { get; private set; } + + public Task SealAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, System.Threading.CancellationToken cancellationToken) + { + if (!dryRun) + { + SealCalls++; + Sealed = true; + } + + return Task.FromResult(_entryCount); + } + } + + /// + /// 计数在途对局强制结算端口(演练夹具)。 + /// + private sealed class CountingMatchSettler : IOnlineInFlightMatchSettler + { + private readonly long _matchCount; + + public CountingMatchSettler(long matchCount) + { + _matchCount = matchCount; + } + + public int SettleCalls { get; private set; } + + public bool Settled { get; private set; } + + public Task ForceSettleAsync(IReadOnlyList sourceServerIds, long targetServerId, bool dryRun, System.Threading.CancellationToken cancellationToken) + { + if (!dryRun) + { + SettleCalls++; + Settled = true; + } + + return Task.FromResult(_matchCount); + } + } + + /// + /// 事件收集发布器。 + /// + private sealed class CollectingEventPublisher : IOnlineEventPublisher + { + public List Events { get; } = new(); + + public Task PublishAsync(OnlineEvent onlineEvent, System.Threading.CancellationToken cancellationToken = default) + { + Events.Add(onlineEvent); + return Task.CompletedTask; + } + } +} diff --git a/scripts/acceptance.sh b/scripts/acceptance.sh index 8338954e6..e42ad7c2f 100755 --- a/scripts/acceptance.sh +++ b/scripts/acceptance.sh @@ -137,6 +137,11 @@ run_cmd \ "回滚开关验证 EnableUnifiedClient=false" \ "RemoteMessaging__EnableUnifiedClient=false dotnet test $TEST_PROJECT --filter \"$REMOTE_FILTER\"" +run_cmd \ + "合服演练 N3(ServerLifecycle dry-run 先行 + 幂等回放 + 全局域零操作断言)" \ + "dotnet test $TEST_PROJECT --filter \"FullyQualifiedName~OnlineServerMerge|FullyQualifiedName~OnlineServerLifecycle|FullyQualifiedName~MergeRowRewriter\"" + + if [[ "$MODE" == "full" ]]; then run_cmd \ "重试开关验证 EnableRetry=false" \