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