diff --git a/.editorconfig b/.editorconfig index fde3db835..27a21f5f3 100644 --- a/.editorconfig +++ b/.editorconfig @@ -12,10 +12,15 @@ dotnet_diagnostic.GFX0020.severity = error dotnet_diagnostic.GFX0021.severity = error # Hotfix Wrapper 源码生成器诊断(GameFrameX.Hotfix.WrapperGenerator/Utils/Logger.cs 分配): -# GFW 前缀与分析器 GFX0001-0021 错开;GFW0001=契约违规(Error)、GFW0002=契约警示(Warning),可按 ID 抑制或升级 +# GFW 前缀与分析器 GFX0001-0022 错开;GFW0001=契约违规(Error)、GFW0002=契约警示(Warning),可按 ID 抑制或升级 dotnet_diagnostic.GFW0001.severity = error dotnet_diagnostic.GFW0002.severity = warning +# 静态便捷层过渡标注(GameDb/GameEventDispatcher/HotfixManager/PlayerSessionManager/ConfigComponent 的 +# [Obsolete] 指向注入面):仓内存量调用点约数百处,迁移由后续收敛阶段分批完成;仓内构建把 CS0618 +# 降为 none 保持告警基线不变,nupkg 消费方仍见完整 Obsolete 文案(迁移信标不失真)。 +dotnet_diagnostic.CS0618.severity = none + # PB 库(vendored 生态移植,不按本仓风格改造,整目录排除) [GameFrameX.ProtoBuf.Net/**.cs] csharp_prefer_braces = true:none diff --git a/Capability/GameFrameX.Capability.Hosting.Abstractions/CapabilityHostModulePhase.cs b/Capability/GameFrameX.Capability.Hosting.Abstractions/CapabilityHostModulePhase.cs new file mode 100644 index 000000000..28e7e0dda --- /dev/null +++ b/Capability/GameFrameX.Capability.Hosting.Abstractions/CapabilityHostModulePhase.cs @@ -0,0 +1,52 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +namespace GameFrameX.Capability.Hosting.Abstractions; + +/// +/// 宿主基础设施模块的激活相位(组合选项的 AddHostModule 声明): +/// 机制在依赖拓扑定序时为相位注入合成定序边—— 模块先于全部能力模块激活, +/// 模块晚于全部能力模块与全部 Before 模块激活;停用一律按激活逆序。 +/// +/// 维护约束:合成边只参与定序,不进入服务解析来源策略(AllowedOwnersByConsumer)—— +/// 宿主模块与能力模块之间的服务可见性仍由 Requires / Optional 显式声明决定。 +/// +/// +public enum CapabilityHostModulePhase +{ + /// + /// 早段宿主模块:在全部能力模块激活之前激活(承载旧栈早段固定序列,如数据库初始化、发现层激活、组件注册、热更装载)。 + /// + BeforeCapabilities = 0, + + /// + /// 晚段宿主模块:在全部能力模块与全部早段宿主模块激活之后激活(承载依赖能力桥就绪的收尾序列,如网络监听开放、ServiceOnline 分发)。 + /// + AfterCapabilities = 1, +} diff --git a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityComposition.cs b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityComposition.cs index 5edf4a747..938d41bcd 100644 --- a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityComposition.cs +++ b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityComposition.cs @@ -37,11 +37,19 @@ namespace GameFrameX.Capability.Hosting.Core; /// 编排责任全部收回机制层)。 /// /// 维护约束(机制开放红线):机制包零能力硬编码——第二个能力族只需提供 -/// 实现,机制零改动;装配问题逐条打日志后抛汇总异常(一次报全);业务面与管理面至少启用其一。 +/// 实现,机制零改动;装配问题逐条打日志后抛汇总异常(一次报全);业务面与管理面至少启用其一; +/// 宿主基础设施模块()与能力模块进入同一宿主, +/// 由机制统一拓扑定序与启停——组合根唯一,不承认任何静态组合面。 /// /// public static class CapabilityComposition { + /// + /// 无族组合(宿主基础设施模块 only)的族标识占位:服务覆盖与解析来源标记使用, + /// 不对应任何部署扫描面或配置段。 + /// + internal const string HostOnlyFamilyId = "host"; + /// /// 组合一个能力族(族基建 → 宿主覆盖 → 部署目录扫描 → 同 Id 校验 → 过滤 → 依赖检查 → 定序 → /// Options 合并 → Register → 宿主 / 管理面 / 报告)。 @@ -96,8 +104,8 @@ public static CapabilityRuntime Compose(ICapabilityFamily family, CapabilityComp CapabilityHost host; try { - var modules = CapabilityAssembly.DiscoverFromDeploymentDirectory(family.DeploymentAssemblyPrefix); - host = builder.Build(modules); + var discoveredModules = CapabilityAssembly.DiscoverFromDeploymentDirectory(family.DeploymentAssemblyPrefix); + host = builder.Build(MergeHostModules(discoveredModules, options)); } catch (CapabilityAssemblyException exception) { @@ -131,4 +139,130 @@ public static CapabilityRuntime Compose(ICapabilityFamily family, CapabilityComp return new CapabilityRuntime(options.EnableRuntime ? host : null, adminApiPlane, host.Report); } + + /// + /// 无族组合(宿主基础设施模块 only):不执行族基建注册、部署目录扫描、管理面组装与成功报告渲染, + /// 仅把 组装为业务宿主——供未启用任何能力族的 + /// 进程 / Role 承载宿主侧固定启停序列(组合根仍唯一收敛于机制)。 + /// + /// 维护约束:至少声明一个宿主模块;EnableRuntime 必须为 true(无族形态无管理面可退); + /// 管理面工厂不得设置(管理面属族组合产物,需与 同用)。 + /// + /// + /// 组合选项(须含至少一个宿主模块)。 + /// 业务宿主组合产物(管理面为 null)。 + public static CapabilityRuntime Compose(CapabilityCompositionOptions options) + { + if (options == null) + { + throw new ArgumentNullException(nameof(options)); + } + + if (options.HostModules.Count == 0) + { + // Localization: Capability.Hosting.Composition.HostModulesRequired - 无族组合缺少宿主模块。 + throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Capability.Hosting.Composition.HostModulesRequired)); + } + + if (options.AdminApiPlaneFactory != null) + { + // Localization: Capability.Hosting.Composition.AdminApiPlaneRequiresFamily - 管理面工厂需与能力族同用。 + throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Capability.Hosting.Composition.AdminApiPlaneRequiresFamily)); + } + + if (!options.EnableRuntime) + { + // Localization: Capability.Hosting.Composition.NoPlaneEnabled - 未启用任何能力面。 + throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Capability.Hosting.Composition.NoPlaneEnabled)); + } + + if (options.HostOptions == null) + { + options.HostOptions = new CapabilityHostOptions(); + } + + if (!options.HostOptions.IsValid()) + { + // Localization: Capability.Hosting.OptionsInvalid - 能力宿主选项非法(作用域三元组 / 调度间隔)。 + throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Capability.Hosting.OptionsInvalid)); + } + + var services = new CapabilityServices(); + services.SetFamilyCapabilityId(HostOnlyFamilyId); + var eventBus = new CapabilityEventBus(options.AssemblyLog); + + var overrideEntries = options.OverrideEntries; + for (var i = 0; i < overrideEntries.Count; i++) + { + var entry = overrideEntries[i]; + services.AddOverride(new CapabilityServiceRegistration(entry.ServiceType, string.Empty, entry.Factory, HostOnlyFamilyId, true)); + } + + var builder = new CapabilityHostBuilder(services, eventBus, new HostOnlyCapabilityFamily(), options); + var hostModules = new List(options.HostModules.Count); + for (var i = 0; i < options.HostModules.Count; i++) + { + hostModules.Add(options.HostModules[i].Module); + } + + var host = builder.Build(hostModules); + return new CapabilityRuntime(host, null, host.Report); + } + + /// + /// 合并宿主基础设施模块到发现序模块表(宿主模块追加于尾部;同 Id 查重在装配表构建时统一执行)。 + /// + /// 部署目录发现的能力模块。 + /// 组合选项(宿主模块来源)。 + /// 合并后的模块表。 + private static IReadOnlyList MergeHostModules(IReadOnlyList discoveredModules, CapabilityCompositionOptions options) + { + if (options.HostModules.Count == 0) + { + return discoveredModules; + } + + var merged = new List(discoveredModules.Count + options.HostModules.Count); + for (var i = 0; i < discoveredModules.Count; i++) + { + merged.Add(discoveredModules[i]); + } + + for (var i = 0; i < options.HostModules.Count; i++) + { + merged.Add(options.HostModules[i].Module); + } + + return merged; + } + + /// + /// 无族组合的占位族(族标识 / 配置段名 / 部署前缀均为宿主占位语义;不注册任何族基建)。 + /// + private sealed class HostOnlyCapabilityFamily : ICapabilityFamily + { + /// 获取族标识(宿主占位)。 + public string FamilyId + { + get { return HostOnlyFamilyId; } + } + + /// 获取配置段名(宿主占位;错误路径前缀不出现)。 + public string ConfigurationSectionName + { + get { return "Host"; } + } + + /// 获取部署程序集前缀(占位值;无族组合不执行部署扫描)。 + public string DeploymentAssemblyPrefix + { + get { return "GameFrameX.Host"; } + } + + /// 无族基建可注册(空实现)。 + /// 族基建注册面(不使用)。 + public void RegisterInfrastructure(CapabilityFamilyContext context) + { + } + } } diff --git a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityCompositionOptions.cs b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityCompositionOptions.cs index ed6a06a72..4fdb68c6b 100644 --- a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityCompositionOptions.cs +++ b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityCompositionOptions.cs @@ -32,7 +32,7 @@ namespace GameFrameX.Capability.Hosting.Core; /// -/// 能力组合选项( 的唯一配置面:族配置段 + 装配日志出口 + +/// 能力组合选项( 的唯一配置面:族配置段 + 装配日志出口 + /// 双面开关 + 宿主选项 + 代码层 Options 覆盖与服务覆盖 + 管理面工厂)。 /// /// 维护约束(GFX0018 符号检查面): / / @@ -52,6 +52,11 @@ public sealed class CapabilityCompositionOptions /// private readonly List _overrideEntries = new(); + /// + /// 宿主基础设施模块(相位声明;注册序落表)。 + /// + private readonly List _hostModules = new(); + /// /// 管理面工厂(由 Hosting.AdminApi 包的 UseAdminApi 扩展设置)。 /// @@ -104,6 +109,34 @@ public CapabilityCompositionOptions(JsonElement familyConfigurationSection, ICap /// public ICapabilitySchedulerObserver SchedulerObserver { get; set; } + /// + /// 获取宿主基础设施模块表(机制装配期读取)。 + /// + internal IReadOnlyList HostModules + { + get { return _hostModules; } + } + + /// + /// 声明一个宿主基础设施模块:与能力模块进入同一宿主参与统一拓扑定序与生命周期—— + /// 先于全部能力模块激活, + /// 晚于全部能力模块激活;停用按激活逆序。 + /// 维护约束:宿主模块不受 影响(恒启用);其 Requires 只允许引用 + /// 其它已在模块表中的能力 Id;同一 Id 重复声明 = 装配失败。 + /// + /// 宿主模块实例(不可为 null)。 + /// 激活相位。 + public void AddHostModule(ICapabilityModule module, CapabilityHostModulePhase phase) + { + if (module == null) + { + throw new ArgumentNullException(nameof(module)); + } + + _hostModules.Add(new HostModuleEntry(module, phase)); + } + + /// /// 声明代码层 Options 覆盖(只改需要改的字段;合并优先级:包内默认 < 配置段 < 代码 Configure)。 /// @@ -236,4 +269,32 @@ public OverrideEntry(Type serviceType, Func f /// public Func Factory { get; } } + + /// + /// 宿主基础设施模块条目(模块 + 激活相位)。 + /// + internal sealed class HostModuleEntry + { + /// + /// 初始化 。 + /// + /// 宿主模块。 + /// 激活相位。 + public HostModuleEntry(ICapabilityModule module, CapabilityHostModulePhase phase) + { + Module = module; + Phase = phase; + } + + /// + /// 获取宿主模块。 + /// + public ICapabilityModule Module { get; } + + /// + /// 获取激活相位。 + /// + public CapabilityHostModulePhase Phase { get; } + } } + diff --git a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityDependencyChecker.cs b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityDependencyChecker.cs index 04224dbad..46cd12c64 100644 --- a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityDependencyChecker.cs +++ b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityDependencyChecker.cs @@ -46,10 +46,11 @@ internal static class CapabilityDependencyChecker /// 执行依赖检查与拓扑定序。 /// /// 全部已发现模块(含被过滤的)。 - /// 过滤器判定启用的模块。 + /// 过滤器判定启用的模块(宿主模块恒在)。 /// 装配过滤器(缺席原因判定用)。 + /// 宿主基础设施模块表(相位合成定序边来源)。 /// 检查结果(问题条目 / 依赖状态 / 缺失功能 / 解析来源策略 / 拓扑序)。 - public static Result Check(IReadOnlyList allModules, IReadOnlyList enabledModules, CapabilityAssemblyFilter filter) + public static Result Check(IReadOnlyList allModules, IReadOnlyList enabledModules, CapabilityAssemblyFilter filter, IReadOnlyList hostModules) { var manifestsById = new Dictionary(StringComparer.Ordinal); for (var i = 0; i < allModules.Count; i++) @@ -75,6 +76,8 @@ public static Result Check(IReadOnlyList allModules, IReadOnl CheckModule(enabledModules[i].Manifest, manifestsById, enabledIds, filter, result, edges); } + ApplyHostModulePhaseEdges(enabledModules, hostModules, edges); + CollectCycles(enabledModules, edges, result); if (result.Problems.Count == 0) { @@ -84,6 +87,86 @@ public static Result Check(IReadOnlyList allModules, IReadOnl return result; } + /// + /// 注入宿主模块相位的合成定序边:能力模块依赖全部 BeforeCapabilities 宿主模块; + /// AfterCapabilities 宿主模块依赖全部能力模块与全部 BeforeCapabilities 宿主模块。 + /// + /// 维护约束:合成边只参与定序(与显式 Requires/Optional 边同图参与环检测), + /// 不写入 AllowedOwnersByConsumer——宿主模块与能力模块之间的服务可见性仍由显式依赖声明决定。 + /// 能力模块显式 Requires 一个 AfterCapabilities 宿主模块会与合成边成环,按环路 fail-fast 报出。 + /// + /// + /// 启用模块。 + /// 宿主模块表(含相位)。 + /// 定序边累积器(依赖方 → 依赖集合)。 + private static void ApplyHostModulePhaseEdges(IReadOnlyList enabledModules, IReadOnlyList hostModules, Dictionary> edges) + { + if (hostModules == null || hostModules.Count == 0) + { + return; + } + + var beforePhaseIds = new List(); + var afterPhaseIds = new List(); + var hostModuleIds = new HashSet(StringComparer.Ordinal); + for (var i = 0; i < hostModules.Count; i++) + { + var hostModuleId = hostModules[i].Module.Manifest.Id; + if (!edges.ContainsKey(hostModuleId)) + { + // 未进入启用集的宿主模块(不在本次装配模块表内)不参与合成边。 + continue; + } + + hostModuleIds.Add(hostModuleId); + if (hostModules[i].Phase == CapabilityHostModulePhase.BeforeCapabilities) + { + beforePhaseIds.Add(hostModuleId); + } + else + { + afterPhaseIds.Add(hostModuleId); + } + } + + if (beforePhaseIds.Count == 0 && afterPhaseIds.Count == 0) + { + return; + } + + for (var i = 0; i < enabledModules.Count; i++) + { + var moduleId = enabledModules[i].Manifest.Id; + if (hostModuleIds.Contains(moduleId)) + { + // After 相位宿主模块依赖能力模块与 Before 相位宿主模块;Before 相位宿主模块之间不注入合成边(由自身声明与 Id 序决定)。 + if (afterPhaseIds.Contains(moduleId)) + { + var dependentIds = edges[moduleId]; + for (var j = 0; j < enabledModules.Count; j++) + { + var otherId = enabledModules[j].Manifest.Id; + if (!string.Equals(otherId, moduleId, StringComparison.Ordinal) + && !afterPhaseIds.Contains(otherId)) + { + dependentIds.Add(otherId); + } + } + } + + continue; + } + + // 能力模块依赖全部 Before 相位宿主模块。 + var moduleEdges = edges[moduleId]; + for (var j = 0; j < beforePhaseIds.Count; j++) + { + moduleEdges.Add(beforePhaseIds[j]); + } + } + } + + /// /// 检查单个模块的必选 / 可选依赖(必选缺失记问题;可选缺失记数据;在场依赖记定序边与来源策略)。 /// diff --git a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityHostBuilder.cs b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityHostBuilder.cs index e88d93b8e..84c82cf3f 100644 --- a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityHostBuilder.cs +++ b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityHostBuilder.cs @@ -80,9 +80,10 @@ public CapabilityHostBuilder(CapabilityServices services, CapabilityEventBus eve } /// - /// 装配(过滤器校验 → 过滤 → 依赖检查 → 定序 → 来源策略 → Options 合并 → Register → 产出宿主)。 + /// 装配(同 Id 查重 → 过滤器校验 → 过滤(宿主模块豁免)→ 依赖检查(含相位合成定序边)→ 定序 → + /// 来源策略 → Options 合并 → Register → 产出宿主)。 /// - /// 全部已发现模块(发现序)。 + /// 全部模块(发现序 + 宿主模块尾部追加)。 /// 能力宿主(含报告与调度壳)。 public CapabilityHost Build(IReadOnlyList modules) { @@ -90,22 +91,37 @@ public CapabilityHost Build(IReadOnlyList modules) var manifestsById = new Dictionary(StringComparer.Ordinal); for (var i = 0; i < modules.Count; i++) { - manifestsById[modules[i].Manifest.Id] = modules[i]; + var module = modules[i]; + if (manifestsById.TryGetValue(module.Manifest.Id, out var existing)) + { + // Localization: Capability.Hosting.DuplicateCapability - 能力 Id 重复注册。 + throw new InvalidOperationException(string.Format(LocalizationService.GetString(Localization.Keys.Capability.Hosting.DuplicateCapability), module.Manifest.Id + " (" + existing.GetType().Assembly.GetName().Name + " / " + module.GetType().Assembly.GetName().Name + ")")); + } + + manifestsById.Add(module.Manifest.Id, module); } ValidateFilterTargets(filter, manifestsById); + // 宿主基础设施模块不受过滤器影响(恒启用);能力模块照常走过滤。 + var hostModuleIds = new HashSet(StringComparer.Ordinal); + var hostModules = _options.HostModules; + for (var i = 0; i < hostModules.Count; i++) + { + hostModuleIds.Add(hostModules[i].Module.Manifest.Id); + } + var enabledModules = new List(); for (var i = 0; i < modules.Count; i++) { - if (filter.Match(modules[i].Manifest) == CapabilityFilterState.Enabled) + if (hostModuleIds.Contains(modules[i].Manifest.Id) || filter.Match(modules[i].Manifest) == CapabilityFilterState.Enabled) { enabledModules.Add(modules[i]); } } // 依赖检查在任何模块 Register 之前:检查不通过就不执行任何模块代码,不会留下装了一半的状态。 - var dependencyResult = CapabilityDependencyChecker.Check(modules, enabledModules, filter); + var dependencyResult = CapabilityDependencyChecker.Check(modules, enabledModules, filter, hostModules); if (dependencyResult.Problems.Count > 0) { throw new CapabilityAssemblyException(dependencyResult.Problems); diff --git a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityRuntime.cs b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityRuntime.cs index 28e8720a6..9842efc0e 100644 --- a/Capability/GameFrameX.Capability.Hosting.Core/CapabilityRuntime.cs +++ b/Capability/GameFrameX.Capability.Hosting.Core/CapabilityRuntime.cs @@ -31,7 +31,7 @@ namespace GameFrameX.Capability.Hosting.Core; /// -/// 能力组合产物(一次 的双面承载:业务宿主 + 管理面 + 报告; +/// 能力组合产物(一次 的双面承载:业务宿主 + 管理面 + 报告; /// 未启用的面为 null)。 /// /// 维护约束(启停序):启动 = 业务宿主先启(拓扑序 Activate + 调度)再启管理面(监听开放时桥已发布); diff --git a/Directory.Build.targets b/Directory.Build.targets index 2c2408a8a..df34cd0dc 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -4,7 +4,7 @@ false - );实例类型(含实例字段持有 +/// CapabilityRuntime 与实例方法调用 Compose——合法的实例组合根形态); +/// 静态方法仅收发 CapabilityRuntime 参数 / 返回值不构成组合根(无状态静态转发合法)。 +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class StaticCompositionRootAnalyzer : DiagnosticAnalyzer +{ + private const string CapabilityCompositionMetadataName = "GameFrameX.Capability.Hosting.Core.CapabilityComposition"; + private const string CapabilityRuntimeMetadataName = "GameFrameX.Capability.Hosting.Core.CapabilityRuntime"; + private const string CapabilityHostMetadataName = "GameFrameX.Capability.Hosting.Core.CapabilityHost"; + + private static readonly DiagnosticDescriptor Rule = new DiagnosticDescriptor( + "GFX0022", + "Static composition roots are forbidden: capability assembly must ride the single composition root", + "Static type '{0}' in assembly '{1}' acts as a static composition root ({2}); compose through CapabilityComposition from an instance composition root instead", + ArchitectureAnalyzerConstants.Category, + DiagnosticSeverity.Error, + true); + + /// 机制程序集名(其内的 CapabilityComposition 是无状态纯工厂入口,白名单豁免)。 + private const string MechanismAssemblyName = "GameFrameX.Capability.Hosting.Core"; + public override ImmutableArray SupportedDiagnostics + { + get { return ImmutableArray.Create(Rule); } + } + + /// + /// 注册静态类符号分析(装配状态面)与调用点分析(组合入口面)。 + /// + /// + /// Registers the static-type symbol analysis (the assembly-state face) and the invocation + /// analysis (the compose-entry face); the mechanism assembly and test assemblies are exempt. + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); + context.EnableConcurrentExecution(); + context.RegisterCompilationStartAction(compilationContext => + { + var compositionType = compilationContext.Compilation.GetTypeByMetadataName(CapabilityCompositionMetadataName); + var runtimeType = compilationContext.Compilation.GetTypeByMetadataName(CapabilityRuntimeMetadataName); + var hostType = compilationContext.Compilation.GetTypeByMetadataName(CapabilityHostMetadataName); + if (compositionType == null && runtimeType == null && hostType == null) + { + // 本编译未引用机制包:规则无对象。 + return; + } + + var mechanismAssemblyName = MechanismAssemblyName; + + compilationContext.RegisterSymbolAction(symbolContext => + { + var type = (INamedTypeSymbol)symbolContext.Symbol; + if (!type.IsStatic || type.TypeKind == TypeKind.Error || type.IsImplicitlyDeclared) + { + return; + } + + var assemblyName = type.ContainingAssembly.Identity.Name; + if (assemblyName == mechanismAssemblyName || ArchitectureSymbolFacts.ShouldIgnoreAssembly(assemblyName)) + { + return; + } + + foreach (var member in type.GetMembers()) + { + var memberType = member switch + { + IFieldSymbol field => field.Type, + IPropertySymbol property => property.Type, + _ => null, + }; + + if (memberType == null) + { + continue; + } + + if (SymbolEqualityComparer.Default.Equals(memberType, runtimeType)) + { + symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, member.Locations[0], type.Name, assemblyName, "static member holding CapabilityRuntime")); + return; + } + + if (SymbolEqualityComparer.Default.Equals(memberType, hostType)) + { + symbolContext.ReportDiagnostic(Diagnostic.Create(Rule, member.Locations[0], type.Name, assemblyName, "static member holding CapabilityHost")); + return; + } + } + }, SymbolKind.NamedType); + + if (compositionType == null) + { + return; + } + + compilationContext.RegisterOperationAction(operationContext => + { + var invocation = (Microsoft.CodeAnalysis.Operations.IInvocationOperation)operationContext.Operation; + var targetMethod = invocation.TargetMethod; + if (targetMethod == null || !string.Equals(targetMethod.Name, "Compose", System.StringComparison.Ordinal)) + { + return; + } + + var containingType = targetMethod.ContainingType; + if (containingType == null || !SymbolEqualityComparer.Default.Equals(containingType, compositionType)) + { + return; + } + + var callerType = operationContext.ContainingSymbol?.ContainingType; + if (callerType == null || !callerType.IsStatic || callerType.TypeKind == TypeKind.Error) + { + return; + } + + var assemblyName = callerType.ContainingAssembly.Identity.Name; + if (assemblyName == mechanismAssemblyName || ArchitectureSymbolFacts.ShouldIgnoreAssembly(assemblyName)) + { + return; + } + + operationContext.ReportDiagnostic(Diagnostic.Create(Rule, invocation.Syntax.GetLocation(), callerType.Name, assemblyName, "static entry invoking CapabilityComposition.Compose")); + }, OperationKind.Invocation); + }); + } +} diff --git a/GameFrameX.Config/ConfigComponent.cs b/GameFrameX.Config/ConfigComponent.cs index 36a6101a6..92365e63f 100644 --- a/GameFrameX.Config/ConfigComponent.cs +++ b/GameFrameX.Config/ConfigComponent.cs @@ -44,6 +44,11 @@ private ConfigComponent() Tables = new TablesComponent(); } + /// + /// 进程唯一实例的静态获取入口(过渡保留:请改经构造参数注入 实例—— + /// 宿主 / 模块持有实例引用传递;本实例即注入源的进程缺省)。 + /// + [Obsolete("静态单例入口过渡保留:请改用经构造参数注入的 ConfigComponent 实例(进程唯一实例即注入源)。Static singleton entry kept for transition; inject the ConfigComponent instance through constructors (this process-unique instance is the injection source).", false)] public static ConfigComponent Instance { get; } = new(); private TablesComponent Tables { get; } diff --git a/GameFrameX.Core/Events/EventDispatcher.cs b/GameFrameX.Core/Events/EventDispatcher.cs index 55baa2c53..8bf5222b0 100644 --- a/GameFrameX.Core/Events/EventDispatcher.cs +++ b/GameFrameX.Core/Events/EventDispatcher.cs @@ -3,7 +3,7 @@ // GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights // 均受中华人民共和国及相关国际法律法规保护。 // are protected by the laws of the People's Republic of China and relevant international regulations. -// 使用本项目须严格遵守相应法律法规及开源许可证之规定。 +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 // Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. // 本项目采用 Apache License 2.0 单协议分发, // This project is licensed solely under the Apache License 2.0, @@ -12,234 +12,70 @@ // 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 // 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! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! // 因基于本项目二次开发所产生的一切法律纠纷与责任, -// Any legal disputes and liabilities arising from secondary development based on this project -// 本项目组织与贡献者概不承担。 +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 // shall be borne solely by the developer; the project organization and contributors assume no responsibility. // GitHub 仓库:https://github.com/GameFrameX -// GitHub Repository: https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX // Gitee 仓库:https://gitee.com/GameFrameX -// Gitee Repository: https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX // CNB 仓库:https://cnb.cool/GameFrameX -// CNB Repository: https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX // 官方文档:https://gameframex.doc.alianblank.com/ // Official Documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== using GameFrameX.Core.Abstractions.Events; -using GameFrameX.Core.Abstractions; -using GameFrameX.Core.Actors; -using GameFrameX.Core.Actors.Impl; -using GameFrameX.Core.Components; -using GameFrameX.Core.Hotfix; -using GameFrameX.Foundation.Extensions; -using GameFrameX.Foundation.Logger; -using GameFrameX.Foundation.Localization.Core; -using GameFrameX.Foundation.Utility; -using GameFrameX.Utility; -using GameFrameX.Utility.Setting; namespace GameFrameX.Core.Events; /// -/// 事件分发类 - 负责处理游戏中所有事件的分发和处理 +/// 事件分发静态便捷层(过渡保留:转发 ,已标记过时并指向注入面)。 /// +/// +/// The static convenience layer for event dispatching (transitional: forwards to +/// and is marked obsolete, pointing at the +/// injection seam ). 组合根 / 宿主模块应注入 ; +/// 后续收敛版本迁移调用点后移除本层。 +/// Compositions inject ; the layer is removed once later +/// convergence versions migrate the call sites. +/// public static class EventDispatcher { /// - /// 在飞派发计数:Dispatch 触发后、派发任务(Actor 路径与全局路径)完成前递增, - /// 任务完成时递减;停机排空()以归零为完成判据。 - /// - private static int _inFlightDispatchCount; - /// - /// 分发事件到指定的Actor或全局监听器 + /// 分发事件到指定的Actor或全局监听器(静态便捷层:转发 )。 /// /// 目标Actor的唯一标识符,如果为无效值则分发到全局监听器 /// 事件携带的参数数据,绑定键取自其具体类型;无载荷事件须使用空标记类,禁止传null - /// 为 null 时抛出 + /// 为 null 时抛出 + [Obsolete("静态便捷层过渡保留:请改用注入的 IEventDispatcher 实例(进程缺省 GameEventDispatcher.ProcessDefault)。Static convenience layer kept for transition; use the injected IEventDispatcher instance (process default GameEventDispatcher.ProcessDefault) instead.", false)] public static void Dispatch(long actorId, GameEventArgs eventArgs) { - ArgumentNullException.ThrowIfNull(eventArgs); - - // 尝试获取目标Actor - var actor = ActorManager.GetActor(actorId); - if (actor != null) - { - // 派发完成信号:工作单元执行完、或入队被拒(Actor 已隔离 / 邮箱已停)时只计一次。 - // Dispatch completion signal: counted exactly once, whether the work unit ran or the enqueue was rejected. - var dispatchCompleted = 0; - void CompleteDispatch() - { - if (Interlocked.Exchange(ref dispatchCompleted, 1) == 0) - { - Interlocked.Decrement(ref _inFlightDispatchCount); - } - } - - // 用入队(而非 Tell)取得完成信号:Tell 在隔离/邮箱停止时静默丢弃工作单元, - // 在飞计数将永久滞留,停机排空每次都空等满超时;EnqueueAsync 仍经 Actor 邮箱 FIFO 串行执行。 - // Enqueue (instead of Tell) provides the completion signal: Tell silently drops the work unit - // when the actor is quarantined or its mailbox stopped, leaking the in-flight counter; EnqueueAsync - // still runs the work unit serially through the actor mailbox in FIFO order. - Interlocked.Increment(ref _inFlightDispatchCount); - var dispatchTask = actor.WorkerActor.EnqueueAsync(async () => - { - try - { - await DispatchToActorAsync(actor, actorId, eventArgs); - } - finally - { - CompleteDispatch(); - } - }, callChainId: WorkerActor.NextChainId(), discard: true, timeOut: GlobalSettings.CurrentSetting.ActorTimeOut); - - _ = dispatchTask.ContinueWith(_ => CompleteDispatch(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); - return; - } - - // 目标Actor不在内存中:按监听器所属Actor分别投递串行执行,不在线程池上执行监听器 - DispatchGlobal(actorId, eventArgs); + GameEventDispatcher.ProcessDefault.Dispatch(actorId, eventArgs); } /// - /// 等待所有在飞事件派发完成(停机排空用,C367)。 + /// 等待所有在飞事件派发完成(停机排空用;静态便捷层:转发 )。 /// - /// - /// Polls the in-flight dispatch counter until it reaches zero or the timeout elapses. - /// 返回 false 表示超时仍有派发未完成,不抛异常——调用方记日志后放行停机。 - /// /// 最长等待时限。 /// 时限内全部派发完成返回 true;超时仍有在飞派发返回 false。 - public static async Task WaitAllDispatchedAsync(TimeSpan timeout) + [Obsolete("静态便捷层过渡保留:请改用注入的 IEventDispatcher 实例(进程缺省 GameEventDispatcher.ProcessDefault)。Static convenience layer kept for transition; use the injected IEventDispatcher instance (process default GameEventDispatcher.ProcessDefault) instead.", false)] + public static Task WaitAllDispatchedAsync(TimeSpan timeout) { - var deadlineUtcMilliseconds = TimerHelper.UnixTimeMilliseconds() + (long)timeout.TotalMilliseconds; - while (Interlocked.CompareExchange(ref _inFlightDispatchCount, 0, 0) > 0) - { - if (TimerHelper.UnixTimeMilliseconds() >= deadlineUtcMilliseconds) - { - return false; - } - - await Task.Delay(20); - } - - return true; + return GameEventDispatcher.ProcessDefault.WaitAllDispatchedAsync(timeout); } /// - /// 在目标 Actor 上下文内分发事件:取出该 Actor 类型注册的监听器并逐个调用其事件处理方法。 + /// 在目标 Actor 上下文内分发事件(静态便捷层:转发 同名内部路径,仓内扩展入口共用)。 /// /// 目标 Actor /// 目标Actor的唯一标识符 /// 事件携带的参数数据,不为null /// 异步任务 - internal static async Task DispatchToActorAsync(IActor actor, long actorId, GameEventArgs eventArgs) + internal static Task DispatchToActorAsync(GameFrameX.Core.Abstractions.IActor actor, long actorId, GameEventArgs eventArgs) { - // 事件需要在本actor内执行,不可多线程执行,所以不能使用Task.WhenAll来处理 - // 获取该Actor类型下注册的所有事件监听器 - var listeners = HotfixManager.Resolver.FindListeners(actor.Type, eventArgs.GetType()); - if (listeners.IsNullOrEmpty()) - { - // Localization: Core.EventDispatcher.DispatchNoListeners - EventDispatcher.Dispatch Actor {0} 类型:{1} 事件类型:{2} 没有找到任何监听者 - LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchNoListeners, actorId, actor.Type, eventArgs.GetType().Name)); - return; - } - - // 遍历所有监听器并执行事件处理 - foreach (var listener in listeners) - { - await DispatchListenerInActorAsync(actor, listener, actorId, eventArgs); - } - } - - /// - /// 全局分发:目标 Actor 不在内存中时,把每个监听器投递到其所属全局 Actor 的消息队列中串行执行; - /// 监听器属于单个玩家 Actor 类型(或所属全局 Actor 尚未创建)时记 Warning 后跳过,绝不以空代理调用监听器。 - /// - /// 原始目标Actor的唯一标识符(仅用于日志定位) - /// 事件携带的参数数据,不为null - private static void DispatchGlobal(long actorId, GameEventArgs eventArgs) - { - // 事件需要在本actor内执行,不可多线程执行,所以不能使用Task.WhenAll来处理 - // 获取全局注册的事件监听器(聚合全部Actor类型) - var listeners = HotfixManager.Resolver.FindListeners(eventArgs.GetType()); - if (listeners.IsNullOrEmpty()) - { - // Localization: Core.EventDispatcher.DispatchNoListeners - EventDispatcher.Dispatch Actor {0} 类型:{1} 事件类型:{2} 没有找到任何监听者 - LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchNoListeners, actorId, ActorIdGenerator.GetActorType(actorId), eventArgs.GetType().Name)); - return; - } - - // 遍历所有监听器:按所属Actor类型分别投递(同一Actor上的监听器按投递顺序FIFO串行) - foreach (var listener in listeners) - { - var componentType = HotfixManager.Resolver.GetComponentType(listener.AgentType); - if (componentType == null) - { - // Localization: Core.EventDispatcher.DispatchOwnerActorNotLoaded - EventDispatcher.Dispatch Actor {0} 事件类型:{1} 监听器 {2} 所属 Actor 不在内存中,已跳过 - LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchOwnerActorNotLoaded, actorId, eventArgs.GetType().Name, listener.GetType().FullName)); - continue; - } - - var ownerActorType = ComponentRegister.GetActorType(componentType); - Actor ownerActor = null; - if (ownerActorType > GlobalConst.ActorTypeSeparator) - { - // 全局Actor在启动期以默认服务器ID创建,这里用同一ID反查 - ownerActor = ActorManager.GetActor(ActorIdGenerator.GetActorId(ownerActorType)); - } - - if (ownerActor == null) - { - // 监听器属于单个玩家Actor类型(目标Actor已回收)或全局Actor尚未创建:跳过,不再以空代理执行 - // Localization: Core.EventDispatcher.DispatchOwnerActorNotLoaded - EventDispatcher.Dispatch Actor {0} 事件类型:{1} 监听器 {2} 所属 Actor 不在内存中,已跳过 - LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchOwnerActorNotLoaded, actorId, eventArgs.GetType().Name, listener.GetType().FullName)); - continue; - } - - // 每个监听器投递计入在飞计数:仍经所属 Actor 邮箱 FIFO 串行执行,但用 EnqueueAsync 取得完成信号, - // 停机排空可等待;入队被拒(隔离/邮箱停止)由任务终态统一回落计数。 - // Each listener dispatch counts as in-flight: still serialized through the owner actor's mailbox - // in FIFO order, but EnqueueAsync provides the completion signal for shutdown drain; a rejected - // enqueue (quarantined/stopped mailbox) settles the counter via the task's final state. - Interlocked.Increment(ref _inFlightDispatchCount); - var listenerDispatchTask = ownerActor.WorkerActor.EnqueueAsync(() => DispatchListenerInActorAsync(ownerActor, listener, actorId, eventArgs), callChainId: WorkerActor.NextChainId(), discard: true, timeOut: GlobalSettings.CurrentSetting.ActorTimeOut); - _ = listenerDispatchTask.ContinueWith(_ => Interlocked.Decrement(ref _inFlightDispatchCount), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); - } - } - - /// - /// 在 Actor 上下文内执行单个监听器:取出该监听器代理类型的组件代理并调用其事件处理方法,异常就地记录。 - /// - /// 监听器所属 Actor - /// 事件监听器 - /// 原始目标Actor的唯一标识符(仅用于日志定位) - /// 事件携带的参数数据,不为null - /// 异步任务 - private static async Task DispatchListenerInActorAsync(IActor actor, IEventListener listener, long actorId, GameEventArgs eventArgs) - { - // 获取监听器对应的组件代理 - var componentAgent = await actor.GetComponentAgentAsync(listener.AgentType, false); - - if (componentAgent == null) - { - // 组件未注册到该 Actor(isNew:false 未命中):显式跳过并告警,绝不以 null 代理调用监听器 - // Localization: Core.EventDispatcher.DispatchOwnerActorNotLoaded - EventDispatcher.Dispatch Actor {0} 事件类型:{1} 监听器 {2} 所属 Actor 不在内存中,已跳过 - LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchOwnerActorNotLoaded, actorId, eventArgs.GetType().Name, listener.GetType().FullName)); - return; - } - try - { - // 调用监听器的事件处理方法 - await listener.HandleEventAsync(componentAgent, eventArgs); - } - catch (Exception exception) - { - // 捕获并记录事件处理过程中的异常 - // Localization: Core.EventDispatcher.DispatchError - EventDispatcher.Dispatch Actor {0} {1} 异常: {2} - LogHelper.Error(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchError, actorId, eventArgs.GetType().Name, exception)); - } + return GameEventDispatcher.DispatchToActorAsync(actor, actorId, eventArgs); } -} \ No newline at end of file +} diff --git a/GameFrameX.Core/Events/GameEventDispatcher.cs b/GameFrameX.Core/Events/GameEventDispatcher.cs new file mode 100644 index 000000000..790eb7996 --- /dev/null +++ b/GameFrameX.Core/Events/GameEventDispatcher.cs @@ -0,0 +1,276 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using GameFrameX.Core.Abstractions.Events; +using GameFrameX.Core.Abstractions; +using GameFrameX.Core.Actors; +using GameFrameX.Core.Actors.Impl; +using GameFrameX.Core.Components; +using GameFrameX.Core.Hotfix; +using GameFrameX.Foundation.Extensions; +using GameFrameX.Foundation.Logger; +using GameFrameX.Foundation.Localization.Core; +using GameFrameX.Foundation.Utility; +using GameFrameX.Utility; +using GameFrameX.Utility.Setting; + +namespace GameFrameX.Core.Events; + +/// +/// 事件分发实例核(在飞计数 / Actor 路径与全局路径派发的实现承载;静态便捷层 +/// 经 转发同核,双层面共享状态不分裂)。 +/// +/// +/// The event-dispatch instance core (carries the in-flight counter and both the actor-path and +/// global-path dispatching; the static convenience layer forwards +/// through , so both layers share the same state and never split). +/// +public sealed class GameEventDispatcher : IEventDispatcher +{ + /// + /// 进程缺省实例(静态便捷层 的转发目标;组合根注入用同一实例)。 + /// + /// + /// The process-default instance (the forwarding target of the static convenience layer + /// ; compositions inject this very instance). + /// + public static readonly GameEventDispatcher ProcessDefault = new GameEventDispatcher(); + + /// + /// 在飞派发计数:Dispatch 触发后、派发任务(Actor 路径与全局路径)完成前递增, + /// 任务完成时递减;停机排空()以归零为完成判据。 + /// + /// + /// The in-flight dispatch counter: incremented when a dispatch fires and decremented when its + /// task (actor path or global path) completes; the shutdown drain + /// () treats zero as completion. + /// + private int _inFlightDispatchCount; + + /// + /// 初始化 (公开构造:实例可经注入面独立构造用于隔离测试)。 + /// + /// + /// Initializes (public constructor: instances can be built + /// independently through the injection seam for isolated tests). + /// + public GameEventDispatcher() + { + } + + /// + /// 分发事件到指定的Actor或全局监听器。 + /// + /// 目标Actor的唯一标识符,如果为无效值则分发到全局监听器 + /// 事件携带的参数数据,绑定键取自其具体类型;无载荷事件须使用空标记类,禁止传null + /// 为 null 时抛出 + public void Dispatch(long actorId, GameEventArgs eventArgs) + { + ArgumentNullException.ThrowIfNull(eventArgs); + + // 尝试获取目标Actor + var actor = ActorManager.GetActor(actorId); + if (actor != null) + { + // 派发完成信号:工作单元执行完、或入队被拒(Actor 已隔离 / 邮箱已停)时只计一次。 + // Dispatch completion signal: counted exactly once, whether the work unit ran or the enqueue was rejected. + var dispatchCompleted = 0; + void CompleteDispatch() + { + if (Interlocked.Exchange(ref dispatchCompleted, 1) == 0) + { + Interlocked.Decrement(ref _inFlightDispatchCount); + } + } + + // 用入队(而非 Tell)取得完成信号:Tell 在隔离/邮箱停止时静默丢弃工作单元, + // 在飞计数将永久滞留,停机排空每次都空等满超时;EnqueueAsync 仍经 Actor 邮箱 FIFO 串行执行。 + // Enqueue (instead of Tell) provides the completion signal: Tell silently drops the work unit + // when the actor is quarantined or its mailbox stopped, leaking the in-flight counter; EnqueueAsync + // still runs the work unit serially through the actor mailbox in FIFO order. + Interlocked.Increment(ref _inFlightDispatchCount); + var dispatchTask = actor.WorkerActor.EnqueueAsync(async () => + { + try + { + await DispatchToActorAsync(actor, actorId, eventArgs); + } + finally + { + CompleteDispatch(); + } + }, callChainId: WorkerActor.NextChainId(), discard: true, timeOut: GlobalSettings.CurrentSetting.ActorTimeOut); + + _ = dispatchTask.ContinueWith(_ => CompleteDispatch(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + return; + } + + // 目标Actor不在内存中:按监听器所属Actor分别投递串行执行,不在线程池上执行监听器 + DispatchGlobal(actorId, eventArgs); + } + + /// + /// 等待所有在飞事件派发完成(停机排空用)。 + /// + /// + /// Polls the in-flight dispatch counter until it reaches zero or the timeout elapses. + /// 返回 false 表示超时仍有派发未完成,不抛异常——调用方记日志后放行停机。 + /// + /// 最长等待时限。 + /// 时限内全部派发完成返回 true;超时仍有在飞派发返回 false。 + public async Task WaitAllDispatchedAsync(TimeSpan timeout) + { + var deadlineUtcMilliseconds = TimerHelper.UnixTimeMilliseconds() + (long)timeout.TotalMilliseconds; + while (Interlocked.CompareExchange(ref _inFlightDispatchCount, 0, 0) > 0) + { + if (TimerHelper.UnixTimeMilliseconds() >= deadlineUtcMilliseconds) + { + return false; + } + + await Task.Delay(20); + } + + return true; + } + + /// + /// 在目标 Actor 上下文内分发事件:取出该 Actor 类型注册的监听器并逐个调用其事件处理方法。 + /// + /// 目标 Actor + /// 目标Actor的唯一标识符 + /// 事件携带的参数数据,不为null + /// 异步任务 + internal static async Task DispatchToActorAsync(IActor actor, long actorId, GameEventArgs eventArgs) + { + // 事件需要在本actor内执行,不可多线程执行,所以不能使用Task.WhenAll来处理 + // 获取该Actor类型下注册的所有事件监听器 + var listeners = HotfixManager.Resolver.FindListeners(actor.Type, eventArgs.GetType()); + if (listeners.IsNullOrEmpty()) + { + // Localization: Core.EventDispatcher.DispatchNoListeners - EventDispatcher.Dispatch Actor {0} 类型:{1} 事件类型:{2} 没有找到任何监听者 + LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchNoListeners, actorId, actor.Type, eventArgs.GetType().Name)); + return; + } + + // 遍历所有监听器并执行事件处理 + foreach (var listener in listeners) + { + await DispatchListenerInActorAsync(actor, listener, actorId, eventArgs); + } + } + + /// + /// 全局分发:目标 Actor 不在内存中时,把每个监听器投递到其所属全局 Actor 的消息队列中串行执行; + /// 监听器属于单个玩家 Actor 类型(或所属全局 Actor 尚未创建)时记 Warning 后跳过,绝不以空代理调用监听器。 + /// + /// 原始目标Actor的唯一标识符(仅用于日志定位) + /// 事件携带的参数数据,不为null + private void DispatchGlobal(long actorId, GameEventArgs eventArgs) + { + // 事件需要在本actor内执行,不可多线程执行,所以不能使用Task.WhenAll来处理 + // 获取全局注册的事件监听器(聚合全部Actor类型) + var listeners = HotfixManager.Resolver.FindListeners(eventArgs.GetType()); + if (listeners.IsNullOrEmpty()) + { + LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchNoListeners, actorId, ActorIdGenerator.GetActorType(actorId), eventArgs.GetType().Name)); + return; + } + + // 遍历所有监听器:按所属Actor类型分别投递(同一Actor上的监听器按投递顺序FIFO串行) + foreach (var listener in listeners) + { + var componentType = HotfixManager.Resolver.GetComponentType(listener.AgentType); + if (componentType == null) + { + // Localization: Core.EventDispatcher.DispatchOwnerActorNotLoaded - EventDispatcher.Dispatch Actor {0} 事件类型:{1} 监听器 {2} 所属 Actor 不在内存中,已跳过 + LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchOwnerActorNotLoaded, actorId, eventArgs.GetType().Name, listener.GetType().FullName)); + continue; + } + + var ownerActorType = ComponentRegister.GetActorType(componentType); + Actor ownerActor = null; + if (ownerActorType > GlobalConst.ActorTypeSeparator) + { + // 全局Actor在启动期以默认服务器ID创建,这里用同一ID反查 + ownerActor = ActorManager.GetActor(ActorIdGenerator.GetActorId(ownerActorType)); + } + + if (ownerActor == null) + { + // 监听器属于单个玩家Actor类型(目标Actor已回收)或全局Actor尚未创建:跳过,不再以空代理执行 + // Localization: Core.EventDispatcher.DispatchOwnerActorNotLoaded - EventDispatcher.Dispatch Actor {0} 事件类型:{1} 监听器 {2} 所属 Actor 不在内存中,已跳过 + LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchOwnerActorNotLoaded, actorId, eventArgs.GetType().Name, listener.GetType().FullName)); + continue; + } + + // 每个监听器投递计入在飞计数:仍经所属 Actor 邮箱 FIFO 串行执行,但用 EnqueueAsync 取得完成信号, + // 停机排空可等待;入队被拒(隔离/邮箱停止)由任务终态统一回落计数。 + // Each listener dispatch counts as in-flight: still serialized through the owner actor's mailbox + // in FIFO order, but EnqueueAsync provides the completion signal for shutdown drain; a rejected + // enqueue (quarantined/stopped mailbox) settles the counter via the task's final state. + Interlocked.Increment(ref _inFlightDispatchCount); + var listenerDispatchTask = ownerActor.WorkerActor.EnqueueAsync(() => DispatchListenerInActorAsync(ownerActor, listener, actorId, eventArgs), callChainId: WorkerActor.NextChainId(), discard: true, timeOut: GlobalSettings.CurrentSetting.ActorTimeOut); + _ = listenerDispatchTask.ContinueWith(_ => Interlocked.Decrement(ref _inFlightDispatchCount), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + } + } + + /// + /// 在 Actor 上下文内执行单个监听器:取出该监听器代理类型的组件代理并调用其事件处理方法,异常就地记录。 + /// + /// 监听器所属 Actor + /// 事件监听器 + /// 原始目标Actor的唯一标识符(仅用于日志定位) + /// 事件携带的参数数据,不为null + /// 异步任务 + private static async Task DispatchListenerInActorAsync(IActor actor, IEventListener listener, long actorId, GameEventArgs eventArgs) + { + // 获取监听器对应的组件代理 + var componentAgent = await actor.GetComponentAgentAsync(listener.AgentType, false); + + if (componentAgent == null) + { + // 组件未注册到该 Actor(isNew:false 未命中):显式跳过并告警,绝不以 null 代理调用监听器 + // Localization: Core.EventDispatcher.DispatchOwnerActorNotLoaded - EventDispatcher.Dispatch Actor {0} 事件类型:{1} 监听器 {2} 所属 Actor 不在内存中,已跳过 + LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchOwnerActorNotLoaded, actorId, eventArgs.GetType().Name, listener.GetType().FullName)); + return; + } + try + { + // 调用监听器的事件处理方法 + await listener.HandleEventAsync(componentAgent, eventArgs); + } + catch (Exception exception) + { + // 捕获并记录事件处理过程中的异常 + // Localization: Core.EventDispatcher.DispatchError - EventDispatcher.Dispatch Actor {0} {1} 异常: {2} + LogHelper.Error(LocalizationService.GetString(Localization.Keys.Core.EventDispatcher.DispatchError, actorId, eventArgs.GetType().Name, exception)); + } + } +} diff --git a/GameFrameX.Core/Events/IEventDispatcher.cs b/GameFrameX.Core/Events/IEventDispatcher.cs new file mode 100644 index 000000000..50478dea7 --- /dev/null +++ b/GameFrameX.Core/Events/IEventDispatcher.cs @@ -0,0 +1,61 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using GameFrameX.Core.Abstractions.Events; + +namespace GameFrameX.Core.Events; + +/// +/// 事件分发契约( 实例核的注入面):分发到目标 Actor 或全局监听器, +/// 并提供停机排空等待。 +/// +/// +/// The event-dispatch contract (the injection seam over the instance +/// core): dispatches to the target actor or the global listeners, plus the shutdown-drain wait. +/// 组合根 / 宿主模块经构造参数注入本接口;静态便捷层 为过渡转发。 +/// Compositions inject this interface through constructors; the static convenience layer +/// forwards during the transition. +/// +public interface IEventDispatcher +{ + /// + /// 分发事件到指定的Actor或全局监听器。 + /// + /// 目标Actor的唯一标识符,如果为无效值则分发到全局监听器 + /// 事件携带的参数数据,绑定键取自其具体类型;无载荷事件须使用空标记类,禁止传null + /// 为 null 时抛出 + void Dispatch(long actorId, GameEventArgs eventArgs); + + /// + /// 等待所有在飞事件派发完成(停机排空用)。 + /// + /// 最长等待时限。 + /// 时限内全部派发完成返回 true;超时仍有在飞派发返回 false。 + Task WaitAllDispatchedAsync(TimeSpan timeout); +} diff --git a/GameFrameX.Core/Hotfix/HotfixManager.cs b/GameFrameX.Core/Hotfix/HotfixManager.cs index ff40bf921..2bc744410 100644 --- a/GameFrameX.Core/Hotfix/HotfixManager.cs +++ b/GameFrameX.Core/Hotfix/HotfixManager.cs @@ -2,27 +2,27 @@ // GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 // GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights // 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the People's Republic of China and related international regulations. -// 使用本项目须严格遵守相应法律法规之开源许可证之规定。 +// 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. +// please refer to the LICENSE file in the root directory of the source code for the full license text. // 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 // It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, // 侵犯他人合法权益等法律法规所禁止的行为! -// or infringe upon the legitimate rights or interests of others, as prohibited by laws and regulations. +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! // 因基于本项目二次开发所产生的一切法律纠纷与责任, // Any legal disputes or liabilities arising from secondary development based on this project -// 本项目组织与贡献者概不承担。 +// 本组织与贡献者概不承担。 // shall be borne solely by the developer; the project organization and contributors assume no responsibility. // GitHub 仓库:https://github.com/GameFrameX -// GitHub Repository: https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX // Gitee 仓库:https://gitee.com/GameFrameX -// Gitee Repository: https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX // CNB 仓库:https://cnb.cool/GameFrameX -// CNB Repository: https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX // 官方文档:https://gameframex.doc.alianblank.com/ // Official Documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== @@ -39,299 +39,193 @@ namespace GameFrameX.Core.Hotfix; /// -/// 热更新管理器——static 转发门面。 -/// Hotfix manager — a static forwarding facade. +/// 热更新管理器静态便捷层(过渡保留:转发 ,公共成员已标记过时并指向注入面)。 /// /// -/// 职责边界:装载入口与策略(同路径幂等守卫、10min 宽限常量、目录兜底)留在此处; -/// ALC 基建与退役编排机制由 GameFrameX.Utility.Hotload.CollectibleAssemblyHost<TModule> 提供; -/// 全部解析路由经 ( 契约实例)承载,Core 子系统与测试替身均依赖该契约。 -/// Responsibility split: load entries and policies (the same-path idempotency guard, the 10-minute -/// grace constant, directory ensuring) stay here; ALC infrastructure and retirement orchestration live in -/// GameFrameX.Utility.Hotload.CollectibleAssemblyHost<TModule>; all resolution routing goes through -/// (an contract instance) consumed by Core subsystems and test doubles. -/// -/// 同路径幂等守卫:单进程多 Role(--AllInOne)形态下首个 Role 装载热更模块后,其余 Role 经装载入口的重复调用 -/// 在此短路返回,避免重复的可收集 ALC 装载制造跨 ALC 的类型身份割裂(旧模块 agent 的激活/转型随竞态随机失败); -/// 路径由 统一拼装(进程内 CWD 不变),字符串等值即路径等值。 -/// Same-path idempotency guard: in the single-process multi-role (--AllInOne) shape, once the first role has loaded -/// the hotfix module, repeated load calls from the remaining roles short-circuit here — avoiding duplicate -/// collectible-ALC loads that would create cross-ALC type identity splits (agent activation/casts on old modules -/// would fail racily); paths are built uniformly by (the -/// CWD never changes in-process), so string equality is path equality. -/// +/// The static convenience layer of the hotfix manager (transitional: forwards to +/// ; the public members are marked obsolete, pointing at +/// the injection seam). 组合根 / 宿主模块应注入 实例;Core 子系统解析路由 +/// 仍经内部 缝(转发同核);后续收敛版本迁移调用点后移除本层。 +/// Compositions inject the instance; Core-subsystem resolution routing +/// keeps riding the internal seam (same core); the layer is removed once +/// later convergence versions migrate the call sites. /// public static class HotfixManager { /// - /// 热更宿主实例:当前模块指针与退役链的持有者(生产唯一装配)。 - /// The hotfix host instance: owner of the current-module pointer and the retirement chain (the single production wiring). - /// - private static readonly HotfixHost Host = new HotfixHost(); - - /// - /// 解析契约当前实现:默认为生产 ;测试经 注入替身(传 null 复原)。 - /// The current resolution-contract implementation: the production by default; tests inject a - /// substitute via (pass null to restore). - /// - private static IHotfixResolver _resolver = Host; - - /// - /// 基础配置信息 - /// Base application setting - /// - private static AppSetting _baseSetting; - - /// - /// 热更解析契约注入缝:Core 子系统经此依赖抽象而非 static 实现;亦为测试替身入口。 - /// The hotfix resolution-contract seam: Core subsystems depend on the abstraction instead of the static - /// implementation; also the entry point for test doubles. + /// 热更解析契约注入缝(静态便捷层:转发 ;Core 子系统与测试替身依赖该契约)。 + /// The hotfix resolution-contract seam (static forward of ). /// internal static IHotfixResolver Resolver { - get { return _resolver; } + get { return HotfixRuntime.ProcessDefault.Resolver; } } /// - /// 注入/复原解析契约实现(测试专用):传 null 复原为生产宿主。 - /// Injects/restores the resolution-contract implementation (testing only): passing null restores the production host. + /// 注入/复原解析契约实现(测试专用;静态便捷层转发 )。 + /// Injects/restores the resolution-contract implementation (testing only; static forward). /// /// 替身实现;null 复原 / The substitute; null restores. internal static void SetResolverForTesting(IHotfixResolver resolver) { - _resolver = resolver ?? Host; + HotfixRuntime.ProcessDefault.SetResolverForTesting(resolver); } /// - /// 热更新程序集 - /// The hotfix assembly + /// 热更新程序集(静态便捷层:转发 )。 + /// The hotfix assembly (static forward). /// + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static Assembly HotfixAssembly { - get { return Resolver.HotfixAssembly; } + get { return HotfixRuntime.ProcessDefault.HotfixAssembly; } } /// - /// 最近一次热更新重载的时间 - /// The time of the most recent hot reload + /// 最近一次热更新重载的时间(静态便捷层:转发 )。 + /// The time of the most recent hot reload (static forward). /// + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static DateTime ReloadTime { - get { return Host.ReloadTime; } + get { return HotfixRuntime.ProcessDefault.ReloadTime; } } /// - /// 加载热更新模块(同步入口)。 - /// Loads the hotfix module (synchronous entry). + /// 加载热更新模块(同步入口;静态便捷层:转发 )。 + /// Loads the hotfix module (synchronous entry; static forward). /// /// 应用程序配置 / The application setting. - /// 装载参数(null 走默认值:目录 hotfix + GameFrameX.Hotfix.dll) / Load options (null for defaults: the hotfix directory plus GameFrameX.Hotfix.dll). + /// 装载参数 / Load options. /// 返回是否加载成功 / Whether the load succeeded. + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static bool LoadHotfix(AppSetting setting, HotfixLoadOptions options = null) { - var loadOptions = options ?? new HotfixLoadOptions(); - var path = loadOptions.ResolveAssemblyFilePath(); - if (setting != null) - { - _baseSetting = setting; - } - - // 同路径幂等判重:当前模块即从该路径装载时直接返回成功,避免重复的可收集 ALC 装载 - //(单进程多 Role 形态下,后续 Role 对同一热更 DLL 的重复装载会制造跨 ALC 的类型身份割裂, - // 旧模块 agent 的激活/转型随竞态随机失败;进程内同一 DLL 只装载一次) - if (Host.IsSamePathLoaded(path)) - { - return true; - } - - // 装载前幂等确保目录存在(历史由调用方各自兜底创建,收敛为装载入口自身的前置条件) - EnsureHotfixDirectory(path); - var hotfixModule = new HotfixModule(path, loadOptions); - var reload = Host.CurrentModule != null; - // 起服时失败会有异常抛出 - var success = hotfixModule.Init(reload); - if (!success) - { - return false; - } - - if (reload) - { - // 补退役:与 LoadHotfixModuleAsync 路径对齐——旧模块进入退役链(宽限排空 + 卸载 GC 验证由模块链承担), - // 否则旧可收集 ALC 永不卸载,每次同步重载泄漏一份完整热更程序集内存 - // Retire the old module to align with the LoadHotfixModuleAsync path — it joins the retirement chain - // (grace drain plus unload GC verification belong to the module chain); without this the old collectible - // ALC is never unloaded, leaking a full hotfix assembly per synchronous reload - Host.Retire(HotfixHost.RetirementGracePeriod); - } - - // 同步路径保持历史行为:仅切换当前模块指针与注册,不回调桥接 - // Synchronous path keeps historical behavior: swap and register the current module only — no bridge callback - Host.RegisterCurrent(hotfixModule); - return true; + return HotfixRuntime.ProcessDefault.LoadHotfix(setting, options); } /// - /// 加载热更新模块(重载入口:旧模块退役编排 + 桥接回调)。 - /// Loads the hotfix module (reload entry: old-module retirement orchestration plus bridge callback). + /// 加载热更新模块(重载入口;静态便捷层:转发 )。 + /// Loads the hotfix module (reload entry; static forward). /// /// 应用程序配置 / The application setting. - /// 装载参数(null 走默认值) / Load options (null for defaults). + /// 装载参数 / Load options. /// 返回是否加载成功 / Whether the load succeeded. - public static async Task LoadHotfixModuleAsync(AppSetting setting, HotfixLoadOptions options = null) + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] + public static Task LoadHotfixModuleAsync(AppSetting setting, HotfixLoadOptions options = null) { - var loadOptions = options ?? new HotfixLoadOptions(); - var path = loadOptions.ResolveAssemblyFilePath(); - if (setting != null) - { - _baseSetting = setting; - } - - // 同路径幂等判重:当前模块即从该路径装载时直接返回成功,避免重复的可收集 ALC 装载 - //(热更重载总是指向新 version 子目录;同路径「重载」没有可观测收益,只会制造跨 ALC 类型身份割裂) - if (Host.IsSamePathLoaded(path)) - { - return true; - } - - // 装载前幂等确保目录存在(历史由调用方各自兜底创建,收敛为装载入口自身的前置条件) - EnsureHotfixDirectory(path); - var hotfixModule = new HotfixModule(path, loadOptions); - var reload = Host.CurrentModule != null; - // 起服时失败会有异常抛出 - var success = hotfixModule.Init(reload); - if (!success) - { - return false; - } - - return await Host.LoadAsync(hotfixModule, _baseSetting, reload); + return HotfixRuntime.ProcessDefault.LoadHotfixModuleAsync(setting, options); } /// - /// 停止热更新模块 - /// Stops the hotfix module + /// 停止热更新模块(静态便捷层:转发 )。 + /// Stops the hotfix module (static forward). /// /// 停止原因 / The stop reason. /// 停止任务 / The stop task. + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static Task StopAsync(string message = "") { - return Host.StopAsync(message); + return HotfixRuntime.ProcessDefault.StopAsync(message); } /// - /// 获取组件的代理实例 - /// Gets the agent instance for a component + /// 获取组件的代理实例(静态便捷层:转发 )。 + /// Gets the agent instance for a component (static forward). /// /// 组件实例 / The component instance. /// 引用程序集类型 / A type from the caller's hotfix assembly. /// 代理类型 / The agent type. /// 返回代理实例 / The agent instance. + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static T GetAgent(BaseComponent component, Type refAssemblyType) where T : class, IComponentAgent { - return Resolver.GetAgent(component, refAssemblyType); + return HotfixRuntime.ProcessDefault.GetAgent(component, refAssemblyType); } /// - /// 获取RPC处理器实例。 - /// Gets the RPC handler instance. + /// 获取RPC处理器实例(静态便捷层:转发 )。 + /// Gets the RPC handler instance (static forward). /// - /// 请求消息的类型。/ The request message type. - /// 对应的 实例,如果未找到则返回 null。/ The matching , or null when absent. + /// 请求消息的类型 / The request message type. + /// 对应的 实例,如果未找到则返回 null / The matching handler, or null when absent. + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static IMessageHandler GetRpcHandler(Type type) { - return Resolver.GetRpcHandler(type); + return HotfixRuntime.ProcessDefault.GetRpcHandler(type); } /// - /// 获取消息处理器 - /// Gets the message handler + /// 获取消息处理器(静态便捷层:转发 )。 + /// Gets the message handler (static forward). /// /// 消息ID / The message identifier. /// 返回对应的消息处理器 / The matching handler. + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static IMessageHandler GetMessageHandler(int msgId) { - return Resolver.GetMessageHandler(msgId); + return HotfixRuntime.ProcessDefault.GetMessageHandler(msgId); } /// - /// 获取HTTP消息处理器 - /// Gets the HTTP handler + /// 获取HTTP消息处理器(静态便捷层:转发 )。 + /// Gets the HTTP handler (static forward). /// /// HTTP命令 / The HTTP command. /// 返回对应HTTP处理器 / The matching HTTP handler. + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static BaseHttpHandler GetHttpHandler(string cmd) { - return Resolver.GetHttpHandler(cmd); + return HotfixRuntime.ProcessDefault.GetHttpHandler(cmd); } /// - /// 获取所有HTTP消息处理器列表 - /// Gets the list of all HTTP handlers + /// 获取所有HTTP消息处理器列表(静态便捷层:转发 )。 + /// Gets the list of all HTTP handlers (static forward). /// /// 返回HTTP处理器列表 / The HTTP handler list. + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static List GetListHttpHandler() { - return Resolver.GetListHttpHandler(); + return HotfixRuntime.ProcessDefault.GetListHttpHandler(); } /// - /// 获取指定Actor类型和事件参数类型的事件监听器列表 - /// Gets event listeners for the given actor type and event-args type + /// 获取指定Actor类型和事件参数类型的事件监听器列表(静态便捷层:转发 )。 + /// Gets event listeners for the given actor type and event-args type (static forward). /// /// Actor类型 / The actor type. /// 事件参数类型(事件绑定键) / The event-args type (the event binding key). /// 返回监听器列表,如果没有则空列表 / The listener list; empty when none. + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static List FindListeners(ushort actorType, Type eventArgsType) { - return Resolver.FindListeners(actorType, eventArgsType); + return HotfixRuntime.ProcessDefault.FindListeners(actorType, eventArgsType); } /// - /// 获取指定事件参数类型的事件监听器列表 - /// Gets event listeners for the given event-args type + /// 获取指定事件参数类型的事件监听器列表(静态便捷层:转发 )。 + /// Gets event listeners for the given event-args type (static forward). /// /// 事件参数类型(事件绑定键) / The event-args type (the event binding key). /// 返回监听器列表,如果没有则空列表 / The listener list; empty when none. + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static List FindListeners(Type eventArgsType) { - return Resolver.FindListeners(eventArgsType); + return HotfixRuntime.ProcessDefault.FindListeners(eventArgsType); } /// - /// 获取指定类型的实例 - /// 主要用于获取Event,Timer, Schedule的Handler实例 - /// Gets an instance of the given type, mainly Event/Timer/Schedule handler instances + /// 获取指定类型的实例(静态便捷层:转发 )。 + /// Gets an instance of the given type (static forward). /// /// 实例类型 / The instance type. /// 类型名称 / The type name. /// 引用程序集类型 / A type from the caller's hotfix assembly. /// 返回指定类型的实例,如果类型名称为空则返回默认值 / The instance, or default for an empty type name. + [Obsolete("静态便捷层过渡保留:请改用注入的 HotfixRuntime 实例(进程缺省 HotfixRuntime.ProcessDefault)。Static convenience layer kept for transition; use the injected HotfixRuntime instance (process default HotfixRuntime.ProcessDefault) instead.", false)] public static T GetInstance(string typeName, Type refAssemblyType = null) { - return Resolver.GetInstance(typeName, refAssemblyType); - } - - /// - /// 确保热更新模块所在目录存在(装载前幂等建目录)。 - /// Ensures the directory holding the hotfix assembly exists (idempotent creation before loading). - /// - /// - /// 历史上由调用方各自兜底创建热更目录;该职责属装载入口自身的前置条件,收敛于此。 - /// 对已存在目录为 no-op,且天然覆盖按 - /// version 子目录装载( 的任意父目录链)的场景。 - /// Directory creation used to be each caller's concern; it belongs to the load entry itself. - /// is a no-op for existing directories and covers - /// version-subdirectory loads (any parent chain of ). - /// - /// 热更程序集文件完整路径 / The full path of the hotfix assembly file. - private static void EnsureHotfixDirectory(string assemblyFilePath) - { - // 根路径/裸文件名时 GetDirectoryName 返回 null 或空串,无从建目录,直接跳过 - var directory = Path.GetDirectoryName(assemblyFilePath); - if (!string.IsNullOrEmpty(directory)) - { - Directory.CreateDirectory(directory); - } + return HotfixRuntime.ProcessDefault.GetInstance(typeName, refAssemblyType); } } diff --git a/GameFrameX.Core/Hotfix/HotfixRuntime.cs b/GameFrameX.Core/Hotfix/HotfixRuntime.cs new file mode 100644 index 000000000..128b4eeae --- /dev/null +++ b/GameFrameX.Core/Hotfix/HotfixRuntime.cs @@ -0,0 +1,329 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using System.Reflection; +using GameFrameX.Core.Abstractions.Agent; +using GameFrameX.Core.Abstractions.Events; +using GameFrameX.Core.Abstractions.Hotfix; +using GameFrameX.Core.Components; +using GameFrameX.Network.Abstractions; +using GameFrameX.Network.HTTP; +using GameFrameX.Utility.Setting; + +namespace GameFrameX.Core.Hotfix; + +/// +/// 热更运行时实例核(注入面:热更宿主 + 解析契约 + 基础配置的实例承载;静态便捷层 +/// 经 转发同核,双层面共享状态不分裂)。 +/// +/// +/// The hotfix runtime instance core (the injection seam: the hotfix host, the resolution contract +/// and the base setting carried on an instance; the static convenience layer +/// forwards through , so both layers share +/// the same state and never split). 装载入口与策略(同路径幂等守卫、10min 宽限常量、目录兜底) +/// 与全部解析路由( 契约)均在本类承载。 +/// Load entries and policies (the same-path idempotency guard, the 10-minute grace constant, +/// directory ensuring) and all resolution routing (the contract) +/// live on this class. +/// +public sealed class HotfixRuntime +{ + /// + /// 进程缺省实例(静态便捷层 的转发目标;组合根注入用同一实例)。 + /// + /// + /// The process-default instance (the forwarding target of the static convenience layer + /// ; compositions inject this very instance). + /// + public static readonly HotfixRuntime ProcessDefault = new HotfixRuntime(); + + /// + /// 热更宿主实例:当前模块指针与退役链的持有者(生产唯一装配)。 + /// The hotfix host instance: owner of the current-module pointer and the retirement chain (the single production wiring). + /// + private readonly HotfixHost _host = new HotfixHost(); + + /// + /// 解析契约当前实现:默认为生产 ;测试经 注入替身(传 null 复原)。 + /// The current resolution-contract implementation: the production by default; tests inject a + /// substitute via (pass null to restore). + /// + private IHotfixResolver _resolver; + + /// + /// 基础配置信息 / Base application setting. + /// + private AppSetting _baseSetting; + + /// + /// 初始化 (公开构造:实例可经注入面独立构造用于隔离测试)。 + /// + /// + /// Initializes (public constructor: instances can be built + /// independently through the injection seam for isolated tests). + /// + public HotfixRuntime() + { + _resolver = _host; + } + + /// + /// 热更解析契约注入缝:Core 子系统经此依赖抽象而非静态实现;亦为测试替身入口。 + /// The hotfix resolution-contract seam: Core subsystems depend on the abstraction instead of the static + /// implementation; also the entry point for test doubles. + /// + internal IHotfixResolver Resolver + { + get { return _resolver; } + } + + /// + /// 注入/复原解析契约实现(测试专用):传 null 复原为生产宿主。 + /// Injects/restores the resolution-contract implementation (testing only): passing null restores the production host. + /// + /// 替身实现;null 复原 / The substitute; null restores. + internal void SetResolverForTesting(IHotfixResolver resolver) + { + _resolver = resolver ?? _host; + } + + /// + /// 热更新程序集 / The hotfix assembly. + /// + public Assembly HotfixAssembly + { + get { return Resolver.HotfixAssembly; } + } + + /// + /// 最近一次热更新重载的时间 / The time of the most recent hot reload. + /// + public DateTime ReloadTime + { + get { return _host.ReloadTime; } + } + + /// + /// 加载热更新模块(同步入口)。 + /// Loads the hotfix module (synchronous entry). + /// + /// 应用程序配置 / The application setting. + /// 装载参数(null 走默认值:目录 hotfix + GameFrameX.Hotfix.dll) / Load options (null for defaults: the hotfix directory plus GameFrameX.Hotfix.dll). + /// 返回是否加载成功 / Whether the load succeeded. + public bool LoadHotfix(AppSetting setting, HotfixLoadOptions options = null) + { + var loadOptions = options ?? new HotfixLoadOptions(); + var path = loadOptions.ResolveAssemblyFilePath(); + if (setting != null) + { + _baseSetting = setting; + } + + // 同路径幂等判重:当前模块即从该路径装载时直接返回成功,避免重复的可收集 ALC 装载 + //(单进程多 Role 形态下,后续 Role 对同一热更 DLL 的重复装载会制造跨 ALC 的类型身份割裂, + // 旧模块 agent 的激活/转型随竞态随机失败;进程内同一 DLL 只装载一次) + if (_host.IsSamePathLoaded(path)) + { + return true; + } + + // 装载前幂等确保目录存在(历史由调用方各自兜底创建,收敛为装载入口自身的前置条件) + EnsureHotfixDirectory(path); + var hotfixModule = new HotfixModule(path, loadOptions); + var reload = _host.CurrentModule != null; + // 起服时失败会有异常抛出 + var success = hotfixModule.Init(reload); + if (!success) + { + return false; + } + + if (reload) + { + // 补退役:与 LoadHotfixModuleAsync 路径对齐——旧模块进入退役链(宽限排空 + 卸载 GC 验证由模块链承担), + // 否则旧可收集 ALC 永不卸载,每次同步重载泄漏一份完整热更程序集内存 + // Retire the old module to align with the LoadHotfixModuleAsync path — it joins the retirement chain + // (grace drain plus unload GC verification belong to the module chain); without this the old collectible + // ALC is never unloaded, leaking a full hotfix assembly per synchronous reload + _host.Retire(HotfixHost.RetirementGracePeriod); + } + + // 同步路径保持历史行为:仅切换当前模块指针与注册,不回调桥接 + // Synchronous path keeps historical behavior: swap and register the current module only — no bridge callback + _host.RegisterCurrent(hotfixModule); + return true; + } + + /// + /// 加载热更新模块(重载入口:旧模块退役编排 + 桥接回调)。 + /// Loads the hotfix module (reload entry: old-module retirement orchestration plus bridge callback). + /// + /// 应用程序配置 / The application setting. + /// 装载参数(null 走默认值) / Load options (null for defaults). + /// 返回是否加载成功 / Whether the load succeeded. + public async Task LoadHotfixModuleAsync(AppSetting setting, HotfixLoadOptions options = null) + { + var loadOptions = options ?? new HotfixLoadOptions(); + var path = loadOptions.ResolveAssemblyFilePath(); + if (setting != null) + { + _baseSetting = setting; + } + + // 同路径幂等判重:当前模块即从该路径装载时直接返回成功,避免重复的可收集 ALC 装载 + //(热更重载总是指向新 version 子目录;同路径「重载」没有可观测收益,只会制造跨 ALC 类型身份割裂) + if (_host.IsSamePathLoaded(path)) + { + return true; + } + + // 装载前幂等确保目录存在(历史由调用方各自兜底创建,收敛为装载入口自身的前置条件) + EnsureHotfixDirectory(path); + var hotfixModule = new HotfixModule(path, loadOptions); + var reload = _host.CurrentModule != null; + // 起服时失败会有异常抛出 + var success = hotfixModule.Init(reload); + if (!success) + { + return false; + } + + return await _host.LoadAsync(hotfixModule, _baseSetting, reload); + } + + /// + /// 停止热更新模块 / Stops the hotfix module. + /// + /// 停止原因 / The stop reason. + /// 停止任务 / The stop task. + public Task StopAsync(string message = "") + { + return _host.StopAsync(message); + } + + /// + /// 获取组件的代理实例 / Gets the agent instance for a component. + /// + /// 组件实例 / The component instance. + /// 引用程序集类型 / A type from the caller's hotfix assembly. + /// 代理类型 / The agent type. + /// 返回代理实例 / The agent instance. + public T GetAgent(BaseComponent component, Type refAssemblyType) where T : class, IComponentAgent + { + return Resolver.GetAgent(component, refAssemblyType); + } + + /// + /// 获取RPC处理器实例 / Gets the RPC handler instance. + /// + /// 请求消息的类型 / The request message type. + /// 对应的 实例,如果未找到则返回 null / The matching , or null when absent. + public IMessageHandler GetRpcHandler(Type type) + { + return Resolver.GetRpcHandler(type); + } + + /// + /// 获取消息处理器 / Gets the message handler. + /// + /// 消息ID / The message identifier. + /// 返回对应的消息处理器 / The matching handler. + public IMessageHandler GetMessageHandler(int msgId) + { + return Resolver.GetMessageHandler(msgId); + } + + /// + /// 获取HTTP消息处理器 / Gets the HTTP handler. + /// + /// HTTP命令 / The HTTP command. + /// 返回对应HTTP处理器 / The matching HTTP handler. + public BaseHttpHandler GetHttpHandler(string cmd) + { + return Resolver.GetHttpHandler(cmd); + } + + /// + /// 获取所有HTTP消息处理器列表 / Gets the list of all HTTP handlers. + /// + /// 返回HTTP处理器列表 / The HTTP handler list. + public List GetListHttpHandler() + { + return Resolver.GetListHttpHandler(); + } + + /// + /// 获取指定Actor类型和事件参数类型的事件监听器列表 / Gets event listeners for the given actor type and event-args type. + /// + /// Actor类型 / The actor type. + /// 事件参数类型(事件绑定键) / The event-args type (the event binding key). + /// 返回监听器列表,如果没有则空列表 / The listener list; empty when none. + public List FindListeners(ushort actorType, Type eventArgsType) + { + return Resolver.FindListeners(actorType, eventArgsType); + } + + /// + /// 获取指定事件参数类型的事件监听器列表 / Gets event listeners for the given event-args type. + /// + /// 事件参数类型(事件绑定键) / The event-args type (the event binding key). + /// 返回监听器列表,如果没有则空列表 / The listener list; empty when none. + public List FindListeners(Type eventArgsType) + { + return Resolver.FindListeners(eventArgsType); + } + + /// + /// 获取指定类型的实例,主要用于获取Event,Timer, Schedule的Handler实例 + /// Gets an instance of the given type, mainly Event/Timer/Schedule handler instances. + /// + /// 实例类型 / The instance type. + /// 类型名称 / The type name. + /// 引用程序集类型 / A type from the caller's hotfix assembly. + /// 返回指定类型的实例,如果类型名称为空则返回默认值 / The instance, or default for an empty type name. + public T GetInstance(string typeName, Type refAssemblyType = null) + { + return Resolver.GetInstance(typeName, refAssemblyType); + } + + /// + /// 确保热更新模块所在目录存在(装载前幂等建目录)。 + /// Ensures the directory holding the hotfix assembly exists (idempotent creation before loading). + /// + /// 热更程序集文件完整路径 / The full path of the hotfix assembly file. + private static void EnsureHotfixDirectory(string assemblyFilePath) + { + // 根路径/裸文件名时 GetDirectoryName 返回 null 或空串,无从建目录,直接跳过 + var directory = Path.GetDirectoryName(assemblyFilePath); + if (!string.IsNullOrEmpty(directory)) + { + Directory.CreateDirectory(directory); + } + } +} diff --git a/GameFrameX.Core/Session/PlayerSessionManager.cs b/GameFrameX.Core/Session/PlayerSessionManager.cs index 32f04ead3..ddf14ebd9 100644 --- a/GameFrameX.Core/Session/PlayerSessionManager.cs +++ b/GameFrameX.Core/Session/PlayerSessionManager.cs @@ -50,6 +50,7 @@ public sealed class PlayerSessionManager : IPlayerSessionManager /// 全局单例入口。获取路径为 PlayerSessionManager.Instance,引用面一律按 接口 /// ( 单例先例同款:私有构造 + static readonly 实例)。 /// + [Obsolete("静态单例入口过渡保留:请改用注入的 IPlayerSessionManager(组合根经 Override 提供;进程缺省即本实例)。Static singleton entry kept for transition; use the injected IPlayerSessionManager (provided by the composition root; the process default is this very instance).", false)] public static readonly IPlayerSessionManager Instance = new PlayerSessionManager(); private PlayerSessionManager() diff --git a/GameFrameX.DataBase/GameDatabase.cs b/GameFrameX.DataBase/GameDatabase.cs new file mode 100644 index 000000000..d032108bd --- /dev/null +++ b/GameFrameX.DataBase/GameDatabase.cs @@ -0,0 +1,471 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + + +using System.Diagnostics.CodeAnalysis; +using GameFrameX.DataBase.Abstractions; +using GameFrameX.Foundation.Localization.Core; +using GameFrameX.Foundation.Logger; +using GameFrameX.Localization; +using GameFrameX.Utility.Setting; + +namespace GameFrameX.DataBase; +/// +/// 游戏数据库实例门面(生命周期注入面:初始化 / 默认库提名 / 注册查询 / 关停卸载)。 +/// +/// +/// The instance facade of the game database (the injection seam for the lifecycle surface: +/// initialization, default-database nomination, registry queries and close/teardown). +/// The facade targets the database explicitly nominated by when present +/// and falls back to the first registered database otherwise; additional databases are registered in +/// and resolved by name. 组合根 / 宿主模块应持有本实例并经构造参数注入; +/// 进程缺省实例 供静态便捷层 过渡转发(静态层标记过时, +/// 后续收敛版本迁移调用点)。 +/// Host compositions hold this instance and inject it through constructors; the process-default +/// instance backs the transitional static convenience layer +/// (marked obsolete; call sites migrate in later convergence versions). +/// +public sealed class GameDatabase +{ + /// + /// 进程缺省实例(静态便捷层 的转发目标;组合根注入用同一实例,避免双门面状态分裂)。 + /// + /// + /// The process-default instance (the forwarding target of the static convenience layer + /// ; compositions inject this very instance so the facade state never splits). + /// + public static readonly GameDatabase ProcessDefault = new GameDatabase(); + + /// + /// 数据库服务实现实例(首个注册库的门面别名;二次 Init 不再静默覆盖)。 + /// + /// + /// Database service implementation instance (facade alias of the first registered database; + /// a second Init no longer silently overwrites it). + /// + private IDatabaseService _dbServiceImplementation; + + /// + /// 门面默认库的注册名(显式指定标记;null 表示未显式指定,门面回落首个注册库)。 + /// + /// + /// The registry name explicitly nominated as the facade default database; null means no explicit + /// nomination and the facade falls back to the first registered database. + /// + private string _defaultDatabaseName; + + /// + /// 门面隐式绑定告警的一次性标志(0 = 未告警,1 = 已告警)。 + /// + /// + /// One-shot flag for the implicit facade binding warning (0 = not warned, 1 = warned). + /// + private int _implicitBindingWarningLogged; + + /// + /// 初始化 (私有构造:实例经 或注入面流转)。 + /// + /// + /// Initializes (private constructor: instances flow through + /// or the injection seam). + /// + private GameDatabase() + { + } + + /// + /// 控制库的固定注册名(转发 )。 + /// + /// + /// The fixed registry name of the control database (forwards to + /// so call sites stay on the unified entry). + /// + public const string ControlDatabaseName = MultiDbRegistry.ControlDatabaseName; + + /// + /// 门面目标库(CRUD 与无参 的实际落点;静态便捷层经同核转发)。 + /// + /// + /// The facade target database actually serving the CRUD members and the parameterless + /// (the static convenience layer forwards through this same core). + /// Centralizes the default-binding semantics: explicit nomination first, + /// first-registered fallback otherwise; emits the one-shot implicit-binding warning when multiple + /// databases are registered without an explicit nomination. + /// + internal IDatabaseService FacadeService + { + get + { + ArgumentNullException.ThrowIfNull(_dbServiceImplementation); + if (Volatile.Read(ref _defaultDatabaseName) == null && MultiDbRegistry.RegisteredCount > 1) + { + WarnImplicitBindingOnce(); + } + + return _dbServiceImplementation; + } + } + + /// + /// 门面当前绑定的数据库服务原始读(不含空抛与隐式绑定告警——静态 CRUD partial 空判守卫行的转发面, + /// 行为与旧私有静态字段一致)。 + /// + /// + /// The raw read of the currently bound facade database service (no null-throw and no + /// implicit-binding warning — the forward for the static CRUD partials' null-guard lines, + /// behaving exactly like the former private static field). + /// + internal IDatabaseService CurrentServiceImplementation + { + get { return _dbServiceImplementation; } + } + + /// + /// 多库注册但从未 时,首次门面调用打一条一次性 Warning(不 fail fast, + /// 避免破坏单库与既有测试场景)。 + /// + /// + /// Logs a one-shot Warning on the first facade call when more than one database is registered and + /// was never called (warn once instead of failing fast, so + /// single-database processes and existing tests keep working unchanged). + /// + private void WarnImplicitBindingOnce() + { + if (Interlocked.CompareExchange(ref _implicitBindingWarningLogged, 1, 0) != 0) + { + return; + } + + // Localization: Database.GameDb.ImplicitDefaultBindingWarningLog - GameDb.ImplicitDefaultBinding 已注册多个数据库({0})但无声明式默认库提名(DbOptions.IsDefault 均为 false),静态门面当前指向首个注册库;多库部署请在业务库 Init 时保留缺省 IsDefault = true(或显式调用 GameDb.SetDefault(业务库名))。 + LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Database.GameDbImplicitDefaultBindingWarningLog, string.Join(", ", MultiDbRegistry.GetRegisteredDatabaseNames()))); + } + + /// + /// 初始化数据库(显式实现类型逃生门:AOT/裁剪、自定义 实现与测试假实现)。 + /// + /// + /// Initialize the database (explicit-type escape hatch for AOT/trimming scenarios, custom + /// implementations and test fakes): registers by + /// into and, on success, nominates the + /// facade default database when is set (default). The generic + /// argument is itself the provider — is ignored on this path. + /// Non-default databases (e.g. the control database registered first by the launch flow) must + /// pass IsDefault = false explicitly, otherwise a later default registration fails fast + /// with a set-once conflict. Startup composition roots resolving the provider from configuration + /// should use the non-generic overload instead. + /// + /// 数据库服务的具体实现类型,必须实现IDatabaseService接口且有无参构造函数 / Database service implementation type, must implement IDatabaseService interface and have a parameterless constructor + /// 数据库配置选项(ConnectionString 唯一来源;Name 同时作为注册名;IsDefault 提名门面默认库) / Database configuration options (ConnectionString is the single source; Name doubles as the registry name; IsDefault nominates the facade default) + /// 当 、其 ConnectionString 或 Name 为 null 时抛出 / Thrown when dbOptions, its ConnectionString, or Name is null + /// 当 ConnectionString 为空白时抛出 / Thrown when ConnectionString is blank + /// 当同名库已注册,或 IsDefault 提名与既有默认库冲突时抛出(拒绝静默覆盖) / Thrown when a database with the same name is already registered, or the IsDefault nomination conflicts with the existing default (silent overwrite rejected) + /// 返回数据库是否初始化成功 / Returns whether the database was initialized successfully + public Task InitAsync(DbOptions dbOptions) where T : IDatabaseService, new() + { + return InitCoreAsync(new T(), dbOptions); + } + + /// + /// 初始化数据库(推荐启动路径:按 经 约定解析实现)。 + /// + /// + /// Recommended launch path: resolves the implementation from through + /// the convention mapping table (the composition root stays free of provider-type generics and + /// ternaries), then runs the exact same validation→Open→Register→rollback→nomination→facade path as + /// the generic overload through the shared InitCore. The generic + /// remains the explicit escape hatch for AOT/trimming scenarios, + /// custom implementations and test fakes. + /// + /// 数据库配置选项(Provider 约定解析依据;ConnectionString 唯一来源;Name 同时作为注册名;IsDefault 提名门面默认库) / Database configuration options (Provider drives convention resolution; ConnectionString is the single source; Name doubles as the registry name; IsDefault nominates the facade default) + /// 当 、其 ConnectionString 或 Name 为 null 时抛出 / Thrown when dbOptions, its ConnectionString, or Name is null + /// 当 ConnectionString 为空白时抛出 / Thrown when ConnectionString is blank + /// 当枚举未配映射、宿主缺 Provider 工程引用、实例化失败、同名库已注册,或 IsDefault 提名与既有默认库冲突时抛出 / Thrown when the enum is unmapped, the provider assembly is not referenced by the host, instantiation fails, a database with the same name is already registered, or the IsDefault nomination conflicts with the existing default + /// 返回数据库是否初始化成功 / Returns whether the database was initialized successfully + [RequiresUnreferencedCode("按命名约定反射创建提供者;AOT/裁剪场景请改用 InitAsync 显式指定实现类型")] + public Task InitAsync(DbOptions dbOptions) + { + ArgumentNullException.ThrowIfNull(dbOptions); + return InitCoreAsync(DbProviderResolver.Create(dbOptions.Provider), dbOptions); + } + + /// + /// 两个 Init 重载的共享执行路径:参数校验→打开→注册(失败回滚关闭)→门面首绑→IsDefault 提名(连接串/提名单一来源化)。 + /// + /// + /// Shared execution path of both Init overloads: argument validation, Open, registration with + /// close-on-failure rollback, first-registered facade binding, and the + /// nomination (the connection string and the default nomination each have a single source — + /// DbOptions). A nomination conflict rolls the registration back (unregister + close) before the + /// exception propagates, so a failed Init leaves no residue in the registry or the facade. + /// + /// 已创建的数据库实现实例(泛型重载由 new() 创建,非泛型重载由 反射创建) / The already created database service instance (new() in the generic overload, reflection in the non-generic overload) + /// 数据库配置选项(Name 同时作为注册名) / Database configuration options (Name doubles as the registry name) + /// 当 、其 ConnectionString 或 Name 为 null 时抛出 / Thrown when dbOptions, its ConnectionString, or Name is null + /// 当 ConnectionString 为空白时抛出 / Thrown when ConnectionString is blank + /// 当同名库已注册,或 IsDefault 提名与既有默认库冲突时抛出(拒绝静默覆盖) / Thrown when a database with the same name is already registered, or the IsDefault nomination conflicts with the existing default (silent overwrite rejected) + /// 返回数据库是否初始化成功 / Returns whether the database was initialized successfully + private async Task InitCoreAsync(IDatabaseService service, DbOptions dbOptions) + { + ArgumentNullException.ThrowIfNull(dbOptions); + ArgumentException.ThrowIfNullOrWhiteSpace(dbOptions.ConnectionString, nameof(DbOptions.ConnectionString)); + ArgumentNullException.ThrowIfNull(dbOptions.Name, nameof(dbOptions.Name)); + + var isOpened = await service.OpenAsync(dbOptions); + if (!isOpened) + { + return false; + } + + try + { + MultiDbRegistry.Register(dbOptions.Name, service); + } + catch (InvalidOperationException) + { + // 注册失败(如同名库已注册):先释放已打开的服务,再抛出原异常,避免泄漏已建立的连接 + // Registration failed (e.g. duplicate name): release the opened service before rethrowing to avoid leaking the established connection. + await service.CloseAsync(); + throw; + } + + if (_dbServiceImplementation == null) + { + _dbServiceImplementation = service; + } + + if (dbOptions.IsDefault) + { + try + { + NominateDefaultDatabase(dbOptions.Name, service); + } + catch (InvalidOperationException) + { + // 提名冲突(set-once 异名):回滚本次注册并释放已打开的服务,Init 失败不在注册表/门面留残留。 + // 冲突路径上方门面首绑必为 no-op:提名成功必写首绑,故默认名非空 ⇒ 门面绑定非空。 + // Nomination conflict (set-once, different name): roll back this registration and release the opened + // service so a failed Init leaves no residue in the registry or the facade. The first-registered + // binding above is provably a no-op on this path: every successful nomination writes the binding, so a + // non-null default name implies a non-null facade binding. + MultiDbRegistry.Unregister(dbOptions.Name); + await service.CloseAsync(); + throw; + } + } + + return true; + } + + /// + /// 显式指定门面默认库(CRUD 与无参 的目标库)。 + /// + /// + /// Explicitly nominates the default database of the facade (the target of every CRUD member and + /// the parameterless ). Declarative nomination via + /// is the primary launch path (the nomination then happens inside Init right after a successful + /// registration); this method remains the explicit / post-registration entry point and shares the + /// exact same set-once core. Set-once: a second call with a different name throws; the same name + /// is idempotently accepted. + /// + /// 注册名(须已通过 Init 注册) / Registry name (must already be registered via Init) + /// 当 为 null 时抛出 / Thrown when databaseName is null + /// 当注册名未注册,或默认库已显式指定为另一注册名时抛出 / Thrown when the name is not registered, or the default was already set to a different name + public void SetDefault(string databaseName) + { + ArgumentNullException.ThrowIfNull(databaseName); + if (!MultiDbRegistry.TryGet(databaseName, out var service)) + { + // Localization: Database.Registry.NotRegistered - 没有名为“{0}”的数据库被注册。已注册名称:[{1}] + throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Database.RegistryNotRegistered, databaseName, string.Join(", ", MultiDbRegistry.GetRegisteredDatabaseNames()))); + } + + NominateDefaultDatabase(databaseName, service); + } + + /// + /// 门面默认库提名的 set-once 核心( 与 声明式提名共用)。 + /// + /// + /// Set-once core of the facade default nomination, shared by the public + /// and the declarative path inside InitCore: the first + /// nomination wins; the same name is idempotently accepted; a different name throws naming both + /// databases. The concurrent first-set race resolves via CAS — the loser re-reads the winner and + /// applies the same same-name/different-name rule as the serial path. + /// + /// 要提名的注册名 / Registry name to nominate + /// 该注册名对应的服务实例(提名即绑定为门面目标) / The service registered under the name (the nomination binds it as the facade target) + /// 当默认库已显式指定为另一注册名时抛出 / Thrown when the default was already set to a different name + private void NominateDefaultDatabase(string databaseName, IDatabaseService service) + { + var current = Volatile.Read(ref _defaultDatabaseName); + if (current != null) + { + if (current == databaseName) + { + return; + } + + // Localization: Database.Registry.DefaultAlreadySet - 默认数据库已被设置为“{0}”(set-once);不允许将其更改为“{1}”。已注册名称:[{2}] + throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Database.RegistryDefaultAlreadySet, current, databaseName, string.Join(", ", MultiDbRegistry.GetRegisteredDatabaseNames()))); + } + + if (Interlocked.CompareExchange(ref _defaultDatabaseName, databaseName, null) != null) + { + // 并发首次指定:胜者生效;同名视为幂等,异名拒绝(与串行路径语义一致) + var winner = Volatile.Read(ref _defaultDatabaseName); + if (winner != databaseName) + { + // Localization: Database.Registry.DefaultAlreadySet - 默认数据库已被设置为“{0}”(set-once);不允许将其更改为“{1}”。已注册名称:[{2}] + throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Database.RegistryDefaultAlreadySet, winner, databaseName, string.Join(", ", MultiDbRegistry.GetRegisteredDatabaseNames()))); + } + + return; + } + + _dbServiceImplementation = service; + } + + /// + /// 判断指定注册名的库是否已注册(转发 ,供启动链幂等守卫使用)。 + /// + /// + /// Determines whether a database with the specified registry name is registered (forwards to + /// for idempotent startup guards, so callers no longer + /// need to reference the registry type directly). + /// + /// 注册名 / Registry name + /// 已注册返回 true;否则 false / true when registered; otherwise false + public bool Contains(string databaseName) + { + return MultiDbRegistry.Contains(databaseName); + } + + /// + /// 以指定类型获取数据库服务实例。 + /// + /// + /// Get the database service instance as the specified type. + /// + /// 要转换的数据库服务类型,必须实现IDatabaseService接口 / Database service type to convert to, must implement IDatabaseService interface + /// 转换后的数据库服务实例 / The converted database service instance + /// 当类型转换失败时抛出 / Thrown when the cast fails + public T As() where T : IDatabaseService + { + return (T)FacadeService; + } + + /// + /// 按注册名以指定类型获取数据库服务实例(多库获取)。 + /// + /// + /// Get the database service instance as the specified type by registry name. + /// + /// 要转换的数据库服务类型,必须实现IDatabaseService接口 / Database service type to convert to, must implement IDatabaseService interface + /// 注册名(如 ) / Registry name (e.g. ) + /// 转换后的数据库服务实例 / The converted database service instance + /// 当类型转换失败时抛出 / Thrown when the cast fails + /// 当注册名未注册时抛出 / Thrown when the name is not registered + public T As(string databaseName) where T : IDatabaseService + { + return (T)MultiDbRegistry.Get(databaseName); + } + + /// + /// 异步关闭数据库连接并卸载门面(关闭全部已注册数据库,随后清空注册表与门面状态)。 + /// + /// + /// Asynchronously closes every registered database connection and tears the facade down: the registry and the + /// facade state are cleared after the close loop even when an individual close throws (the exception still + /// propagates), so a close→Init cycle can re-register the same names instead of hitting the duplicate-name guard + /// on stale entries. + /// + /// 表示异步关闭操作的任务 / Task representing the asynchronous close operation + public async Task CloseAsync() + { + ArgumentNullException.ThrowIfNull(_dbServiceImplementation); + try + { + List closeFailures = null; + foreach (var databaseService in MultiDbRegistry.GetRegisteredDatabaseServices()) + { + try + { + await databaseService.CloseAsync(); + } + catch (Exception closeException) + { + // 单库关停失败不阻断其余库:先记录,全部库尝试完毕后再统一上抛 + if (closeFailures == null) + { + closeFailures = new List(); + } + + closeFailures.Add(closeException); + } + } + + if (closeFailures != null) + { + throw closeFailures.Count == 1 ? closeFailures[0] : new AggregateException(closeFailures); + } + } + finally + { + // 关停即卸载:个别库 Close 抛出也完成卸载,注册表不残留已关停的库 + // Tear down on close: uninstall even when an individual close throws, so no closed database is left registered. + ResetFacadeState(); + } + } + + /// + /// 重置门面状态与多库注册表( 关停卸载与单元测试隔离共用核心)。 + /// + /// + /// Resets the facade state and the multi-database registry — the shared core of the + /// teardown and the unit-test isolation entry below. + /// + private void ResetFacadeState() + { + _dbServiceImplementation = null; + _defaultDatabaseName = null; + Volatile.Write(ref _implicitBindingWarningLogged, 0); + MultiDbRegistry.Clear(); + } + + /// + /// 重置门面与多库注册表(仅供单元测试隔离静态状态使用)。 + /// + /// + /// Resets the facade and the multi-database registry. For unit test isolation only. + /// + internal void ResetForTesting() + { + ResetFacadeState(); + } +} diff --git a/GameFrameX.DataBase/GameDb.cs b/GameFrameX.DataBase/GameDb.cs index 456e8851b..790fe9c8d 100644 --- a/GameFrameX.DataBase/GameDb.cs +++ b/GameFrameX.DataBase/GameDb.cs @@ -3,7 +3,7 @@ // GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights // 均受中华人民共和国及相关国际法律法规保护。 // are protected by the laws of the People's Republic of China and relevant international regulations. -// 使用本项目须严格遵守相应法律法规及开源许可证之规定。 +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 // Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. // 本项目采用 Apache License 2.0 单协议分发, // This project is licensed solely under the Apache License 2.0, @@ -12,17 +12,17 @@ // 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 // 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! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! // 因基于本项目二次开发所产生的一切法律纠纷与责任, -// Any legal disputes and liabilities arising from secondary development based on this project -// 本项目组织与贡献者概不承担。 +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 // shall be borne solely by the developer; the project organization and contributors assume no responsibility. // GitHub 仓库:https://github.com/GameFrameX -// GitHub Repository: https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX // Gitee 仓库:https://gitee.com/GameFrameX -// Gitee Repository: https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX // CNB 仓库:https://cnb.cool/GameFrameX -// CNB Repository: https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX // 官方文档:https://gameframex.doc.alianblank.com/ // Official Documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== @@ -38,397 +38,142 @@ namespace GameFrameX.DataBase; /// -/// 游戏数据库静态工具类,提供对数据库的基本操作封装。 +/// 游戏数据库静态便捷层(过渡保留:生命周期面转发 ,已标记过时并指向注入面)。 /// /// -/// Static utility class for game database operations, providing basic database operation encapsulation. -/// The static facade targets the database explicitly nominated by when present -/// and falls back to the first registered database otherwise (semantics preserved for -/// single-database processes and legacy consumers); additional databases are registered in -/// and resolved by name. +/// The static convenience layer for game database operations (transitional: the lifecycle surface +/// forwards to and is marked obsolete, pointing at the +/// injection seam). CRUD 静态成员暂无实例替代,保留不标注;后续收敛版本迁移调用点后移除本层。 +/// The static CRUD members have no instance replacement yet and stay unmarked; the layer is removed +/// once later convergence versions migrate the call sites. /// public static partial class GameDb { /// - /// 数据库服务实现实例(首个注册库的门面别名;二次 Init 不再静默覆盖)。 + /// 控制库的固定注册名(转发 ;常量转发不参与门面状态,不标注过时)。 /// /// - /// Database service implementation instance (facade alias of the first registered database; - /// a second Init no longer silently overwrites it). - /// - private static IDatabaseService _dbServiceImplementation; - - /// - /// 门面默认库的注册名(显式指定标记;null 表示未显式指定,门面回落首个注册库)。 - /// - /// - /// The registry name explicitly nominated as the facade default database; null means no explicit - /// nomination and the facade falls back to the first registered database. - /// - private static string _defaultDatabaseName; - - /// - /// 门面隐式绑定告警的一次性标志(0 = 未告警,1 = 已告警)。 - /// - /// - /// One-shot flag for the implicit facade binding warning (0 = not warned, 1 = warned). + /// The fixed registry name of the control database (forwards to + /// ; a constant forward holds no facade state + /// and stays unmarked). /// - private static int _implicitBindingWarningLogged; + public const string ControlDatabaseName = MultiDbRegistry.ControlDatabaseName; /// - /// 门面目标库(全部静态 CRUD 与无参 的实际落点)。 + /// 静态 CRUD partial 的空判守卫转发面(原始读,不触发空抛与隐式绑定告警;行为与旧私有静态字段一致)。 /// /// - /// The facade target database actually serving every static CRUD member and the parameterless - /// . Centralizes the default-binding semantics: explicit - /// nomination first, first-registered fallback otherwise; emits the one-shot implicit-binding - /// warning when multiple databases are registered without an explicit nomination. + /// The null-guard forward for the static CRUD partials (raw read, no null-throw and no + /// implicit-binding warning; behavior identical to the former private static field). /// - private static IDatabaseService FacadeService + private static IDatabaseService _dbServiceImplementation { - get - { - ArgumentNullException.ThrowIfNull(_dbServiceImplementation); - if (Volatile.Read(ref _defaultDatabaseName) == null && MultiDbRegistry.RegisteredCount > 1) - { - WarnImplicitBindingOnce(); - } - - return _dbServiceImplementation; - } + get { return GameDatabase.ProcessDefault.CurrentServiceImplementation; } } /// - /// 多库注册但从未 时,首次门面调用打一条一次性 Warning(不 fail fast, - /// 避免破坏单库与既有测试场景)。 + /// 门面目标库(静态 CRUD partial 的转发目标——静态层与实例核共享同一门面状态,不产生双门面分裂)。 /// /// - /// Logs a one-shot Warning on the first facade call when more than one database is registered and - /// was never called (warn once instead of failing fast, so - /// single-database processes and existing tests keep working unchanged). + /// The facade target database for the static CRUD partials — the static layer and the instance + /// core share the same facade state, so the two layers never split. /// - private static void WarnImplicitBindingOnce() + private static IDatabaseService FacadeService { - if (Interlocked.CompareExchange(ref _implicitBindingWarningLogged, 1, 0) != 0) - { - return; - } - - // Localization: Database.GameDb.ImplicitDefaultBindingWarningLog - GameDb.ImplicitDefaultBinding 已注册多个数据库({0})但无声明式默认库提名(DbOptions.IsDefault 均为 false),静态门面当前指向首个注册库;多库部署请在业务库 Init 时保留缺省 IsDefault = true(或显式调用 GameDb.SetDefault(业务库名))。 - LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Database.GameDbImplicitDefaultBindingWarningLog, string.Join(", ", MultiDbRegistry.GetRegisteredDatabaseNames()))); + get { return GameDatabase.ProcessDefault.FacadeService; } } /// - /// 初始化GameDb(显式实现类型逃生门:AOT/裁剪、自定义 实现与测试假实现)。 + /// 初始化数据库(静态便捷层:转发 )。 /// - /// - /// Initialize the GameDb instance (explicit-type escape hatch for AOT/trimming scenarios, custom - /// implementations and test fakes): registers by - /// into and, on success, nominates the - /// facade default database when is set (default). The generic - /// argument is itself the provider — is ignored on this path. - /// Non-default databases (e.g. the control database registered first by the launch flow) must - /// pass IsDefault = false explicitly, otherwise a later default registration fails fast - /// with a set-once conflict. Startup composition roots resolving the provider from configuration - /// should use the non-generic overload instead. - /// - /// 数据库服务的具体实现类型,必须实现IDatabaseService接口且有无参构造函数 / Database service implementation type, must implement IDatabaseService interface and have a parameterless constructor - /// 数据库配置选项(ConnectionString 唯一来源;Name 同时作为注册名;IsDefault 提名门面默认库) / Database configuration options (ConnectionString is the single source; Name doubles as the registry name; IsDefault nominates the facade default) - /// 当 、其 ConnectionString 或 Name 为 null 时抛出 / Thrown when dbOptions, its ConnectionString, or Name is null - /// 当 ConnectionString 为空白时抛出 / Thrown when ConnectionString is blank - /// 当同名库已注册,或 IsDefault 提名与既有默认库冲突时抛出(拒绝静默覆盖) / Thrown when a database with the same name is already registered, or the IsDefault nomination conflicts with the existing default (silent overwrite rejected) + /// Initialize the database (static convenience forward of ). + /// 数据库服务的具体实现类型 / Database service implementation type + /// 数据库配置选项 / Database configuration options /// 返回数据库是否初始化成功 / Returns whether the database was initialized successfully + [Obsolete("静态便捷层过渡保留:请改用注入的 GameDatabase 实例(进程缺省 GameDatabase.ProcessDefault)。Static convenience layer kept for transition; use the injected GameDatabase instance (process default GameDatabase.ProcessDefault) instead.", false)] public static Task InitAsync(DbOptions dbOptions) where T : IDatabaseService, new() { - return InitCoreAsync(new T(), dbOptions); + return GameDatabase.ProcessDefault.InitAsync(dbOptions); } /// - /// 初始化GameDb(推荐启动路径:按 经 约定解析实现)。 + /// 初始化数据库(静态便捷层:转发 )。 /// - /// - /// Recommended launch path: resolves the implementation from through - /// the convention mapping table (the composition root stays free of provider-type generics and - /// ternaries), then runs the exact same validation→Open→Register→rollback→nomination→facade path as - /// the generic overload through the shared InitCore. The generic - /// remains the explicit escape hatch for AOT/trimming scenarios, - /// custom implementations and test fakes. - /// - /// 数据库配置选项(Provider 约定解析依据;ConnectionString 唯一来源;Name 同时作为注册名;IsDefault 提名门面默认库) / Database configuration options (Provider drives convention resolution; ConnectionString is the single source; Name doubles as the registry name; IsDefault nominates the facade default) - /// 当 、其 ConnectionString 或 Name 为 null 时抛出 / Thrown when dbOptions, its ConnectionString, or Name is null - /// 当 ConnectionString 为空白时抛出 / Thrown when ConnectionString is blank - /// 当枚举未配映射、宿主缺 Provider 工程引用、实例化失败、同名库已注册,或 IsDefault 提名与既有默认库冲突时抛出 / Thrown when the enum is unmapped, the provider assembly is not referenced by the host, instantiation fails, a database with the same name is already registered, or the IsDefault nomination conflicts with the existing default + /// Initialize the database (static convenience forward of ). + /// 数据库配置选项 / Database configuration options /// 返回数据库是否初始化成功 / Returns whether the database was initialized successfully - [RequiresUnreferencedCode("按命名约定反射创建提供者;AOT/裁剪场景请改用 Init 显式指定实现类型")] + [Obsolete("静态便捷层过渡保留:请改用注入的 GameDatabase 实例(进程缺省 GameDatabase.ProcessDefault)。Static convenience layer kept for transition; use the injected GameDatabase instance (process default GameDatabase.ProcessDefault) instead.", false)] + [RequiresUnreferencedCode("按命名约定反射创建提供者;AOT/裁剪场景请改用 InitAsync 显式指定实现类型")] public static Task InitAsync(DbOptions dbOptions) { - ArgumentNullException.ThrowIfNull(dbOptions); - return InitCoreAsync(DbProviderResolver.Create(dbOptions.Provider), dbOptions); + return GameDatabase.ProcessDefault.InitAsync(dbOptions); } /// - /// 两个 Init 重载的共享执行路径:参数校验→打开→注册(失败回滚关闭)→门面首绑→IsDefault 提名(连接串/提名单一来源化)。 + /// 显式指定静态门面的默认库(静态便捷层:转发 )。 /// - /// - /// Shared execution path of both Init overloads: argument validation, Open, registration with - /// close-on-failure rollback, first-registered facade binding, and the - /// nomination (the connection string and the default nomination each have a single source — - /// DbOptions). A nomination conflict rolls the registration back (unregister + close) before the - /// exception propagates, so a failed Init leaves no residue in the registry or the facade. - /// - /// 已创建的数据库实现实例(泛型重载由 new() 创建,非泛型重载由 反射创建) / The already created database service instance (new() in the generic overload, reflection in the non-generic overload) - /// 数据库配置选项(Name 同时作为注册名) / Database configuration options (Name doubles as the registry name) - /// 当 、其 ConnectionString 或 Name 为 null 时抛出 / Thrown when dbOptions, its ConnectionString, or Name is null - /// 当 ConnectionString 为空白时抛出 / Thrown when ConnectionString is blank - /// 当同名库已注册,或 IsDefault 提名与既有默认库冲突时抛出(拒绝静默覆盖) / Thrown when a database with the same name is already registered, or the IsDefault nomination conflicts with the existing default (silent overwrite rejected) - /// 返回数据库是否初始化成功 / Returns whether the database was initialized successfully - private static async Task InitCoreAsync(IDatabaseService service, DbOptions dbOptions) - { - ArgumentNullException.ThrowIfNull(dbOptions); - ArgumentException.ThrowIfNullOrWhiteSpace(dbOptions.ConnectionString, nameof(DbOptions.ConnectionString)); - ArgumentNullException.ThrowIfNull(dbOptions.Name, nameof(dbOptions.Name)); - - var isOpened = await service.OpenAsync(dbOptions); - if (!isOpened) - { - return false; - } - - try - { - MultiDbRegistry.Register(dbOptions.Name, service); - } - catch (InvalidOperationException) - { - // 注册失败(如同名库已注册):先释放已打开的服务,再抛出原异常,避免泄漏已建立的连接 - // Registration failed (e.g. duplicate name): release the opened service before rethrowing to avoid leaking the established connection. - await service.CloseAsync(); - throw; - } - - if (_dbServiceImplementation == null) - { - _dbServiceImplementation = service; - } - - if (dbOptions.IsDefault) - { - try - { - NominateDefaultDatabase(dbOptions.Name, service); - } - catch (InvalidOperationException) - { - // 提名冲突(set-once 异名):回滚本次注册并释放已打开的服务,Init 失败不在注册表/门面留残留。 - // 冲突路径上方门面首绑必为 no-op:提名成功必写首绑,故默认名非空 ⇒ 门面绑定非空。 - // Nomination conflict (set-once, different name): roll back this registration and release the opened - // service so a failed Init leaves no residue in the registry or the facade. The first-registered - // binding above is provably a no-op on this path: every successful nomination writes the binding, so a - // non-null default name implies a non-null facade binding. - MultiDbRegistry.Unregister(dbOptions.Name); - await service.CloseAsync(); - throw; - } - } - - return true; - } - - /// - /// 显式指定静态门面的默认库(全部静态 CRUD 与无参 的目标库)。 - /// - /// - /// Explicitly nominates the default database of the static facade (the target of every static CRUD - /// member and the parameterless ). Declarative nomination via - /// is the primary launch path (the nomination then happens inside - /// Init right after a successful registration); this method remains the explicit / - /// post-registration entry point and shares the exact same set-once core. Set-once: a second call - /// with a different name throws; the same name is idempotently accepted. - /// - /// 注册名(须已通过 GameDb.Init 注册) / Registry name (must already be registered via GameDb.Init) - /// 当 为 null 时抛出 / Thrown when databaseName is null - /// 当注册名未注册,或默认库已显式指定为另一注册名时抛出 / Thrown when the name is not registered, or the default was already set to a different name + /// Nominates the default database (static convenience forward of ). + /// 注册名 / Registry name + [Obsolete("静态便捷层过渡保留:请改用注入的 GameDatabase 实例(进程缺省 GameDatabase.ProcessDefault)。Static convenience layer kept for transition; use the injected GameDatabase instance (process default GameDatabase.ProcessDefault) instead.", false)] public static void SetDefault(string databaseName) { - ArgumentNullException.ThrowIfNull(databaseName); - if (!MultiDbRegistry.TryGet(databaseName, out var service)) - { - // Localization: Database.Registry.NotRegistered - 没有名为“{0}”的数据库被注册。已注册名称:[{1}] - throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Database.RegistryNotRegistered, databaseName, string.Join(", ", MultiDbRegistry.GetRegisteredDatabaseNames()))); - } - - NominateDefaultDatabase(databaseName, service); - } - - /// - /// 门面默认库提名的 set-once 核心( 与 声明式提名共用)。 - /// - /// - /// Set-once core of the facade default nomination, shared by the public - /// and the declarative path inside InitCore: the first - /// nomination wins; the same name is idempotently accepted; a different name throws naming both - /// databases. The concurrent first-set race resolves via CAS — the loser re-reads the winner and - /// applies the same same-name/different-name rule as the serial path. - /// - /// 要提名的注册名 / Registry name to nominate - /// 该注册名对应的服务实例(提名即绑定为门面目标) / The service registered under the name (the nomination binds it as the facade target) - /// 当默认库已显式指定为另一注册名时抛出 / Thrown when the default was already set to a different name - private static void NominateDefaultDatabase(string databaseName, IDatabaseService service) - { - var current = Volatile.Read(ref _defaultDatabaseName); - if (current != null) - { - if (current == databaseName) - { - return; - } - - // Localization: Database.Registry.DefaultAlreadySet - 默认数据库已被设置为“{0}”(set-once);不允许将其更改为“{1}”。已注册名称:[{2}] - throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Database.RegistryDefaultAlreadySet, current, databaseName, string.Join(", ", MultiDbRegistry.GetRegisteredDatabaseNames()))); - } - - if (Interlocked.CompareExchange(ref _defaultDatabaseName, databaseName, null) != null) - { - // 并发首次指定:胜者生效;同名视为幂等,异名拒绝(与串行路径语义一致) - var winner = Volatile.Read(ref _defaultDatabaseName); - if (winner != databaseName) - { - // Localization: Database.Registry.DefaultAlreadySet - 默认数据库已被设置为“{0}”(set-once);不允许将其更改为“{1}”。已注册名称:[{2}] - throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Database.RegistryDefaultAlreadySet, winner, databaseName, string.Join(", ", MultiDbRegistry.GetRegisteredDatabaseNames()))); - } - - return; - } - - _dbServiceImplementation = service; + GameDatabase.ProcessDefault.SetDefault(databaseName); } /// - /// 判断指定注册名的库是否已注册(转发 ,供启动链幂等守卫使用)。 + /// 判断指定注册名的库是否已注册(静态便捷层:转发 )。 /// - /// - /// Determines whether a database with the specified registry name is registered (forwards to - /// for idempotent startup guards, so callers no longer - /// need to reference the registry type directly). - /// + /// Determines whether a database is registered (static convenience forward of ). /// 注册名 / Registry name /// 已注册返回 true;否则 false / true when registered; otherwise false + [Obsolete("静态便捷层过渡保留:请改用注入的 GameDatabase 实例(进程缺省 GameDatabase.ProcessDefault)。Static convenience layer kept for transition; use the injected GameDatabase instance (process default GameDatabase.ProcessDefault) instead.", false)] public static bool Contains(string databaseName) { - return MultiDbRegistry.Contains(databaseName); + return GameDatabase.ProcessDefault.Contains(databaseName); } /// - /// 控制库的固定注册名(转发 )。 - /// - /// - /// The fixed registry name of the control database (forwards to - /// so call sites stay on the unified entry). - /// - public const string ControlDatabaseName = MultiDbRegistry.ControlDatabaseName; - - /// - /// 以指定类型获取数据库服务实例。 + /// 以指定类型获取数据库服务实例(静态便捷层:转发 )。 /// - /// - /// Get the database service instance as the specified type. - /// - /// 要转换的数据库服务类型,必须实现IDatabaseService接口 / Database service type to convert to, must implement IDatabaseService interface + /// Gets the database service as the specified type (static convenience forward of ). + /// 要转换的数据库服务类型 / Database service type to convert to /// 转换后的数据库服务实例 / The converted database service instance - /// 当类型转换失败时抛出 / Thrown when type conversion fails + [Obsolete("静态便捷层过渡保留:请改用注入的 GameDatabase 实例(进程缺省 GameDatabase.ProcessDefault)。Static convenience layer kept for transition; use the injected GameDatabase instance (process default GameDatabase.ProcessDefault) instead.", false)] public static T As() where T : IDatabaseService { - return (T)FacadeService; + return GameDatabase.ProcessDefault.As(); } /// - /// 按注册名以指定类型获取数据库服务实例(多库获取)。 + /// 按注册名以指定类型获取数据库服务实例(静态便捷层:转发 )。 /// - /// - /// Get the database service instance as the specified type by registry name. - /// - /// 要转换的数据库服务类型,必须实现IDatabaseService接口 / Database service type to convert to, must implement IDatabaseService interface - /// 注册名(如 ) / Registry name (e.g. ) + /// Gets the database service as the specified type by registry name (static convenience forward of ). + /// 要转换的数据库服务类型 / Database service type to convert to + /// 注册名 / Registry name /// 转换后的数据库服务实例 / The converted database service instance - /// 当类型转换失败时抛出 / Thrown when type conversion fails - /// 当注册名未注册时抛出 / Thrown when the name is not registered + [Obsolete("静态便捷层过渡保留:请改用注入的 GameDatabase 实例(进程缺省 GameDatabase.ProcessDefault)。Static convenience layer kept for transition; use the injected GameDatabase instance (process default GameDatabase.ProcessDefault) instead.", false)] public static T As(string databaseName) where T : IDatabaseService { - return (T)MultiDbRegistry.Get(databaseName); + return GameDatabase.ProcessDefault.As(databaseName); } /// - /// 异步关闭数据库连接并卸载门面(关闭全部已注册数据库,随后清空注册表与门面静态状态)。 + /// 异步关闭数据库连接并卸载门面(静态便捷层:转发 )。 /// - /// - /// Asynchronously closes every registered database connection and tears the facade down: the registry and the - /// facade static state are cleared after the close loop even when an individual close throws (the exception still - /// propagates), so a close→Init cycle can re-register the same names instead of hitting the duplicate-name guard - /// on stale entries. This async member is the sole close entry point — the former sync-over-async - /// Close() was removed. - /// + /// Closes every registered database and tears the facade down (static convenience forward of ). /// 表示异步关闭操作的任务 / Task representing the asynchronous close operation - public static async Task CloseAsync() + [Obsolete("静态便捷层过渡保留:请改用注入的 GameDatabase 实例(进程缺省 GameDatabase.ProcessDefault)。Static convenience layer kept for transition; use the injected GameDatabase instance (process default GameDatabase.ProcessDefault) instead.", false)] + public static Task CloseAsync() { - ArgumentNullException.ThrowIfNull(_dbServiceImplementation); - try - { - List closeFailures = null; - foreach (var databaseService in MultiDbRegistry.GetRegisteredDatabaseServices()) - { - try - { - await databaseService.CloseAsync(); - } - catch (Exception closeException) - { - // 单库关停失败不阻断其余库:先记录,全部库尝试完毕后再统一上抛 - if (closeFailures == null) - { - closeFailures = new List(); - } - - closeFailures.Add(closeException); - } - } - - if (closeFailures != null) - { - throw closeFailures.Count == 1 ? closeFailures[0] : new AggregateException(closeFailures); - } - } - finally - { - // 关停即卸载:个别库 Close 抛出也完成卸载,注册表不残留已关停的库 - // Tear down on close: uninstall even when an individual close throws, so no closed database is left registered. - ResetFacadeState(); - } + return GameDatabase.ProcessDefault.CloseAsync(); } /// - /// 重置门面静态状态与多库注册表( 关停卸载与单元测试隔离共用核心)。 + /// 重置门面与多库注册表(静态便捷层测试隔离入口:与实例核 ResetForTesting 同核)。 /// - /// - /// Resets the facade static state and the multi-database registry — the shared core of the - /// teardown and the unit-test isolation entry below. - /// - private static void ResetFacadeState() - { - _dbServiceImplementation = null; - _defaultDatabaseName = null; - Volatile.Write(ref _implicitBindingWarningLogged, 0); - MultiDbRegistry.Clear(); - } - - /// - /// 重置数据库门面与多库注册表(仅供单元测试隔离静态状态使用)。 - /// - /// - /// Resets the static facade and the multi-database registry. For unit test isolation of static state only. - /// + /// Resets the facade and the registry (the static test-isolation entry; same core as the instance ResetForTesting). internal static void ResetForTesting() { - ResetFacadeState(); + GameDatabase.ProcessDefault.ResetForTesting(); } - } diff --git a/GameFrameX.Launcher/Composition/ILegacyRuntimeHostOwner.cs b/GameFrameX.Launcher/Composition/ILegacyRuntimeHostOwner.cs new file mode 100644 index 000000000..e62b479dd --- /dev/null +++ b/GameFrameX.Launcher/Composition/ILegacyRuntimeHostOwner.cs @@ -0,0 +1,123 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using GameFrameX.Utility.Setting; + +namespace GameFrameX.Launcher.Composition; + +/// +/// 旧栈宿主回调面:(早段)与 +/// (晚段)经本接口回调宿主启动模板的固定序列步骤 +///(模板的虚方法钩子语义原样保留——Role 覆写继续生效)。 +/// +/// +/// The legacy-stack host callback surface: the early-phase and the +/// late-phase call back into the startup template's fixed +/// sequence steps through this interface (the template's virtual-hook semantics are preserved verbatim +/// — role overrides keep working). +/// +internal interface ILegacyRuntimeHostOwner +{ + /// 获取当前 Role 的应用配置。 + AppSetting Setting { get; } + + /// 获取本次停机原因(晚段模块停用序列透传给 ServiceOffline 与基类停机流程)。 + string CurrentStopMessage { get; } + + /// + /// 装载热更模块(经 注入面;同路径幂等守卫在实例核内)。 + /// + /// 表示装载操作的异步任务。 + Task LoadHotfixModuleAsync(); + + /// + /// 初始化控制库(Contains 判重护栏 + IsDefault = false 显式声明;虚方法语义保留)。 + /// + /// 表示异步操作的任务。 + Task InitializeControlDatabaseAsync(); + + /// + /// 激活发现层(读侧 watcher + 写侧心跳 + 跨 Role 路由缝重装 + 玩家路由层;虚方法语义保留)。 + /// + /// 表示异步操作的任务。 + Task ActivateDiscoveryLayerAsync(); + + /// + /// 初始化业务库(缺省 IsDefault = true 声明式提名门面默认库;虚方法语义保留)。 + /// + /// 表示异步操作的任务。 + Task InitializeBusinessDatabaseAsync(); + + /// + /// 启动网络监听(消息解码/编码/压缩与热更 HTTP 处理器桥接由模板内部装配)。 + /// + /// 表示异步操作的任务。 + Task StartNetworkListenersAsync(); + + /// + /// 启动完成钩子(缺省分发 ServiceOnline 事件——唯一分发点;虚方法语义保留)。 + /// + /// 表示钩子操作的异步任务。 + Task OnStartupCompletedAsync(); + + /// + /// 放行启动就绪屏障(优先级链启动语义)并标记启动序列完成。 + /// + void MarkStartUpReadyBarrier(); + + /// + /// 心跳切 Active(未激活发现层或无广播身份时为无害 no-op)。 + /// + /// 表示异步操作的任务。 + Task MarkDiscoveryActiveAsync(); + + /// + /// 获取是否应发布 KCP 附加端点(IsEnableInnerKcp 且已配置内网 KCP 监听)。 + /// + bool ShouldPublishInnerKcpEndpoint { get; } + + /// + /// 发布 KCP 附加端点到发现层广播。 + /// + void PublishInnerKcpAdvertiseEndpoint(); + + /// + /// 停机钩子(缺省分发 ServiceOffline 事件——唯一分发点;虚方法语义保留)。 + /// + /// 终止原因。 + /// 表示钩子操作的异步任务。 + Task OnStoppingAsync(string message); + + /// + /// 基类停机流程(停机日志 + 网络停机 + 运行时状态与退出令牌置位)——晚段模块停用序列的收尾步骤。 + /// + /// 终止原因。 + /// 表示异步操作的任务。 + Task StopNetworkAndMarkStoppedAsync(string message); +} diff --git a/GameFrameX.Launcher/Composition/LegacyNetworkListenerHostModule.cs b/GameFrameX.Launcher/Composition/LegacyNetworkListenerHostModule.cs new file mode 100644 index 000000000..9a225d225 --- /dev/null +++ b/GameFrameX.Launcher/Composition/LegacyNetworkListenerHostModule.cs @@ -0,0 +1,131 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using GameFrameX.Capability.Hosting.Abstractions; +using GameFrameX.Foundation.Localization.Core; +using GameFrameX.Foundation.Logger; +using GameFrameX.Localization; + +namespace GameFrameX.Launcher.Composition; + +/// +/// 旧栈晚段宿主模块():承载启动模板固定序列中 +/// 晚于能力族激活的部分——网络监听启动 → KCP 附加端点发布 → ServiceOnline 分发 → +/// 启动就绪屏障放行 → 心跳 Active;停用(激活逆序中最先执行)承载 +/// ServiceOffline 分发与基类停机流程(网络停机 + 退出令牌置位)。 +/// +/// +/// The late-phase legacy host module (): carries +/// the part of the startup template's fixed sequence that follows capability activation — the network +/// listener startup, the kcp additional-endpoint publish, the ServiceOnline dispatch, the +/// startup-ready barrier release and the Active heartbeat; its deactivation (first in the reverse +/// order) carries the ServiceOffline dispatch and the base stop flow (network shutdown plus the +/// exit-token settlement). 启停顺序语义:晚段必须晚于全部能力模块激活——监听开放时能力桥已发布、 +/// 热更侧钩子已挂载(等价旧模板序列「热更 → 能力 → 监听」的监听半段);停用逆序使网络先于能力族 +/// teardown 关闭,消除了旧停机序中「监听仍开放而能力已拆」的窗口(有意改进,语义位移登记于所属 change)。 +/// Order semantics: the late phase activates after every capability module — bridges are published and +/// hotfix-side hooks are mounted by the time listening opens (the listener half of the legacy +/// "hotfix → capability → listen" sequence); the reverse deactivation closes the network before the +/// capability teardown, removing the old stop-order window where listeners stayed open while capabilities +/// were already dismantled (a deliberate improvement registered in the owning change). +/// +internal sealed class LegacyNetworkListenerHostModule : ICapabilityModule +{ + /// + /// 晚段固定序列承载步骤(等价迁移自启动模板):监听 → KCP 发布 → ServiceOnline → 就绪屏障 → Active。 + /// + private readonly ILegacyRuntimeHostOwner _owner; + + /// + /// 初始化 。 + /// + /// 宿主回调面(启动模板实例)。 + public LegacyNetworkListenerHostModule(ILegacyRuntimeHostOwner owner) + { + _owner = owner ?? throw new ArgumentNullException(nameof(owner)); + } + + /// + /// 获取能力静态清单(宿主基础设施模块:无参数、无依赖、无 admin action)。 + /// + public CapabilityManifest Manifest { get; } = new CapabilityManifest("host-legacy-listener", "1.0.0"); + + /// + /// 装配期注册(晚段为纯序列步骤,无服务 / job / 事件订阅可注册)。 + /// + /// 注册上下文(不使用)。 + public void Register(CapabilityRegistrationContext context) + { + } + + /// + /// 激活(晚段固定序列):网络监听启动 → KCP 附加端点发布(屏障前发布,Booting 实例不进路由视图)→ + /// ServiceOnline 分发 → 启动完成日志与就绪屏障放行 → 心跳 Active。 + /// + /// 激活上下文(不使用)。 + /// 取消令牌(序列步骤为模板固有流程,不响应取消)。 + /// 异步任务。 + public async Task ActivateAsync(CapabilityActivationContext context, CancellationToken cancellationToken) + { + await _owner.StartNetworkListenersAsync(); + + // KCP 附加端点发布:在监听器装配完成后、就绪屏障与心跳 Active 之前执行;屏障前发布是刻意的—— + // Role 按就绪屏障串行启动,屏障之后本 Role 的实例级闸门读数可能被同进程后续 Role 的装配污染; + // Booting 实例不进任何路由视图,广播前置不会提前暴露端点。 + if (_owner.ShouldPublishInnerKcpEndpoint) + { + _owner.PublishInnerKcpAdvertiseEndpoint(); + } + + await _owner.OnStartupCompletedAsync(); + + LogHelper.DebugConsole(LocalizationService.GetString(Localization.Keys.Launcher.EnterMainLoop)); + LogHelper.Info(LocalizationService.GetString(Localization.Keys.Launcher.ServerStartEnd, _owner.Setting.ServerType)); + + // 启动阶段完成(DB/组件/Role 服务均已就绪),放行下一个 Role 的启动屏障 + _owner.MarkStartUpReadyBarrier(); + + // 启动阶段真正完成后才把心跳从 Booting 切到 Active,避免其他进程在服务就绪前发现本实例并投递流量; + // 未激活发现层或无广播身份时为无害 no-op。 + await _owner.MarkDiscoveryActiveAsync(); + } + + /// + /// 停用(逆序中最先执行):ServiceOffline 分发(先于网络关闭——消费方收到显式下线信号后网络才断)→ + /// 基类停机流程(停机日志 + 网络停机 + 运行时状态与退出令牌置位)。 + /// + /// 取消令牌(不响应取消——停机收尾必须完成)。 + /// 异步任务。 + public async Task DeactivateAsync(CancellationToken cancellationToken) + { + var message = _owner.CurrentStopMessage ?? string.Empty; + await _owner.OnStoppingAsync(message); + await _owner.StopNetworkAndMarkStoppedAsync(message); + } +} diff --git a/GameFrameX.Launcher/Composition/LegacyRuntimeHostModule.cs b/GameFrameX.Launcher/Composition/LegacyRuntimeHostModule.cs new file mode 100644 index 000000000..d8e1dcc9c --- /dev/null +++ b/GameFrameX.Launcher/Composition/LegacyRuntimeHostModule.cs @@ -0,0 +1,119 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using GameFrameX.Apps; +using GameFrameX.Capability.Hosting.Abstractions; +using GameFrameX.Foundation.Localization.Core; +using GameFrameX.Localization; +using GameFrameX.Core.Components; + +namespace GameFrameX.Launcher.Composition; + +/// +/// 旧栈早段宿主模块():承载启动模板固定序列中 +/// 先于能力族激活的部分——控制库初始化 → 发现层激活 → 业务库初始化 → 组件注册 → 热更模块装载。 +/// +/// +/// The early-phase legacy host module (): carries +/// the part of the startup template's fixed sequence that precedes capability activation — control-database +/// initialization, discovery activation, business-database initialization, component registration and the +/// hotfix module load. 启停顺序语义:早段必须先于全部能力模块激活,保证能力侧声明读取与桥挂载时 +/// 数据库、发现层与热更注册表已就绪(等价旧模板序列「热更 → 能力 → 监听」的热更半段);机制经相位 +/// 合成定序边固化该先后关系,本模块自身不声明任何 Requires。 +/// Order semantics: the early phase activates before every capability module so that databases, the +/// discovery layer and the hotfix registry are ready by the time capabilities read declarations and mount +/// bridges (equivalent to the hotfix half of the legacy "hotfix → capability → listen" sequence); the +/// mechanism pins this ordering through phase-synthesized edges and this module itself declares no +/// Requires. 停用语义:热更模块的业务清理不承载于本模块停用——单进程多 Role 形态下早段模块随 +/// 每个 Role 的停机各自停用,若在此触发热更 teardown 会在其余 Role 仍在服务时提前拆除热更业务; +/// 热更停止保持由首个 Role 的退出尾部执行一次(进程最后停机者),生命周期归一由后续服务生命周期 +/// 收敛阶段重构。 +/// Deactivation semantics: the hotfix business cleanup is not carried here — in the single-process +/// multi-role shape this module deactivates once per role, and tearing the hotfix stack down here would +/// dismantle hotfix business while other roles still serve; the hotfix stop stays a one-shot tail of the +/// first role's exit (the process's last stopper), to be restructured by the later server-lifecycle +/// convergence stage. +/// +internal sealed class LegacyRuntimeHostModule : ICapabilityModule +{ + /// + /// 早段固定序列承载步骤(等价迁移自启动模板):控制库 → 发现层 → 业务库 → 组件注册 → 热更装载。 + /// + private readonly ILegacyRuntimeHostOwner _owner; + + /// + /// 初始化 。 + /// + /// 宿主回调面(启动模板实例)。 + public LegacyRuntimeHostModule(ILegacyRuntimeHostOwner owner) + { + _owner = owner ?? throw new ArgumentNullException(nameof(owner)); + } + + /// + /// 获取能力静态清单(宿主基础设施模块:无参数、无依赖、无 admin action)。 + /// + public CapabilityManifest Manifest { get; } = new CapabilityManifest("host-legacy-runtime", "1.0.0"); + + /// + /// 装配期注册(早段为纯序列步骤,无服务 / job / 事件订阅可注册)。 + /// + /// 注册上下文(不使用)。 + public void Register(CapabilityRegistrationContext context) + { + } + + /// + /// 激活(早段固定序列):控制库初始化 → 发现层激活 → 业务库初始化 → 组件注册 → 热更模块装载。 + /// + /// 激活上下文(不使用)。 + /// 取消令牌(序列步骤为模板固有流程,不响应取消)。 + /// 异步任务。 + public async Task ActivateAsync(CapabilityActivationContext context, CancellationToken cancellationToken) + { + await _owner.InitializeControlDatabaseAsync(); + await _owner.ActivateDiscoveryLayerAsync(); + await _owner.InitializeBusinessDatabaseAsync(); + LogHelper.DebugConsole(LocalizationService.GetString(Localization.Keys.Launcher.ComponentRegisterBegin)); + await ComponentRegister.InitAsync(typeof(AppsHandler).Assembly); + LogHelper.DebugConsole(LocalizationService.GetString(Localization.Keys.Launcher.ComponentRegisterEnd)); + await _owner.LoadHotfixModuleAsync(); + } + + /// + /// 停用(有意空实现):热更业务清理不随本模块停用——多 Role 进程逐 Role 停用会提前 teardown 热更 + ///(现状为仅首个 Role 退出尾部停一次),保持不动交服务生命周期收敛阶段重构。 + /// + /// 取消令牌(不使用)。 + /// 已完成的任务。 + public Task DeactivateAsync(CancellationToken cancellationToken) + { + return Task.CompletedTask; + } +} diff --git a/GameFrameX.Launcher/Composition/RuntimeCompositionRoot.cs b/GameFrameX.Launcher/Composition/RuntimeCompositionRoot.cs new file mode 100644 index 000000000..4d1f62afa --- /dev/null +++ b/GameFrameX.Launcher/Composition/RuntimeCompositionRoot.cs @@ -0,0 +1,356 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using System.Text.Json; +using GameFrameX.Capability.Hosting.Abstractions; +using GameFrameX.Capability.Hosting.AdminApi; +using GameFrameX.Capability.Hosting.Core; +using GameFrameX.Capability.Online.Abstractions; +using GameFrameX.Capability.Online.Abstractions.Contracts; +using GameFrameX.Capability.Online.Assets; +using GameFrameX.Capability.Online.Foundation.Identity; +using GameFrameX.Capability.Online.Foundation.Storage; +using GameFrameX.Capability.Online.Operations.HotfixRollback; +using GameFrameX.Capability.Online.Persistence.Assets; +using GameFrameX.Capability.Online.Persistence.Identity; +using GameFrameX.Capability.Online.Persistence.Social; +using GameFrameX.Capability.Online.Persistence.Storage; +using GameFrameX.Capability.Online.Match; +using GameFrameX.Capability.Online.Persistence.Match; +using GameFrameX.Foundation.Localization.Core; +using GameFrameX.Foundation.Logger; +using GameFrameX.Launcher.Online; +using GameFrameX.Localization; +using GameFrameX.Capability.Online.Social; + +namespace GameFrameX.Launcher.Composition; + +/// +/// 运行时组合根协调器(实例形态,取代退役的静态 OnlineCapabilityCompositionRoot): +/// 为每个 Role 经 组装「早晚宿主模块 + (启用时)online 能力族」的统一运行时, +/// 并承载进程级族互斥闸与组合者登记(原静态字段迁实例)。 +/// +/// +/// The runtime composition-root coordinator (an instance shape, replacing the retired static +/// OnlineCapabilityCompositionRoot): composes, per role and through , +/// the unified runtime of "early/late host modules + (when enabled) the online capability family", and +/// carries the process-level family mutual-exclusion gate and the composer registration (the former +/// static fields migrated onto this instance). 维护约束(红线): +/// ① 组合根唯一——一切装配经 (机制内 CapabilityHostBuilder 定序), +/// 本类只做族判定、Options 组装与宿主模块声明,不自带启停定序; +/// ② 同族进程内单例——多 Role 进程首个 EnableRoles 命中的 Role 携带族模块组合,其余命中 Role +/// 只装配宿主模块(互斥闸),族的停止随组合者 Role 的运行时停机(逆序停机下组合者最后停); +/// ③ 双闸全关 / 配置段缺席 / Role 未命中时走无族组合(宿主模块 only,零族装配零族日志——现状等价); +/// ④ admin-only 形态(EnableRuntime=false 且 EnableAdminApi=true)经独立的族运行时承载 +/// (仅管理面),其启动点在宿主运行时启动之后(管理面模块注册面不依赖旧栈),停止先于宿主运行时。 +/// Red lines: a single composition root — every assembly goes through +/// (ordered by the mechanism's CapabilityHostBuilder), this class only decides family inclusion, +/// builds options and declares host modules with no ordering of its own; one family composition per +/// process; the family-less path for disabled/unmatched roles keeps zero family assembly and zero family +/// logging; the admin-only shape rides a separate family runtime started after the host runtime and +/// stopped before it. +/// +internal sealed class RuntimeCompositionRoot +{ + /// + /// 族组合互斥闸(0 = 未组合 / 组合失败已复位,1 = 有 Role 正在组合或已完成组合)。 + /// + private int _familyComposed; + + /// + /// 族组合者 Role 名(ServerType;未组合为 null)。族的停止只归组合者 Role。 + /// + private string _composerServerType; + + /// + /// admin-only 形态的族运行时(仅管理面;未组合为 null)。 + /// + private CapabilityRuntime _adminOnlyFamilyRuntime; + + /// + /// 组装并启动一个 Role 的统一运行时:判定族启用形态 → 组装(宿主模块恒在)→ 启动。 + /// + /// 宿主回调面(启动模板实例)。 + /// 本 Role 的组合产物(停机由调用方持有并驱动)。 + public async Task ComposeAndStartAsync(ILegacyRuntimeHostOwner owner) + { + var setting = owner.Setting; + var online = setting.Online; + var familyRequested = online != null && IsRoleEnabled(online, setting.ServerType) && (online.EnableRuntime || online.EnableAdminApi); + + if (familyRequested && online.EnableRuntime) + { + // 同族进程内单例:首个命中 Role 携带族模块组合,后续命中 Role 只装配宿主模块。 + if (System.Threading.Interlocked.CompareExchange(ref _familyComposed, 1, 0) != 0) + { + return await ComposeAndStartHostRuntimeAsync(setting, owner); + } + + CapabilityRuntime runtime = null; + try + { + var options = BuildFamilyCompositionOptions(setting, enableRuntime: true); + AddHostModules(options, owner); + runtime = CapabilityComposition.Compose(new OnlineCapabilityFamily(), options); + _composerServerType = setting.ServerType; + await runtime.StartAsync(); + return runtime; + } + catch + { + await StopFailedRuntimeAsync(runtime); + _composerServerType = null; + System.Threading.Volatile.Write(ref _familyComposed, 0); + throw; + } + } + + if (familyRequested) + { + // admin-only 形态:宿主运行时承载旧栈;族运行时仅承载管理面(模块注册即可用,不激活), + // 启动于宿主运行时之后——管理面查询到达时旧栈已就绪。 + var hostRuntime = await ComposeAndStartHostRuntimeAsync(setting, owner); + if (System.Threading.Interlocked.CompareExchange(ref _familyComposed, 1, 0) != 0) + { + return hostRuntime; + } + + // admin-only 族运行时(仅管理面)。启动失败 = 组合失败:尽力停止已启动部分、复位族闸后重抛 + //(宿主运行时一并停机,不留无法回收的监听/调度残骸——调用方模板的失败补齐路径完成收尾)。 + _composerServerType = setting.ServerType; + try + { + var adminOptions = BuildFamilyCompositionOptions(setting, enableRuntime: false); + _adminOnlyFamilyRuntime = CapabilityComposition.Compose(new OnlineCapabilityFamily(), adminOptions); + await _adminOnlyFamilyRuntime.StartAsync(); + return hostRuntime; + } + catch + { + await StopFailedRuntimeAsync(_adminOnlyFamilyRuntime); + _adminOnlyFamilyRuntime = null; + _composerServerType = null; + System.Threading.Volatile.Write(ref _familyComposed, 0); + await StopFailedRuntimeAsync(hostRuntime); + throw; + } + } + + // 族未启用(配置段缺席 / Role 未命中 / 双闸全关):无族组合承载旧栈,零族装配零族日志(现状等价)。 + return await ComposeAndStartHostRuntimeAsync(setting, owner); + } + + /// + /// 摘取 admin-only 族运行时(仅组合者 Role 匹配;摘取后由调用方停机——先于宿主运行时停机)。 + /// + /// 调用方 Role 名(ServerType)。 + /// admin-only 族运行时;非组合者 / 未组合 / 已摘取时为 null。 + public CapabilityRuntime DetachAdminOnlyFamilyRuntime(string serverType) + { + if (_adminOnlyFamilyRuntime == null || !string.Equals(_composerServerType, serverType, System.StringComparison.Ordinal)) + { + return null; + } + + var runtime = _adminOnlyFamilyRuntime; + _adminOnlyFamilyRuntime = null; + return runtime; + } + + /// + /// 组装并启动无族宿主运行时(早晚宿主模块 only;无族组合不渲染装配报告——旧栈步骤自身有日志,现状等价)。 + /// + /// 当前 Role 的应用配置。 + /// 宿主回调面。 + /// 宿主组合产物。 + private static async Task ComposeAndStartHostRuntimeAsync(AppSetting setting, ILegacyRuntimeHostOwner owner) + { + var options = new CapabilityCompositionOptions(default(JsonElement), new LogHelperCapabilityAssemblyLog()) + { + EnableRuntime = true, + // 无族形态无能力模块消费作用域三元组;机制要求合法值(>0),未配置段回落 1 占位。 + HostOptions = BuildHostOptions(setting), + }; + AddHostModules(options, owner); + + CapabilityRuntime runtime = null; + try + { + runtime = CapabilityComposition.Compose(options); + await runtime.StartAsync(); + return runtime; + } + catch + { + await StopFailedRuntimeAsync(runtime); + throw; + } + } + + /// + /// 构造宿主选项(作用域单键化 D4 后仅 ServerId,未配置(<=0)回落 1 占位——宿主模块不消费作用域,仅满足机制合法性校验)。 + /// + /// 当前 Role 的应用配置。 + /// 宿主选项。 + private static CapabilityHostOptions BuildHostOptions(AppSetting setting) + { + return new CapabilityHostOptions + { + ServerId = setting.ServerId > 0 ? setting.ServerId : 1, + }; + } + + /// + /// 声明早晚宿主模块(早段承载 DB/发现/组件/热更;晚段承载监听/ServiceOnline/屏障/Active)。 + /// + /// 组合选项。 + /// 宿主回调面。 + private static void AddHostModules(CapabilityCompositionOptions options, ILegacyRuntimeHostOwner owner) + { + options.AddHostModule(new LegacyRuntimeHostModule(owner), CapabilityHostModulePhase.BeforeCapabilities); + options.AddHostModule(new LegacyNetworkListenerHostModule(owner), CapabilityHostModulePhase.AfterCapabilities); + } + + /// + /// 组合失败路径的尽力停止:撤回已启动部分,停止自身的异常只记日志,不得覆盖触发回滚的原异常。 + /// + /// 已创建的运行时(可能为 null)。 + private static async Task StopFailedRuntimeAsync(CapabilityRuntime runtime) + { + if (runtime == null) + { + return; + } + + try + { + await runtime.StopAsync(); + } + catch (System.Exception stopException) + { + LogHelper.Error(stopException.ToString()); + } + } + + /// + /// 构造 Online 族组合选项(族配置段 JSON + 双闸 + 作用域三元组 + 能力过滤器 + 管理面 + 宿主 Override 面)—— + /// 等价迁移自退役的静态组合根。 + /// + /// 当前 Role 的应用配置。 + /// 业务运行面闸(admin-only 形态传 false)。 + /// 族组合选项。 + private static CapabilityCompositionOptions BuildFamilyCompositionOptions(AppSetting setting, bool enableRuntime) + { + var online = setting.Online; + var options = new CapabilityCompositionOptions(BuildFamilyConfigurationSection(setting), new LogHelperCapabilityAssemblyLog()) + { + EnableRuntime = enableRuntime, + HostOptions = new CapabilityHostOptions + { + ServerId = setting.ServerId, + }, + Filter = new CapabilityAssemblyFilter(online.Capabilities, online.Disable), + }; + + if (online.EnableAdminApi) + { + options.UseAdminApi(adminOptions => + { + adminOptions.AdminPort = setting.OnlineAdminPort; + adminOptions.AdminApiPrefix = setting.OnlineAdminApiPrefix; + }); + } + + // 宿主扩展点(Override 注入,来源 = 宿主组合根):Hotfix 版本切换执行器、玩家目录与回滚状态日志。 + // 类型实参必须显式写成契约接口:描述符表按类型键索引,省略时推断为具型,模块的 RequireHostService<契约> 找不到覆盖。 + options.Override(new HotfixManagerRollbackExecutor(setting)); + options.Override(new HostPlayerDirectory()); + options.Override(new LogHelperHotfixRollbackLog()); + + // GameDb 一级 store 覆盖(Online.UseGameDbStores 三态):true 预置五个持久化适配器(业务库已就绪由宿主模块早段保证); + // 未声明(null)= 无声降级防护位——启用族但未声明存储模式时告警(不 fail-fast,保护既有无键部署),随后保持 InMemory 默认。 + if (online.UseGameDbStores == true) + { + options.Override(new GameDbOnlineIdentityStore()); + options.Override(new GameDbOnlinePlayerStorageStore()); + options.Override(new GameDbOnlineAssetStore()); + options.Override(new GameDbOnlineAssetTransactionStore()); + options.Override(new GameDbOnlineFriendStore()); + var matchSettlementStore = new GameDbOnlineMatchSettlementStore(); + options.Override(matchSettlementStore); + options.Override(matchSettlementStore); + } + else if (OnlineCapabilityStoreModePolicy.ShouldWarnStoreModeUndeclared(online)) + { + LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Capability.OnlineModule.UseGameDbStoresUndeclared, setting.ServerType)); + } + + return options; + } + + /// + /// 判定 EnableRoles(缺省 ["Game"])是否命中本 Role。 + /// + /// Online 配置段。 + /// 本 Role 名(ServerType)。 + /// 命中返回 true。 + private static bool IsRoleEnabled(OnlineCapabilityOptions online, string serverType) + { + var enableRoles = online.GetEffectiveEnableRoles(); + for (var index = 0; index < enableRoles.Count; index++) + { + if (string.Equals(enableRoles[index], serverType, System.StringComparison.Ordinal)) + { + return true; + } + } + + return false; + } + + /// + /// 重建族配置段原始 JSON(族级键 + Settings 节点):族脊柱包读取 ServerId 落授权作用域(单键化 D4), + /// 机制 Options 绑定器读取 Settings.<能力Id> 做能力级参数覆盖。 + /// + /// 当前 Role 的应用配置。 + /// 族配置段 JSON 节点。 + private static JsonElement BuildFamilyConfigurationSection(AppSetting setting) + { + var online = setting.Online; + var section = new Dictionary + { + ["ServerId"] = setting.ServerId, + ["EnableRuntime"] = online.EnableRuntime, + ["EnableAdminApi"] = online.EnableAdminApi, + ["UseGameDbStores"] = online.UseGameDbStores, + ["Settings"] = online.Settings.ValueKind == JsonValueKind.Undefined || online.Settings.ValueKind == JsonValueKind.Null ? new Dictionary() : online.Settings, + }; + return JsonSerializer.SerializeToElement(section); + } +} diff --git a/GameFrameX.Launcher/GameFrameX.Launcher.csproj b/GameFrameX.Launcher/GameFrameX.Launcher.csproj index 27f26b63c..aad10e030 100644 --- a/GameFrameX.Launcher/GameFrameX.Launcher.csproj +++ b/GameFrameX.Launcher/GameFrameX.Launcher.csproj @@ -25,6 +25,11 @@ + + + + + diff --git a/GameFrameX.Launcher/Online/OnlineCapabilityCompositionRoot.cs b/GameFrameX.Launcher/Online/OnlineCapabilityCompositionRoot.cs deleted file mode 100644 index dc10260b7..000000000 --- a/GameFrameX.Launcher/Online/OnlineCapabilityCompositionRoot.cs +++ /dev/null @@ -1,335 +0,0 @@ -// ========================================================================================== -// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 -// GameFrameX organization and its derivative projects' copyrights, trademarks, patents and related rights -// 均受中华人民共和国及相关国际法律法规保护。 -// are protected by the laws of the People's Republic of China and related international regulations. -// 使用本项目须严格遵守相应法律法规及开源许可证之规定。 -// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. -// 本项目采用 Apache License 2.0 单协议分发, -// This project is licensed solely under the Apache License 2.0, -// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 -// please refer to the LICENSE file in the root directory of the source code for the full license text. -// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 -// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, -// 侵犯他人合法权益等法律法规所禁止的行为! -// Any legal disputes and liabilities arising from secondary development based on this project -// shall be borne solely by the developer; the project organization and contributors assume no responsibility. -// GitHub 仓库:https://github.com/GameFrameX -// GitHub Repository: https://github.com/GameFrameX -// Gitee 仓库:https://gitee.com/GameFrameX -// Gitee Repository: https://gitee.com/GameFrameX -// CNB 仓库:https://cnb.cool -// CNB Repository: https://cnb.cool -// 官方文档:https://gameframex.doc.alianblank.com/ -// Official documentation: https://gameframex.doc.alianblank.com/ -// ========================================================================================== - - -using System.Collections.Generic; -using System.Text.Json; -using System.Threading.Tasks; -using GameFrameX.Capability.Hosting.Abstractions; -using GameFrameX.Capability.Hosting.AdminApi; -using GameFrameX.Capability.Hosting.Core; -using GameFrameX.Capability.Online.Abstractions; -using GameFrameX.Capability.Online.Abstractions.Contracts; -using GameFrameX.Capability.Online.Assets; -using GameFrameX.Capability.Online.Foundation.Identity; -using GameFrameX.Capability.Online.Foundation.Storage; -using GameFrameX.Capability.Online.Operations.HotfixRollback; -using GameFrameX.Capability.Online.Persistence.Assets; -using GameFrameX.Capability.Online.Persistence.Identity; -using GameFrameX.Capability.Online.Persistence.Social; -using GameFrameX.Capability.Online.Persistence.Storage; -using GameFrameX.Capability.Online.Match; -using GameFrameX.Capability.Online.Persistence.Match; -using GameFrameX.Capability.Online.Social; -using GameFrameX.Foundation.Localization.Core; -using GameFrameX.Foundation.Logger; -using GameFrameX.Localization; -using GameFrameX.Utility.Setting; - -namespace GameFrameX.Launcher.Online; - -/// -/// Online 能力族组合根(C294,替代退役的旧 Launcher 单入口装配): -/// 模板序列的固定步骤经本类型组装 online 族——构造 -///(族配置段 JSON + LogHelper 装配日志 + 双闸 + 作用域三元组 + 能力过滤器 + 管理面监听), -/// 经 产出 并启动。 -/// -/// 维护约束(红线): -/// ① 同族进程内单例——--AllInOne 多 Role 进程中首个 EnableRoles 命中的 Role 完成组合, -/// 其余命中 Role 直接复用( 的互斥闸),停止由组合 Role 的停机步承担; -/// ② 宿主扩展点全部走 Override<T>——Hotfix 版本切换执行器、玩家目录、 -/// GameDb 一级 store 覆盖(Online.UseGameDbStores,五 store 适配器来自 Persistence 包); -/// ③ 双闸全关(EnableRuntime 与 EnableAdminApi 均 false)时零装配零日志(现状等价); -/// ④ 族配置段以原始 JSON 重建(族级键 + 机制使用的 Settings 节点),能力级参数由机制 Options -/// 绑定器逐字段合并、未知键 fail-fast。 -/// -/// -/// -/// The Online capability-family composition root (C294, replacing the retired Launcher single-entry -/// assembly): the fixed template-sequence step assembles the online family through this -/// type — building the (the family configuration-section -/// JSON, the LogHelper assembly log, the two gates, the scope triple, the capability filter and the -/// admin listening options), producing a via -/// and starting it. Red lines: one composition per -/// process for the family — under --AllInOne the first role named by EnableRoles -/// composes and the rest reuse it (the mutual-exclusion gate in ), -/// with the stop owned by the composing role's shutdown step; every host extension point rides -/// Override<T> — the hotfix rollback executor, the player directory and the GameDb -/// level-one store overrides (Online.UseGameDbStores, the five adapters from the Persistence -/// package); with both gates off nothing is assembled and no log fires; the family configuration -/// section is rebuilt as raw JSON (family keys plus the Settings node consumed by the mechanism), -/// capability-level parameters merged field-by-field by the mechanism options binder with unknown -/// keys failing fast. -/// -public static class OnlineCapabilityCompositionRoot -{ - /// - /// 进程内组合产物(同族单例;未组合为 null)。 - /// - /// - /// The in-process composition product (the per-family singleton; null before composition). - /// - private static CapabilityRuntime _runtime; - - /// - /// 组合互斥闸(0 = 未组合 / 组合失败已复位,1 = 有 Role 正在组合或已完成组合)。 - /// 维护约束:只在双闸判定通过、真正要组装时才抢闸;组装或启动失败必须复位为 0, - /// 否则后续命中 EnableRoles 的 Role 会被静默跳过。 - /// - /// - /// The composition mutual-exclusion gate (0 = not composed or reset after a failed composition, - /// 1 = a role is composing or has composed). Claimed only once the two gates pass and assembly - /// really happens; reset to 0 on any composition or start failure. - /// - private static int _composed; - - /// - /// 组合者 Role 名(ServerType;未组合为 null)。族运行时的停止只归该 Role 的停机步(设计 §4.6)。 - /// - /// - /// The composing role name (ServerType; null before composition). Only that role's shutdown - /// step stops the family runtime. - /// - private static string _composerServerType; - - /// - /// 停止单次闸(0 = 未停止,1 = 已进入停止;停机幂等护栏的族级对应物)。 - /// - /// - /// The stop-once gate (0 = running, 1 = stopping/stopped; the family-level twin of the role - /// stop guard). - /// - private static int _stopped; - - /// - /// 按配置段组合并启动 Online 能力族(模板序列固定步骤的承载入口,热更装载之后、网络监听之前调用)。 - /// 判定链:"Online" 配置段缺席 → 不组合;EnableRoles(缺省 ["Game"])不含本 Role 名 → - /// 不组合;双闸全关 → 不组合(零装配零日志,且不占用互斥闸);进程内已有组合 → 复用(本 Role 不再装配)。 - /// 其余路径完成组装并启动(启动序 = 业务宿主 → 管理面),并记录本 Role 为组合者。 - /// 失败语义:组装或启动抛异常时,已创建的运行时先尽力停止(停止失败只记日志、不覆盖原异常), - /// 再清空产物并复位互斥闸,原异常继续上抛。 - /// - /// 当前 Role 的应用配置。 - /// 表示组合与启动操作的异步任务。 - public static async Task ComposeIfEnabledAsync(AppSetting setting) - { - var online = setting.Online; - if (online == null) - { - return; - } - - if (!IsRoleEnabled(online, setting.ServerType)) - { - return; - } - - if (!online.EnableRuntime && !online.EnableAdminApi) - { - return; - } - - // 同族进程内单例:首个命中 Role 完成组合,后续 Role 复用(D6)。 - if (System.Threading.Interlocked.CompareExchange(ref _composed, 1, 0) != 0) - { - return; - } - - try - { - var options = new CapabilityCompositionOptions(BuildFamilyConfigurationSection(setting), new LogHelperCapabilityAssemblyLog()) - { - EnableRuntime = online.EnableRuntime, - HostOptions = new CapabilityHostOptions - { - ServerId = setting.ServerId, - }, - Filter = new CapabilityAssemblyFilter(online.Capabilities, online.Disable), - }; - - if (online.EnableAdminApi) - { - options.UseAdminApi(adminOptions => - { - adminOptions.AdminPort = setting.OnlineAdminPort; - adminOptions.AdminApiPrefix = setting.OnlineAdminApiPrefix; - }); - } - - // 宿主扩展点(Override 注入,来源 = 宿主组合根):Hotfix 版本切换执行器、玩家目录与回滚状态日志。 - // 类型实参必须显式写成契约接口:描述符表按类型键索引,省略时推断为具型,模块的 RequireHostService<契约> 找不到覆盖。 - options.Override(new HotfixManagerRollbackExecutor(setting)); - options.Override(new HostPlayerDirectory()); - options.Override(new LogHelperHotfixRollbackLog()); - - // GameDb 一级 store 覆盖(Online.UseGameDbStores 三态,C302):true 预置五个持久化适配器(业务库已就绪由模板顺序保证); - // 未声明(null)= 无声降级防护位——启用族但未声明存储模式时告警(不 fail-fast,保护既有无键部署),随后保持 InMemory 默认。 - if (online.UseGameDbStores == true) - { - options.Override(new GameDbOnlineIdentityStore()); - options.Override(new GameDbOnlinePlayerStorageStore()); - options.Override(new GameDbOnlineAssetStore()); - options.Override(new GameDbOnlineAssetTransactionStore()); - options.Override(new GameDbOnlineFriendStore()); - var matchSettlementStore = new GameDbOnlineMatchSettlementStore(); - options.Override(matchSettlementStore); - options.Override(matchSettlementStore); - } - else if (ShouldWarnStoreModeUndeclared(online)) - { - LogHelper.Warning(LocalizationService.GetString(Localization.Keys.Capability.OnlineModule.UseGameDbStoresUndeclared, setting.ServerType)); - } - - _runtime = CapabilityComposition.Compose(new OnlineCapabilityFamily(), options); - _composerServerType = setting.ServerType; - await _runtime.StartAsync(); - } - catch - { - await StopFailedRuntimeAsync(); - _runtime = null; - _composerServerType = null; - System.Threading.Volatile.Write(ref _composed, 0); - throw; - } - } - - /// - /// 判定是否需要发出「存储模式未声明」启动期告警(C302 无声降级防护): - /// 族被启用(双闸任一开)但 Online.UseGameDbStores 未在配置中显式声明(null)时为 true。 - /// 为什么不直接在组合点内联判定:三态口径(未声明 / 显式 true / 显式 false)是配置契约本身, - /// 收敛为纯谓词供单测直接断言,避免只能靠日志输出验证信号。 - /// 显式 false(有意选择 InMemory,如本地无库开发)与双闸全关(族未启用,零装配零日志)均不告警。 - /// - /// - /// Determines whether the "storage mode undeclared" startup warning must fire (the C302 - /// silent-degradation guard): true when the family is enabled (either gate on) yet - /// Online.UseGameDbStores was never explicitly declared in configuration (null). The - /// tri-state contract (undeclared / explicit true / explicit false) is collapsed into this pure - /// predicate so unit tests can assert it directly instead of scraping log output; an explicit - /// false (a deliberate in-memory choice, e.g. database-less local development) and both gates off - /// (family disabled: nothing assembled, nothing logged) never warn. - /// - /// 当前 Role 的 Online 配置段。 - /// 未声明存储模式且族已启用时为 true;否则为 false。 - public static bool ShouldWarnStoreModeUndeclared(OnlineCapabilityOptions online) - { - return online != null - && (online.EnableRuntime || online.EnableAdminApi) - && online.UseGameDbStores == null; - } - - /// - /// 组合失败路径的尽力停止:撤回已启动部分(桥 / 调度 / 管理面),停止自身的异常只记日志, - /// 不得覆盖触发回滚的原异常。 - /// - /// 表示停止操作的异步任务。 - private static async Task StopFailedRuntimeAsync() - { - if (_runtime == null) - { - return; - } - - try - { - await _runtime.StopAsync(); - } - catch (System.Exception stopException) - { - LogHelper.Error(stopException.ToString()); - } - } - - /// - /// 停止进程内组合产物(停 admin → 停调度 → 逆序 Deactivate → 自动撤桥)。 - /// 只有组合者 Role 的停机步真正执行族停机;非组合 Role、未组合或已停止时为空操作。 - /// - /// 调用方 Role 名(ServerType)。 - /// 表示停止操作的异步任务。 - public static async Task StopIfComposedAsync(string serverType) - { - if (_runtime == null || !string.Equals(_composerServerType, serverType, System.StringComparison.Ordinal)) - { - return; - } - - if (System.Threading.Interlocked.Exchange(ref _stopped, 1) != 0) - { - return; - } - - try - { - await _runtime.StopAsync(); - } - finally - { - _runtime = null; - } - } - - /// - /// 判定 EnableRoles(缺省 ["Game"])是否命中本 Role。 - /// - /// Online 配置段。 - /// 本 Role 名(ServerType)。 - /// 命中返回 true。 - private static bool IsRoleEnabled(OnlineCapabilityOptions online, string serverType) - { - var enableRoles = online.GetEffectiveEnableRoles(); - for (var index = 0; index < enableRoles.Count; index++) - { - if (string.Equals(enableRoles[index], serverType, System.StringComparison.Ordinal)) - { - return true; - } - } - - return false; - } - - /// - /// 重建族配置段原始 JSON(族级键 + Settings 节点):族脊柱包读取 ServerId 落授权作用域(单键化 D4), - /// 机制 Options 绑定器读取 Settings.<能力Id> 做能力级参数覆盖;JsonElement 底层 = System.Text.Json - ///(GameFrameX.Foundation.Json 5.0.0 实证引用 System.Text.Json,配置装载同为 System.Text.Json 反序列化)。 - /// - /// 当前 Role 的应用配置。 - /// 族配置段 JSON 节点。 - private static JsonElement BuildFamilyConfigurationSection(AppSetting setting) - { - var online = setting.Online; - var section = new Dictionary - { - ["ServerId"] = setting.ServerId, - ["EnableRuntime"] = online.EnableRuntime, - ["EnableAdminApi"] = online.EnableAdminApi, - ["UseGameDbStores"] = online.UseGameDbStores, - ["Settings"] = online.Settings.ValueKind == JsonValueKind.Undefined || online.Settings.ValueKind == JsonValueKind.Null ? new Dictionary() : online.Settings, - }; - return JsonSerializer.SerializeToElement(section); - } -} diff --git a/GameFrameX.Launcher/Online/OnlineCapabilityStoreModePolicy.cs b/GameFrameX.Launcher/Online/OnlineCapabilityStoreModePolicy.cs new file mode 100644 index 000000000..ed051d55b --- /dev/null +++ b/GameFrameX.Launcher/Online/OnlineCapabilityStoreModePolicy.cs @@ -0,0 +1,61 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using GameFrameX.Capability.Online.Abstractions; + +namespace GameFrameX.Launcher.Online; + +/// +/// Online 存储模式策略(纯谓词,自退役的静态组合根迁入):族被启用(双闸任一开)但 +/// Online.UseGameDbStores 未在配置中显式声明(null)时须发「存储模式未声明」启动期告警 +///(无声降级防护)。 +/// +/// +/// The Online storage-mode policy (a pure predicate, migrated from the retired static composition root): +/// the "storage mode undeclared" startup warning (the silent-degradation guard) must fire when the family +/// is enabled (either gate on) yet Online.UseGameDbStores was never explicitly declared in +/// configuration (null). 三态口径收敛为纯谓词供单测直接断言;显式 false(有意选择 InMemory,如本地 +/// 无库开发)与双闸全关(族未启用,零装配零日志)均不告警。 +/// The tri-state contract is collapsed into this pure predicate for direct unit-test assertion; an +/// explicit false (a deliberate in-memory choice) and both gates off (family disabled) never warn. +/// +public static class OnlineCapabilityStoreModePolicy +{ + /// + /// 判定是否需要发出「存储模式未声明」启动期告警:族已启用但 Online.UseGameDbStores 未显式声明时为 true。 + /// + /// 当前 Role 的 Online 配置段。 + /// 未声明存储模式且族已启用时为 true;否则为 false。 + public static bool ShouldWarnStoreModeUndeclared(OnlineCapabilityOptions online) + { + return online != null + && (online.EnableRuntime || online.EnableAdminApi) + && online.UseGameDbStores == null; + } +} diff --git a/GameFrameX.Launcher/StartUp/AppStartUpGame.cs b/GameFrameX.Launcher/StartUp/AppStartUpGame.cs index 96c369a4a..f0820c97e 100644 --- a/GameFrameX.Launcher/StartUp/AppStartUpGame.cs +++ b/GameFrameX.Launcher/StartUp/AppStartUpGame.cs @@ -44,20 +44,18 @@ namespace GameFrameX.Launcher.StartUp; /// /// 组合根边界:本类所在启动模板序列( /// 模板钩子 + 各 Role 差异覆写)负责基础设施装配——网络监听、GameDb 数据库、发现层、热更模块装载与退出编排; -/// 平台业务域服务(好友 / 资产 / 对局等)的组合自 C294 起由模板固定步骤 -/// 经 -/// CapabilityComposition.Compose 单入口承载("Online" 配置段声明启用 Role)。两层边界经 -/// 好友查询桥实证:Hotfix 协议面薄适配器经 Online 契约面进程内消费平台服务,不经本地注册表绕行。 -/// Composition-root boundary: the startup template sequence (the -/// template hooks plus per-role overrides) assembles the -/// infrastructure — network listeners, the GameDb database, the discovery layer, hotfix module loading -/// and exit orchestration — while since C294 the composition of platform domain services (friends, -/// assets, matches, ...) is carried by the fixed template step -/// through the single -/// CapabilityComposition.Compose entry (enabled roles declared in the "Online" configuration -/// section). The two-layer boundary is proven by the friend-query bridge: the Hotfix protocol thin -/// adapter consumes the platform services in-process through the Online contract face, never through -/// the local registry. +/// 平台业务域服务(好友 / 资产 / 对局等)的组合经统一组合根( +/// → CapabilityComposition.Compose 单入口)承载:旧栈固定序列包装为早晚宿主模块与能力模块进入同一运行时 +///("Online" 配置段声明启用 Role)。两层边界经好友查询桥实证:Hotfix 协议面薄适配器经 Online 契约面 +/// 进程内消费平台服务,不经本地注册表绕行。 +/// Composition-root boundary: the startup template assembles the role differences through hooks while +/// since the dual-assembly convergence the composition of the legacy fixed sequence (wrapped as the +/// early/late host modules) and the platform domain services (friends, assets, matches, ...) both ride +/// the single composition root ( → +/// CapabilityComposition.Compose, enabled roles declared in the "Online" configuration section) +/// into one runtime. The two-layer boundary is proven by the friend-query bridge: the Hotfix protocol +/// thin adapter consumes the platform services in-process through the Online contract face, never +/// through the local registry. /// // 显式优先级修复与 Social 同为缺省 1000 的冲突——Game 为主服务先起(值越小优先级越高) [StartUpTag(GameServerConst.Game.Name, 100)] @@ -80,7 +78,7 @@ internal sealed class AppStartUpGame : AppStartUpGameServerBase protected override async Task ShutdownAsync(string exitMessage) { await StopAsync(exitMessage ?? ""); - await HotfixManager.StopAsync(exitMessage); + await GameFrameX.Core.Hotfix.HotfixRuntime.ProcessDefault.StopAsync(exitMessage); } diff --git a/GameFrameX.Launcher/StartUp/AppStartUpGameServerBase.cs b/GameFrameX.Launcher/StartUp/AppStartUpGameServerBase.cs index 896ad9c1a..ccc8b9b00 100644 --- a/GameFrameX.Launcher/StartUp/AppStartUpGameServerBase.cs +++ b/GameFrameX.Launcher/StartUp/AppStartUpGameServerBase.cs @@ -14,75 +14,116 @@ // 侵犯他人合法权益等法律法规所禁止的行为! // or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! // 因基于本项目二次开发所产生的一切法律纠纷与责任, -// Any legal disputes and liabilities arising from secondary development based on this project +// Any legal disputes or liabilities arising from secondary development based on this project // 本组织与贡献者概不承担。 // shall be borne solely by the developer; the project organization and contributors assume no responsibility. // GitHub 仓库:https://github.com/GameFrameX // GitHub Repository: https://github.com/GameFrameX // Gitee 仓库:https://gitee.com/GameFrameX -// Gitee Repository: https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX // CNB 仓库:https://cnb.cool/GameFrameX -// CNB Repository: https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX // 官方文档:https://gameframex.doc.alianblank.com/ // Official Documentation: https://gameframex.doc.alianblank.com/ // ========================================================================================== +using GameFrameX.Apps; using GameFrameX.Apps.Common.EventData; -using GameFrameX.Core.Events; +using GameFrameX.Core.Hotfix; using GameFrameX.DataBase.Abstractions; using GameFrameX.Discovery; using GameFrameX.Foundation.Localization.Core; +using GameFrameX.Foundation.Logger; using GameFrameX.Foundation.Utility; +using GameFrameX.Launcher.Composition; +using GameFrameX.Localization; using GameFrameX.Network.Abstractions; using GameFrameX.Network.HTTP; using GameFrameX.Network.Message; +using GameFrameX.Utility.Setting; namespace GameFrameX.Launcher.StartUp; /// -/// 游戏服务器启动模板:固化「控制库 → 发现层 → 业务库 → 组件注册 → Role 服务」共享启动序列 -/// 与退出兜底,并承载与启动序列无关的组合件——停机幂等护栏、缺省配置收口与三段数据库/发现层装配件; -/// 差异点全部经 hook 下放( / / -/// / )。 +/// 游戏服务器启动模板:固化「启动日志 → Role 预备 → ActorLimit → 统一组合启动」共享启动序列与退出兜底; +/// 旧栈固定装配步骤(DB 初始化 → 发现层激活 → 组件注册 → 热更装载 → 网络监听 → ServiceOnline → 就绪屏障 → +/// 心跳 Active)与能力族激活统一经组合根( → CapabilityComposition) +/// 装配为早晚宿主模块 + 能力模块的同一运行时,由机制拓扑序定序(等价旧序列「热更 → 能力 → 监听」); +/// 停机所有权统一到 CapabilityRuntime.StopAsync(晚段模块停用 = ServiceOffline + 网络停机与退出令牌置位, +/// 随后能力族逆序停用)。差异点全部经 hook 下放( / / +/// / )。 /// /// -/// The single-layer game-server startup template: freezes the shared startup sequence -/// (control database → discovery layer → business database → component registration → role services) -/// together with the exit catch-all, and hosts the sequence-independent composable parts directly — -/// the idempotent stop guard, the default-setting funnel and the three database / discovery wiring -/// steps — pushing every role difference down to hooks. 序列方法 sealed 是刻意选择: -/// 防止装配序列在派生类再分叉;自拟序列的异形 Role(无库网关、自拟装配顺序)直承 -/// 自行编排启动序列——护栏、缺省配置收口与装配件届时按需重新抽取 -///(机械操作,非单向门)。 -/// Sealing the sequence is deliberate — it prevents the assembly sequence from forking again in -/// derived classes; free-form roles (library-less gateways, custom assembly orders) derive -/// directly and orchestrate their own startup — the guard, the funnel -/// and the wiring parts would be re-extracted on demand at that point (a mechanical move, not a -/// one-way door). -/// 单进程多 Role(--AllInOne / 复数 --ServerType)与多进程单 Role 两形态兼容:共享装配步骤幂等 -///(控制库/业务库 Contains 守卫、发现层 Activate 一次性守卫、默认库 set-once), -/// 屏障保持在各 Role 的 DB/组件/Role 服务全就绪之后 -///(优先级链启动语义不变);多进程形态下单 Role 进程的屏障置位无人等待、无副作用。 -/// Compatible with both the single-process multi-role shape (--AllInOne / multiple --ServerType) -/// and the multi-process single-role shape: the shared wiring steps stay idempotent, the -/// startup-ready barrier is still set only after each role's databases, components and role -/// services are all up (the priority-chain startup semantics are unchanged), and in the -/// multi-process shape nobody awaits the barrier, which is harmless. +/// The game-server startup template: freezes the shared startup sequence (start logging → role +/// preparation → ActorLimit → the unified composition start) together with the exit catch-all; the +/// legacy fixed assembly steps (database initialization → discovery activation → component registration +/// → hotfix loading → network listening → ServiceOnline → the ready barrier → the Active heartbeat) and +/// the capability-family activation are composed — through the composition root +/// ( → CapabilityComposition) — into one runtime of early/late host +/// modules plus capability modules, ordered by the mechanism's topological order (equivalent to the +/// legacy "hotfix → capability → listen" sequence); the stop ownership unifies on +/// CapabilityRuntime.StopAsync (the late module's deactivation = ServiceOffline plus the network +/// shutdown and exit-token settlement, followed by the capability family's reverse-order teardown). +/// Every role difference rides hooks. 序列方法 sealed 是刻意选择:防止装配序列在派生类再分叉;自拟序列的 +/// 异形 Role(无库网关、自拟装配顺序)直承 自行编排启动序列——护栏、缺省配置 +/// 收口与装配件届时按需重新抽取(机械操作,非单向门)。 +/// Sealing the sequence is deliberate — it prevents the assembly sequence from forking again in derived +/// classes; free-form roles derive directly and orchestrate their own +/// startup, re-extracting the guard, the funnel and the wiring parts on demand. 单进程多 Role +///(--AllInOne / 复数 --ServerType)与多进程单 Role 两形态兼容:共享装配步骤幂等(控制库/业务库 Contains +/// 守卫、发现层 Activate 一次性守卫、默认库 set-once、热更装载同路径幂等守卫), +/// 屏障保持在各 Role 的全就绪之后(优先级链启动语义不变); +/// 能力族同族进程内单例(首个命中 Role 携带族模块组合,其余命中 Role 只装配宿主模块——族停止随组合者 +/// Role 的运行时停机,逆序停机下组合者最后停)。 +/// Compatible with both the single-process multi-role shape and the multi-process single-role shape: +/// the shared wiring steps stay idempotent, the startup-ready barrier is still set only after each +/// role is fully up, and the capability family composes once per process (the first named role carries +/// the family modules; the family stops with the composer role's runtime, which stops last under the +/// reverse-order shutdown). /// -internal abstract class AppStartUpGameServerBase : AppStartUpBase +internal abstract class AppStartUpGameServerBase : AppStartUpBase, ILegacyRuntimeHostOwner { /// - /// 启动游戏服务器(sealed 模板序列):启动日志 → Role 预备 → ActorLimit → 控制库 → 发现层 → - /// 业务库 → 组件注册 → Role 服务 → 启动完成 → 主循环/就绪屏障 → 心跳 Active → 运行至退出令牌; - /// 任何一步失败落入统一兜底(异常日志 + Fatal),随后退出清理 hook 收尾。 + /// 进程级组合根协调器锚点(族互斥闸与组合者登记的进程共享载体;实例状态全部在协调器实例内, + /// 锚点仅是进程作用域引用——组合根唯一红线由 GFX 分析器在静态类层面固化)。 + /// + /// + /// The process-level composition-root coordinator anchor (the process-shared carrier of the family + /// gate and the composer registration; all mutable state lives on the coordinator instance — the + /// anchor is merely a process-scoped reference, and the single-composition-root red line is pinned + /// by the GFX analyzer at the static-class level). + /// + private static readonly RuntimeCompositionRoot ProcessCompositionRoot = new RuntimeCompositionRoot(); + + /// + /// 本 Role 的组合产物(宿主实例字段——迁移自退役静态根的 _runtime;停机所有权所在)。 + /// + private Capability.Hosting.Core.CapabilityRuntime _composedRuntime; + + /// + /// 本次停机原因(停机护栏内置位;晚段模块停用序列经 回读)。 + /// + private string _stopMessage; + + /// + /// 启动序列完成标志(就绪屏障放行时置位;未置位时的停机走启动失败补齐路径)。 + /// + private volatile bool _startupSequenceCompleted; + + /// + /// 启动游戏服务器(sealed 模板序列):启动日志 → Role 预备 → ActorLimit → 统一组合启动 + ///(早段宿主模块:控制库 → 发现层 → 业务库 → 组件注册 → 热更装载;能力模块:拓扑序激活; + /// 晚段宿主模块:网络监听 → KCP 发布 → ServiceOnline → 就绪屏障 → 心跳 Active)→ + /// 运行至退出令牌;任何一步失败落入统一兜底(异常日志 + Fatal),随后退出清理 hook 收尾。 /// /// /// Starts the game server (the sealed template sequence): start logging → role preparation → - /// ActorLimit → control database → discovery layer → business database → component - /// registration → role services → startup completion → main-loop/ready-barrier → heartbeat - /// Active → run until the exit token; any failure falls into the unified catch-all - /// (exception log + Fatal) and the exit-cleanup hook closes the run. + /// ActorLimit → the unified composition start (the early host module: control database → discovery → + /// business database → component registration → hotfix load; the capability modules activate in + /// topological order; the late host module: network listening → kcp publish → ServiceOnline → the + /// ready barrier → the Active heartbeat) → run until the exit token; any failure falls into the + /// unified catch-all (exception log + Fatal) and the exit-cleanup hook closes the run. /// /// 表示异步启动操作的任务(运行至退出后完成)/ A task that completes after the run-until-exit cycle public sealed override async Task StartAsync() @@ -106,41 +147,10 @@ public sealed override async Task StartAsync() LogHelper.Debug(LocalizationService.GetString(Localization.Keys.Launcher.ActorLimitConfigEnd)); LogHelper.Debug(LocalizationService.GetString(Localization.Keys.Launcher.DatabaseServiceStartBegin)); - await InitializeControlDatabaseAsync(); - await ActivateDiscoveryLayerAsync(); - await InitializeBusinessDatabaseAsync(); + // 旧栈固定序列与能力族统一经组合根装配并启动(早段模块含 DB 三步与热更装载;晚段模块含监听与收尾)。 + _composedRuntime = await ProcessCompositionRoot.ComposeAndStartAsync(this); LogHelper.DebugConsole(LocalizationService.GetString(Localization.Keys.Launcher.DatabaseServiceStartEnd)); - LogHelper.DebugConsole(LocalizationService.GetString(Localization.Keys.Launcher.ComponentRegisterBegin)); - await ComponentRegister.InitAsync(typeof(AppsHandler).Assembly); - LogHelper.DebugConsole(LocalizationService.GetString(Localization.Keys.Launcher.ComponentRegisterEnd)); - - await StartRoleServicesAsync(); - - // KCP 附加端点发布:在 Role 服务(含 KCP 监听器装配)完成后、就绪屏障与心跳 Active 之前执行。 - // 屏障前发布是刻意的——Role 按就绪屏障串行启动,屏障之后本 Role 的实例级闸门读数可能被同进程 - // 后续 Role 的装配污染;Booting 实例不进任何路由视图,广播前置不会提前暴露端点。 - // Publish the kcp additional endpoint after role services (including the KCP listener - // assembly) complete, before the startup-ready barrier and the Active heartbeat. - // Publishing before the barrier is deliberate — roles start sequentially behind the - // barrier, and after it this role's instance-level gate reading could be polluted by a - // later role's assembly in the same process; a Booting instance never enters any route - // view, so publishing early never exposes the endpoint prematurely. - if (Setting.IsEnableInnerKcp && IsInnerKcpListenerConfigured) - { - GameFrameX.Discovery.ActiveDiscoveryRuntime.PublishActiveAdvertiseEndpoints(Setting.ServerType, new[] { KeyValuePair.Create("kcp", Setting.InnerKcpPort) }); - } - - await OnStartupCompletedAsync(); - - LogHelper.DebugConsole(LocalizationService.GetString(Localization.Keys.Launcher.EnterMainLoop)); - LogHelper.Info(LocalizationService.GetString(Localization.Keys.Launcher.ServerStartEnd, Setting.ServerType)); - // 启动阶段完成(DB/组件/Role 服务均已就绪),放行下一个 Role 的启动屏障 - MarkStartUpReady(); - // 启动阶段真正完成后才把心跳从 Booting 切到 Active,避免其他进程在服务就绪前发现本实例并投递流量; - // 未激活发现层或无广播身份时为无害 no-op。公共槽位持有实际激活的 Provider Runtime 写侧,宿主无需按 DatabaseProvider 分派 - await ActiveDiscoveryRuntime.MarkActiveAsync(); - exitMessage = await AppExitToken; } catch (Exception e) @@ -170,57 +180,6 @@ protected virtual Task PrepareAsync() return Task.CompletedTask; } - /// - /// Role 服务启动 hook(缺省 = 统一形态):热更模块装载(激活热更业务生命周期)→ - /// 能力族组合( 固定步骤)→ 网络监听启动。 - /// - /// - /// The role-services hook (default = the unified shape): hotfix module loading (which activates the - /// hotfix business lifecycle) followed by the host network listener startup. 装载走 - /// (异步入口):装载成功经 - /// 桥接 IHotfixBridge.OnLoadSuccess 激活热更生命周期(配置表/定时器/全局组件), - /// 监听所有权在宿主;同路径幂等守卫使 --AllInOne 多 Role 的重复装载短路返回。 - /// Loading goes through - /// (the async entry): a successful load activates the hotfix lifecycle (config tables, timers, global - /// components) through the IHotfixBridge.OnLoadSuccess callback while listener ownership stays - /// with the host; the same-path idempotency guard short-circuits repeated loads by extra roles in - /// --AllInOne. aop 装配自序列最前段挪入本 hook 首段:唯一消费方是 StartServerAsync, - /// 纯反射收集无 DB/状态依赖。 - /// The aop assembly moved here from the very front of the sequence: its only consumer is - /// StartServerAsync, it is pure reflection with no database or state dependency. - /// - /// 表示 hook 操作的异步任务 / A task representing the hook operation - protected virtual async Task StartRoleServicesAsync() - { - await HotfixManager.LoadHotfixModuleAsync(Setting); - await ComposeCapabilitiesAsync(); - await StartServerAsync(new DefaultMessageCompressHandler(), new DefaultMessageDecompressHandler(), HotfixManager.GetListHttpHandler(), HotfixManager.GetHttpHandler); - } - - /// - /// 能力族组合固定步骤(C294 D6):热更装载之后、网络监听之前执行——保证监听开放时桥已发布、 - /// 热更侧钩子挂载先于能力侧声明读取。当前承载 online 族(经 - /// ):"Online" 配置段的 - /// EnableRoles(缺省 ["Game"])命中本 Role 时组合并启动;同族进程内单例(--AllInOne 下 - /// 首个命中 Role 组合,后续复用),停止归本类 停机步(见 - /// OnStoppingAsync 前的组合停机调用)。 - /// - /// - /// The fixed capability-family composition step (C294 D6): runs after the hotfix load and before - /// the network listeners start — bridges are published by the time listening opens and the - /// hotfix-side hook mounts precede the capability-side declaration reads. It currently carries the - /// online family (through - /// ): when the "Online" - /// section's EnableRoles (default ["Game"]) names this role the family is composed and - /// started; one composition per process for the family (under --AllInOne the first named role - /// composes and the rest reuse it), with the stop owned by this class's stop step. - /// - /// 表示组合操作的异步任务 / A task representing the composition operation - protected virtual Task ComposeCapabilitiesAsync() - { - return GameFrameX.Launcher.Online.OnlineCapabilityCompositionRoot.ComposeIfEnabledAsync(Setting); - } - /// /// 启动完成 hook(缺省 = 统一形态,全 Role 生效):网络监听就绪后分发 ServiceOnline 事件 ///(唯一分发点——热更侧不分发)。 @@ -233,7 +192,7 @@ protected virtual Task ComposeCapabilitiesAsync() /// 表示 hook 操作的异步任务 / A task representing the hook operation protected virtual Task OnStartupCompletedAsync() { - EventDispatcher.Dispatch(0, new ServiceOnlineEventArgs(Setting.ServerType, Setting.ServerInstanceId, DateTime.UtcNow)); + GameFrameX.Core.Events.GameEventDispatcher.ProcessDefault.Dispatch(0, new ServiceOnlineEventArgs(Setting.ServerType, Setting.ServerInstanceId, DateTime.UtcNow)); return Task.CompletedTask; } @@ -246,15 +205,19 @@ protected virtual Task OnStartupCompletedAsync() private int _stopped; /// - /// 停止 Role:幂等护栏保证首个调用生效——宿主逆序停机与 Role 自停两条路径竞争时, - /// 只有第一次调用会执行 与基类停机流程 - ///(停机日志、网络停机、运行时状态与退出令牌置位),后续调用直接返回。 + /// 停止 Role:幂等护栏保证首个调用生效——停机所有权统一到 CapabilityRuntime.StopAsync: + /// admin-only 族运行时(如为本 Role 组合)先停,随后本 Role 组合产物停机(机制逆序驱动: + /// 晚段模块停用 = ServiceOffline + 网络停机与退出令牌置位 → 能力族逆序停用 → 早段模块停用); + /// 启动未达监听段的失败路径补齐旧停机尾部(ServiceOffline + 基类停机流程)保持退出令牌语义。 /// /// - /// Stops the role behind an idempotent guard: when the host's reverse-order shutdown races the - /// role's own run-until-exit self-stop, only the first caller runs - /// and the base stop flow (stop log, network shutdown, runtime state and exit-token completion); - /// later calls return immediately. 双停机路径竞争是单进程多 Role 形态的固有现象 + /// Stops the role behind an idempotent guard: the stop ownership unifies on + /// CapabilityRuntime.StopAsync — the admin-only family runtime (when composed by this role) + /// stops first, then this role's composed runtime (mechanism-driven reverse order: the late module's + /// deactivation = ServiceOffline plus the network shutdown and exit-token settlement → the capability + /// family's reverse teardown → the early module); on the startup-failure path (never reaching the + /// listener phase) the legacy stop tail is appended (ServiceOffline plus the base stop flow) to keep + /// the exit-token semantics. 双停机路径竞争是单进程多 Role 形态的固有现象 ///( 逆序停机与 Role 自停并发进入),护栏把两条路径收敛为恰好一次。 /// The dual-path stop race is inherent to the single-process multi-role shape; the guard /// collapses both paths into exactly one stop. @@ -268,41 +231,60 @@ public sealed override async Task StopAsync(string message = "") return; } - // 能力族停机(逆序于启动:停 admin → 停调度 → 逆序 Deactivate → 自动撤桥;仅组合者 Role 执行,其余 Role 与未组合为空操作)—— - // 先于本 Role 的停机流程与 ServiceOffline 分发,消费方自此收显式 8002,不残留旧桥。 - await GameFrameX.Launcher.Online.OnlineCapabilityCompositionRoot.StopIfComposedAsync(Setting.ServerType); - await OnStoppingAsync(message); - await base.StopAsync(message); + _stopMessage = message; + + // admin-only 族运行时(仅管理面)先停(等价旧序 admin-first);族随组合运行时停机的形态不经过这里。 + var adminOnlyFamilyRuntime = ProcessCompositionRoot.DetachAdminOnlyFamilyRuntime(Setting.ServerType); + if (adminOnlyFamilyRuntime != null) + { + await adminOnlyFamilyRuntime.StopAsync(); + } + + var runtime = _composedRuntime; + if (runtime != null) + { + _composedRuntime = null; + await runtime.StopAsync(); + } + + if (!_startupSequenceCompleted) + { + // 启动未达监听段(晚段模块从未激活,其停用序列不会执行):补齐旧停机尾部—— + // ServiceOffline 分发与基类停机流程(含退出令牌置位),与既有失败路径行为一致。 + await OnStoppingAsync(message); + await base.StopAsync(message); + } } /// - /// 停机钩子:护栏放行后、基类停机流程前回调恰好一次,缺省 = ServiceOffline 事件分发 - ///(唯一分发点——热更侧不分发)。 + /// 停机钩子:护栏放行后回调恰好一次,缺省 = ServiceOffline 事件分发(唯一分发点——热更侧不分发); + /// 统一形态下由晚段宿主模块的停用序列调用(先于网络停机)。 /// /// - /// The stopping hook invoked exactly once after the guard admits the first stop and before the - /// base stop flow; the default dispatches the ServiceOffline event — the single dispatch - /// point (the hotfix side does not dispatch it). + /// The stopping hook invoked exactly once after the guard admits the first stop; the default + /// dispatches the ServiceOffline event — the single dispatch point (the hotfix side does not + /// dispatch it); in the unified shape it is invoked by the late host module's deactivation sequence + /// (before the network shutdown). /// /// 终止原因(首个 调用透传)/ The termination reason passed through by the first stop call /// 表示钩子操作的异步任务 / A task representing the hook operation protected virtual Task OnStoppingAsync(string message) { - EventDispatcher.Dispatch(0, new ServiceOfflineEventArgs(Setting.ServerType, Setting.ServerInstanceId, "Stopped", DateTime.UtcNow)); + GameFrameX.Core.Events.GameEventDispatcher.ProcessDefault.Dispatch(0, new ServiceOfflineEventArgs(Setting.ServerType, Setting.ServerInstanceId, "Stopped", DateTime.UtcNow)); return Task.CompletedTask; } /// /// 退出清理 hook(缺省 = 统一形态):自停——护栏内的 , /// 宿主逆序停机先到时本调用被护栏吸收,ServiceOffline 仍恰好一次。 - /// Game 型覆写为「宿主停机(护栏内含能力族停止)→ 热更模块业务清理」两段编排。 + /// Game 型覆写为「宿主停机(护栏内含统一运行时停机)→ 热更模块业务清理」两段编排。 /// /// /// The exit-cleanup hook (default = the unified shape): self-stop through the guarded - /// — when the host's reverse-order stop wins - /// the race, the guard absorbs this call and ServiceOffline still fires exactly once. - /// The Game shape overrides it with the two-phase orchestration: the host stop (with the - /// capability-family stop inside the guard) then the hotfix module's business cleanup. + /// — when the host's reverse-order stop wins the race, the guard + /// absorbs this call and ServiceOffline still fires exactly once. The Game shape overrides it + /// with the two-phase orchestration: the host stop (with the unified-runtime stop inside the guard) + /// then the hotfix module's business cleanup. /// /// 退出原因(可能为 null——启动失败路径未获得退出消息)/ The exit reason (may be null on the startup-failure path) /// 表示 hook 操作的异步任务 / A task representing the hook operation @@ -339,28 +321,73 @@ protected override void Init() protected abstract AppSetting CreateDefaultSetting(); /// + /// 获取当前 Role 的应用配置(宿主回调面)。 + /// + AppSetting ILegacyRuntimeHostOwner.Setting + { + get { return Setting; } + } + + /// + /// 获取本次停机原因(宿主回调面;停机护栏内置位)。 + /// + string ILegacyRuntimeHostOwner.CurrentStopMessage + { + get { return _stopMessage; } + } + + /// + /// 装载热更模块(宿主回调面:经 注入面;同路径幂等守卫在实例核内, + /// --AllInOne 多 Role 的重复装载短路返回)。 + /// + /// 表示装载操作的异步任务。 + Task ILegacyRuntimeHostOwner.LoadHotfixModuleAsync() + { + return HotfixRuntime.ProcessDefault.LoadHotfixModuleAsync(Setting); + } + + /// + /// 初始化控制库(宿主回调面:桥接虚方法钩子,Role 覆写继续生效)。 + /// + /// 表示异步操作的任务。 + Task ILegacyRuntimeHostOwner.InitializeControlDatabaseAsync() + { + return InitializeControlDatabaseAsync(); + } + + /// + /// 激活发现层(宿主回调面:桥接虚方法钩子,Role 覆写继续生效)。 + /// + /// 表示异步操作的任务。 + Task ILegacyRuntimeHostOwner.ActivateDiscoveryLayerAsync() + { + return ActivateDiscoveryLayerAsync(); + } + + /// + /// 初始化业务库(宿主回调面:桥接虚方法钩子,Role 覆写继续生效)。 + /// + /// 表示异步操作的任务。 + Task ILegacyRuntimeHostOwner.InitializeBusinessDatabaseAsync() + { + return InitializeBusinessDatabaseAsync(); + } + + /// + /// 初始化控制库(宿主回调面:Contains 判重护栏 + IsDefault = false 显式声明; + /// 经 注入面)。 /// 控制库先行于业务库(D-Single 缺省回落:与业务库共用同一实例连接串), - /// 经 GameDb 统一入口判重/命名;实现类型按 DbOptions.Provider 由 GameDb 约定解析 + /// 经统一入口判重/命名;实现类型按 DbOptions.Provider 约定解析 ///(PG 路径下 DbOptions.Name 仅作注册名,数据库由连接串 Database 决定)。 - /// 控制库必须显式 IsDefault = false——门面默认库由业务库声明式提名(缺省 true), - /// 漏写会在业务库注册时抛 set-once 冲突(启动期 fail-fast)。 /// - /// - /// Initializes the control database ahead of the business database (the D-Single default - /// fallback shares the business database's connection string), registered and deduplicated - /// through the facade with the provider implementation resolved by - /// convention from DbOptions.Provider. The control database must pass - /// IsDefault = false explicitly — the facade's default database is nominated - /// declaratively by the business database (default true), and omitting it fails fast - /// with a set-once conflict when the business database registers. - /// - /// 表示异步操作的任务 / A task representing the asynchronous operation + /// 表示异步操作的任务。 protected virtual async Task InitializeControlDatabaseAsync() { + var gameDatabase = GameFrameX.DataBase.GameDatabase.ProcessDefault; // Contains 判重护栏:多 Role 进程(--AllInOne)下首个 Role 注册控制库,后续 Role 直接复用 - if (!GameDb.Contains(GameDb.ControlDatabaseName)) + if (!gameDatabase.Contains(GameFrameX.DataBase.GameDatabase.ControlDatabaseName)) { - var controlDatabaseInitResult = await GameDb.InitAsync(new DbOptions { Provider = Setting.DatabaseProvider, ConnectionString = Setting.DataBaseUrl, Name = GameDb.ControlDatabaseName, IsDefault = false, IsUseTimeZone = Setting.IsUseTimeZone, }); + var controlDatabaseInitResult = await gameDatabase.InitAsync(new DbOptions { Provider = Setting.DatabaseProvider, ConnectionString = Setting.DataBaseUrl, Name = GameFrameX.DataBase.GameDatabase.ControlDatabaseName, IsDefault = false, IsUseTimeZone = Setting.IsUseTimeZone, }); if (controlDatabaseInitResult == false) { throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Launcher.DatabaseServiceStartFailed)); @@ -386,13 +413,9 @@ protected virtual async Task InitializeControlDatabaseAsync() /// a multi-role process the first call wins. It then activates the player-routing layer /// (creates the player_route index and installs the sync target) and injects the Tier 1 /// fast-path adapter into the session manager. The provider dispatch lives in the - /// DiscoveryRuntimeResolver convention (reflecting the target runtime from - /// DiscoveryActivationOptions.Provider) so this composition root holds no - /// provider branch; the activation entry point is asynchronous and this method awaits it - /// end to end, so hosts with a SynchronizationContext never block their calling - /// thread on the activation database I/O. The routing glue assembly lives in the - /// composition-side DiscoveryRoutingWire, its route table read back branch-free through the - /// ActiveDiscoveryRuntime.RouteTableProvider slot. + /// DiscoveryRuntimeResolver convention so this composition surface holds no provider + /// branch; the routing glue assembly lives in the composition-side DiscoveryRoutingWire, + /// its route table read back branch-free through the ActiveDiscoveryRuntime.RouteTableProvider slot. /// protected virtual async Task ActivateDiscoveryLayerAsync() { @@ -400,7 +423,7 @@ protected virtual async Task ActivateDiscoveryLayerAsync() await DiscoveryRuntimeResolver.ActivateAsync(new DiscoveryActivationOptions { Provider = Setting.DatabaseProvider, - ConnectionName = GameDb.ControlDatabaseName, + ConnectionName = GameFrameX.DataBase.GameDatabase.ControlDatabaseName, HostedRoleNames = RoleSet.Current, PlayerRouteFastPath = GameFrameX.Core.Session.PlayerSessionFastPathAdapter.Instance, }); @@ -410,10 +433,6 @@ await DiscoveryRuntimeResolver.ActivateAsync(new DiscoveryActivationOptions // 本服发现层实例 Id 注入(与心跳自描述符同源):PlayerSessionManager 的路由同步写真实实例 Id, // 跨服推送按 player_route.InstanceId 实例直达。仅观察形态(未配置广播端口)为 null——路由同步跳过。 - // Inject the local discovery instance id (same source as the heartbeat self descriptor): - // the session manager's route sync then writes the real instance id and cross-server pushes - // dial the exact instance recorded in player_route. Null for observe-only processes (no - // advertise port) — the route sync is skipped there. GameFrameX.Core.Session.PlayerSessionManager.Instance.LocalDiscoveryInstanceId = GameFrameX.Discovery.Routing.PlayerRouteResolverBootstrap.LocalInstanceId; // 路由胶水装配自 Runtime 拆至组合侧 DiscoveryRoutingWire(发现层 Runtime 不再引用消息胶水程序集); // 路由表经公共槽位无分派回读,未激活时 null 触发 Initialize 的 ArgumentNullException fail-fast(既有语义)。 @@ -421,27 +440,26 @@ await DiscoveryRuntimeResolver.ActivateAsync(new DiscoveryActivationOptions } /// - /// 业务库 Init,实现类型按 DbOptions.Provider 由 GameDb 约定解析;缺省 IsDefault = true—— - /// 注册成功即声明式提名门面默认库,全部经 GameDb 门面的业务读写必须落在业务库 - ///(控制库已显式 IsDefault = false,先注册不会抢占门面);失败抛 。 - /// 同名判重护栏:多 Role 进程共享同名业务库时首个注册生效(GameDb.Init 拒绝同名重复注册), + /// 业务库 Init(宿主回调面;经 注入面),实现类型按 + /// DbOptions.Provider 约定解析;缺省 IsDefault = true——注册成功即声明式提名门面默认库, + /// 全部业务读写必须落在业务库(控制库已显式 IsDefault = false,先注册不会抢占门面);失败抛 + /// 。同名判重护栏:多 Role 进程共享同名业务库时首个注册生效, /// 与控制库 Contains 护卫同一多 Role 语义。 /// /// - /// Initializes the business database through the facade with the provider - /// implementation resolved by convention; IsDefault = true by default means a successful - /// registration declaratively nominates the facade's default database (the control database - /// registered earlier with IsDefault = false never steals it), and a failure throws + /// Initializes the business database through the instance facade with the provider resolved by + /// convention; IsDefault = true by default means a successful registration declaratively + /// nominates the facade's default database, and a failure throws /// . The same-name guard makes the first registration win - /// when roles of a multi-role process share one business database — the same multi-role - /// semantics as the control-database Contains guard. + /// when roles of a multi-role process share one business database. /// /// 表示异步操作的任务 / A task representing the asynchronous operation protected virtual async Task InitializeBusinessDatabaseAsync() { - if (!GameDb.Contains(Setting.DataBaseName)) + var gameDatabase = GameFrameX.DataBase.GameDatabase.ProcessDefault; + if (!gameDatabase.Contains(Setting.DataBaseName)) { - var initResult = await GameDb.InitAsync(new DbOptions { Provider = Setting.DatabaseProvider, ConnectionString = Setting.DataBaseUrl, Name = Setting.DataBaseName, IsUseTimeZone = Setting.IsUseTimeZone, }); + var initResult = await gameDatabase.InitAsync(new DbOptions { Provider = Setting.DatabaseProvider, ConnectionString = Setting.DataBaseUrl, Name = Setting.DataBaseName, IsUseTimeZone = Setting.IsUseTimeZone, }); if (initResult == false) { throw new InvalidOperationException(LocalizationService.GetString(Localization.Keys.Launcher.DatabaseServiceStartFailed)); @@ -450,19 +468,91 @@ protected virtual async Task InitializeBusinessDatabaseAsync() } /// - /// 消息处理器解析(统一形态,全 Role 生效):接热更注册表按消息 ID 解析处理器。 + /// 启动网络监听(宿主回调面:晚段宿主模块激活序列调用;消息解码/编码/压缩与热更 HTTP 处理器桥接在此装配)。 + /// + /// 表示异步操作的任务。 + Task ILegacyRuntimeHostOwner.StartNetworkListenersAsync() + { + var hotfixRuntime = HotfixRuntime.ProcessDefault; + return StartServerAsync(new DefaultMessageCompressHandler(), new DefaultMessageDecompressHandler(), hotfixRuntime.GetListHttpHandler(), hotfixRuntime.GetHttpHandler); + } + + /// + /// 启动完成钩子回调(宿主回调面:晚段宿主模块激活序列调用,虚 hook 语义保留)。 + /// + /// 表示钩子操作的异步任务。 + Task ILegacyRuntimeHostOwner.OnStartupCompletedAsync() + { + return OnStartupCompletedAsync(); + } + + /// + /// 放行启动就绪屏障并标记启动序列完成(宿主回调面:晚段宿主模块激活序列尾部调用)。 + /// + void ILegacyRuntimeHostOwner.MarkStartUpReadyBarrier() + { + _startupSequenceCompleted = true; + MarkStartUpReady(); + } + + /// + /// 心跳切 Active(宿主回调面:晚段宿主模块激活序列最后一步;未激活发现层或无广播身份时无害 no-op)。 + /// + /// 表示异步操作的任务。 + Task ILegacyRuntimeHostOwner.MarkDiscoveryActiveAsync() + { + return ActiveDiscoveryRuntime.MarkActiveAsync(); + } + + /// + /// 获取是否应发布 KCP 附加端点(宿主回调面)。 + /// + bool ILegacyRuntimeHostOwner.ShouldPublishInnerKcpEndpoint + { + get { return Setting.IsEnableInnerKcp && IsInnerKcpListenerConfigured; } + } + + /// + /// 发布 KCP 附加端点(宿主回调面:屏障前发布,Booting 实例不进路由视图)。 + /// + void ILegacyRuntimeHostOwner.PublishInnerKcpAdvertiseEndpoint() + { + GameFrameX.Discovery.ActiveDiscoveryRuntime.PublishActiveAdvertiseEndpoints(Setting.ServerType, new[] { KeyValuePair.Create("kcp", Setting.InnerKcpPort) }); + } + + /// + /// 停机钩子回调(宿主回调面:晚段宿主模块停用序列调用,虚 hook 语义保留)。 + /// + /// 终止原因。 + /// 表示钩子操作的异步任务。 + Task ILegacyRuntimeHostOwner.OnStoppingAsync(string message) + { + return OnStoppingAsync(message); + } + + /// + /// 基类停机流程(宿主回调面:晚段宿主模块停用序列收尾——停机日志 + 网络停机 + 运行时状态与退出令牌置位)。 + /// + /// 终止原因。 + /// 表示异步操作的任务。 + Task ILegacyRuntimeHostOwner.StopNetworkAndMarkStoppedAsync(string message) + { + return base.StopAsync(message); + } + + /// + /// 消息处理器解析(统一形态,全 Role 生效):接热更注册表按消息 ID 解析处理器(经 HotfixRuntime 注入面)。 /// /// /// The resolution hook of the base package funnel (the unified shape, effective for every role): - /// bridges the hotfix message-handler registry (HotfixManager.GetMessageHandler). - /// Messages without a registered handler return null and hit the funnel's - /// "handler not found" error log. + /// bridges the hotfix message-handler registry. Messages without a registered handler return + /// null and hit the funnel's "handler not found" error log. /// /// 消息ID / The message identifier /// 处理器实例;未注册时为 null / The handler instance, or null when unregistered protected override IMessageHandler ResolveMessageHandler(int messageId) { - return HotfixManager.GetMessageHandler(messageId); + return HotfixRuntime.ProcessDefault.GetMessageHandler(messageId); } /// diff --git a/GameFrameX.Localization/Keys.Capability.cs b/GameFrameX.Localization/Keys.Capability.cs index 9eddc4e38..64ae9950f 100644 --- a/GameFrameX.Localization/Keys.Capability.cs +++ b/GameFrameX.Localization/Keys.Capability.cs @@ -208,6 +208,24 @@ public static class Composition /// 用途: CapabilityComposition.Compose 时 EnableRuntime 为 false 且未设置管理面工厂 /// public const string NoPlaneEnabled = "Capability.Hosting.Composition.NoPlaneEnabled"; + + /// + /// 无族组合缺少宿主模块。 + /// + /// + /// 键名: Capability.Hosting.Composition.HostModulesRequired + /// 用途: 无族 Compose(options) 时 HostModules 为空 + /// + public const string HostModulesRequired = "Capability.Hosting.Composition.HostModulesRequired"; + + /// + /// 管理面工厂需与能力族同用。 + /// + /// + /// 键名: Capability.Hosting.Composition.AdminApiPlaneRequiresFamily + /// 用途: 无族 Compose(options) 时设置了管理面工厂(管理面属族组合产物) + /// + public const string AdminApiPlaneRequiresFamily = "Capability.Hosting.Composition.AdminApiPlaneRequiresFamily"; } /// diff --git a/GameFrameX.Localization/Localization/Messages/Resources.resx b/GameFrameX.Localization/Localization/Messages/Resources.resx index 65350f2b5..92b225f3a 100644 --- a/GameFrameX.Localization/Localization/Messages/Resources.resx +++ b/GameFrameX.Localization/Localization/Messages/Resources.resx @@ -1086,6 +1086,12 @@ No capability plane is enabled: both EnableRuntime and EnableAdminApi are false; enable at least one of them. + + The family-less composition requires at least one host infrastructure module; declare one via AddHostModule. + + + The admin API plane factory must be used with a capability family; clear it for the family-less host composition. + Admin API listening options are invalid (port / prefix). diff --git a/GameFrameX.Localization/Localization/Messages/Resources.zh-CN.resx b/GameFrameX.Localization/Localization/Messages/Resources.zh-CN.resx index 24e45d32b..27b497832 100644 --- a/GameFrameX.Localization/Localization/Messages/Resources.zh-CN.resx +++ b/GameFrameX.Localization/Localization/Messages/Resources.zh-CN.resx @@ -1087,6 +1087,12 @@ 未启用任何 Online 能力面:EnableRuntime 与 EnableAdminApi 均为 false,请至少启用其一。 + + 无族组合至少需要一个宿主基础设施模块:请经 AddHostModule 声明。 + + + 管理面工厂需与能力族同用;无族宿主组合不得设置管理面工厂。 + 管理面监听选项非法(端口 / 前缀)。 diff --git a/Tests/GameFrameX.Tests/Architecture/StaticCompositionRootAnalyzerTests.cs b/Tests/GameFrameX.Tests/Architecture/StaticCompositionRootAnalyzerTests.cs new file mode 100644 index 000000000..593489eb4 --- /dev/null +++ b/Tests/GameFrameX.Tests/Architecture/StaticCompositionRootAnalyzerTests.cs @@ -0,0 +1,196 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using System.Collections.Immutable; +using GameFrameX.Architecture.Analyzers; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace GameFrameX.Tests.Architecture; + +/// +/// GFX0022 静态组合根分析器测试:静态类持有 CapabilityRuntime / CapabilityHost 装配状态或静态调用 +/// CapabilityComposition.Compose 必报;实例组合根(实例字段持有运行时 / 实例方法调用 Compose)与 +/// 机制程序集白名单不报。机制类型以源内桩呈现(分析器按元数据名解析,桩与真实类型等价)。 +/// +public sealed class StaticCompositionRootAnalyzerTests +{ + private const string MechanismStubSource = """ +namespace GameFrameX.Capability.Hosting.Core +{ + public static class CapabilityComposition + { + public static object Compose(object family, object options) + { + return new CapabilityRuntime(); + } + } + + public sealed class CapabilityRuntime + { + } + + public sealed class CapabilityHost + { + } +} +"""; + + [Fact] + public async Task Static_class_holding_runtime_state_reports_diagnostic() + { + var compilation = CreateCompilation(MechanismStubSource + """ +namespace GameFrameX.Launcher.Sample +{ + public static class SampleStaticCompositionRoot + { + private static readonly GameFrameX.Capability.Hosting.Core.CapabilityRuntime Runtime = null; + } +} +""", "GameFrameX.Launcher.Sample"); + + var diagnostics = await GetDiagnosticsAsync(compilation, new StaticCompositionRootAnalyzer()); + + var diagnostic = Assert.Single(diagnostics, item => item.Id == "GFX0022"); + Assert.Contains("SampleStaticCompositionRoot", diagnostic.GetMessage()); + Assert.Contains("CapabilityRuntime", diagnostic.GetMessage()); + } + + [Fact] + public async Task Static_class_holding_host_state_reports_diagnostic() + { + var compilation = CreateCompilation(MechanismStubSource + """ +namespace GameFrameX.Launcher.Sample +{ + public static class SampleHostHolder + { + public static GameFrameX.Capability.Hosting.Core.CapabilityHost HostProperty { get; set; } + } +} +""", "GameFrameX.Launcher.Sample"); + + var diagnostics = await GetDiagnosticsAsync(compilation, new StaticCompositionRootAnalyzer()); + + Assert.Single(diagnostics, item => item.Id == "GFX0022"); + } + + [Fact] + public async Task Static_class_invoking_compose_reports_diagnostic() + { + var compilation = CreateCompilation(MechanismStubSource + """ +namespace GameFrameX.Launcher.Sample +{ + public static class SampleStaticComposer + { + public static object ComposeIfEnabled() + { + return GameFrameX.Capability.Hosting.Core.CapabilityComposition.Compose(null, null); + } + } +} +""", "GameFrameX.Launcher.Sample"); + + var diagnostics = await GetDiagnosticsAsync(compilation, new StaticCompositionRootAnalyzer()); + + var diagnostic = Assert.Single(diagnostics, item => item.Id == "GFX0022"); + Assert.Contains("SampleStaticComposer", diagnostic.GetMessage()); + Assert.Contains("Compose", diagnostic.GetMessage()); + } + + [Fact] + public async Task Instance_composition_root_does_not_report() + { + var compilation = CreateCompilation(MechanismStubSource + """ +namespace GameFrameX.Launcher.Sample +{ + public sealed class SampleInstanceCompositionRoot + { + private GameFrameX.Capability.Hosting.Core.CapabilityRuntime runtime; + + public object ComposeAndStart() + { + runtime = (GameFrameX.Capability.Hosting.Core.CapabilityRuntime)GameFrameX.Capability.Hosting.Core.CapabilityComposition.Compose(null, null); + return runtime; + } + } +} +""", "GameFrameX.Launcher.Sample"); + + var diagnostics = await GetDiagnosticsAsync(compilation, new StaticCompositionRootAnalyzer()); + + Assert.DoesNotContain(diagnostics, item => item.Id == "GFX0022"); + } + + [Fact] + public async Task Static_forwarding_of_runtime_parameter_does_not_report() + { + var compilation = CreateCompilation(MechanismStubSource + """ +namespace GameFrameX.Launcher.Sample +{ + public static class SampleRuntimeForwarder + { + public static void Stop(GameFrameX.Capability.Hosting.Core.CapabilityRuntime runtime) + { + } + } +} +""", "GameFrameX.Launcher.Sample"); + + var diagnostics = await GetDiagnosticsAsync(compilation, new StaticCompositionRootAnalyzer()); + + Assert.DoesNotContain(diagnostics, item => item.Id == "GFX0022"); + } + + private static async Task> GetDiagnosticsAsync(Compilation compilation, DiagnosticAnalyzer analyzer) + { + var compilationWithAnalyzers = compilation.WithAnalyzers(ImmutableArray.Create(analyzer)); + return await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync(); + } + + private static CSharpCompilation CreateCompilation(string source, string assemblyName) + { + var syntaxTree = CSharpSyntaxTree.ParseText(source, new CSharpParseOptions(LanguageVersion.CSharp10)); + var references = AppDomain.CurrentDomain + .GetAssemblies() + .Where(assembly => !assembly.IsDynamic + && !string.IsNullOrWhiteSpace(assembly.Location) + && !assembly.GetName().Name!.StartsWith("GameFrameX.", StringComparison.Ordinal)) + .Select(assembly => MetadataReference.CreateFromFile(assembly.Location)) + .GroupBy(reference => ((PortableExecutableReference)reference).FilePath) + .Select(group => group.First()) + .ToArray(); + + return CSharpCompilation.Create( + assemblyName, + [syntaxTree], + references, + new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); + } +} diff --git a/Tests/GameFrameX.Tests/Composition/LegacyHostModuleSequenceTests.cs b/Tests/GameFrameX.Tests/Composition/LegacyHostModuleSequenceTests.cs new file mode 100644 index 000000000..13c8752e5 --- /dev/null +++ b/Tests/GameFrameX.Tests/Composition/LegacyHostModuleSequenceTests.cs @@ -0,0 +1,293 @@ +// ========================================================================================== +// GameFrameX 组织及其衍生项目的版权、商标、专利及其他相关权利 +// GameFrameX organization and its derivative projects' copyrights, trademarks, patents, and related rights +// 均受中华人民共和国及相关国际法律法规保护。 +// are protected by the laws of the People's Republic of China and relevant international regulations. +// 使用本项目须严格遵守相应法律法规与开源许可证之规定。 +// Usage of this project must strictly comply with applicable laws, regulations, and open-source licenses. +// 本项目采用 Apache License 2.0 单协议分发, +// This project is licensed solely under the Apache License 2.0, +// 完整许可证文本请参见源代码根目录下的 LICENSE 文件。 +// please refer to the LICENSE file in the root directory of the source code for the full license text. +// 禁止利用本项目实施任何危害国家安全、破坏社会秩序、 +// It is prohibited to use this project to engage in any activities that endanger national security, disrupt social order, +// 侵犯他人合法权益等法律法规所禁止的行为! +// or infringe upon the legitimate rights and interests of others as prohibited by laws and regulations! +// 因基于本项目二次开发所产生的一切法律纠纷与责任, +// Any legal disputes or liabilities arising from secondary development based on this project +// 本组织与贡献者概不承担。 +// shall be borne solely by the developer; the project organization and contributors assume no responsibility. +// GitHub 仓库:https://github.com/GameFrameX +// GitHub Repository: https://github.com/GameFrameX +// Gitee 仓库:https://gitee.com/GameFrameX +// Gitee Repository: https://gitee.com/GameFrameX +// CNB 仓库:https://cnb.cool/GameFrameX +// CNB Repository: https://cnb.cool/GameFrameX +// 官方文档:https://gameframex.doc.alianblank.com/ +// Official Documentation: https://gameframex.doc.alianblank.com/ +// ========================================================================================== + +using System.Text.Json; +using GameFrameX.Capability.Hosting.Abstractions; +using GameFrameX.Capability.Hosting.Core; +using GameFrameX.Launcher.Composition; +using GameFrameX.Tests.Online; +using GameFrameX.Utility.Setting; +using Xunit; + +namespace GameFrameX.Tests.Composition; + +/// +/// 旧栈宿主模块启停顺序断言(双装配裁决):早段 (控制库 → 发现层 → +/// 业务库 → 组件注册 → 热更装载)先于能力模块激活;晚段 +///(监听 → ServiceOnline → 就绪屏障 → Active)晚于能力模块激活——等价旧模板序列「热更 → 能力 → 监听」; +/// 停用严格逆序(晚段 ServiceOffline → 网络停机 → 能力停用)。假宿主记录调用序列,无数据库 / 网络依赖。 +/// +/// +/// The legacy host-module start/stop order assertions (the dual-assembly verdict): the early +/// (control database → discovery → business database → component +/// registration → hotfix load) activates before the capability modules; the late +/// (listening → ServiceOnline → the ready barrier → +/// Active) activates after them — equivalent to the legacy template sequence +/// "hotfix → capability → listen"; deactivation follows the strict reverse order (the late module's +/// ServiceOffline → network shutdown → capability teardown). A fake owner records the call sequence +/// with no database or network dependency. +/// +public class LegacyHostModuleSequenceTests +{ + /// + /// 记录调用序列的假宿主(实现 全部成员,无副作用)。 + /// + private sealed class RecordingLegacyRuntimeHostOwner : ILegacyRuntimeHostOwner + { + /// 调用序列记录器。 + public List Calls { get; } = new List(); + + /// 无 Online 段的最小配置。 + public AppSetting Setting { get; } = new AppSetting(); + + public string CurrentStopMessage { get; set; } = "unit-test-stop"; + + public Task LoadHotfixModuleAsync() + { + Calls.Add("hotfix-load"); + return Task.CompletedTask; + } + + public Task InitializeControlDatabaseAsync() + { + Calls.Add("control-database"); + return Task.CompletedTask; + } + + public Task ActivateDiscoveryLayerAsync() + { + Calls.Add("discovery"); + return Task.CompletedTask; + } + + public Task InitializeBusinessDatabaseAsync() + { + Calls.Add("business-database"); + return Task.CompletedTask; + } + + public Task StartNetworkListenersAsync() + { + Calls.Add("listen"); + return Task.CompletedTask; + } + + public Task OnStartupCompletedAsync() + { + Calls.Add("service-online"); + return Task.CompletedTask; + } + + public void MarkStartUpReadyBarrier() + { + Calls.Add("ready-barrier"); + } + + public Task MarkDiscoveryActiveAsync() + { + Calls.Add("mark-active"); + return Task.CompletedTask; + } + + public bool ShouldPublishInnerKcpEndpoint + { + get + { + Calls.Add("kcp-check"); + return false; + } + } + + public void PublishInnerKcpAdvertiseEndpoint() + { + Calls.Add("kcp-publish"); + } + + public Task OnStoppingAsync(string message) + { + Calls.Add("service-offline:" + message); + return Task.CompletedTask; + } + + public Task StopNetworkAndMarkStoppedAsync(string message) + { + Calls.Add("network-stop:" + message); + return Task.CompletedTask; + } + } + + /// + /// 记录激活 / 停用的假模块(Id 取 zz- 前缀保证在 After 相位内按 Id 序数最后激活、最先停用—— + /// 停用逆序断言的观测点)。 + /// + private sealed class RecordingTrailingHostModule : ICapabilityModule + { + private readonly List _calls; + + public RecordingTrailingHostModule(List calls) + { + _calls = calls; + Manifest = new CapabilityManifest("zz-recording-trailing", "1.0.0"); + } + + public CapabilityManifest Manifest { get; } + + public void Register(CapabilityRegistrationContext context) + { + } + + public Task ActivateAsync(CapabilityActivationContext context, CancellationToken cancellationToken) + { + _calls.Add("trailing-activate"); + return Task.CompletedTask; + } + + public Task DeactivateAsync(CancellationToken cancellationToken) + { + _calls.Add("trailing-stop"); + return Task.CompletedTask; + } + } + + /// + /// 构造含早晚宿主模块的组合选项(作用域三元组取合法值满足机制校验)。 + /// + private static CapabilityCompositionOptions BuildOptions(RecordingLegacyRuntimeHostOwner owner) + { + var options = new CapabilityCompositionOptions(JsonSerializer.SerializeToElement(new Dictionary()), new CollectingCapabilityAssemblyLog()) + { + HostOptions = new CapabilityHostOptions { ServerId = 1, }, + }; + options.AddHostModule(new LegacyRuntimeHostModule(owner), CapabilityHostModulePhase.BeforeCapabilities); + options.AddHostModule(new LegacyNetworkListenerHostModule(owner), CapabilityHostModulePhase.AfterCapabilities); + return options; + } + + /// + /// 无族组合(宿主模块 only):启动序 = 早段序列 → 晚段序列;停用逆序 = 晚段停用(ServiceOffline → 网络停机)→ 早段停用(空)。 + /// + [Fact] + public async Task HostOnlyComposition_StartsEarlyThenLate_StopsLateFirst() + { + var owner = new RecordingLegacyRuntimeHostOwner(); + var runtime = CapabilityComposition.Compose(BuildOptions(owner)); + Assert.Null(runtime.AdminApi); + await runtime.StartAsync(); + + Assert.Equal(new[] + { + "control-database", + "discovery", + "business-database", + "hotfix-load", + "listen", + "kcp-check", + "service-online", + "ready-barrier", + "mark-active", + }, owner.Calls); + + await runtime.StopAsync(); + + // 停用严格逆序:晚段(ServiceOffline → 网络停机与退出令牌置位)先停;早段停用为有意空实现(热更停止归首个 Role 退出尾部)。 + Assert.Equal(new[] + { + "control-database", + "discovery", + "business-database", + "hotfix-load", + "listen", + "kcp-check", + "service-online", + "ready-barrier", + "mark-active", + "service-offline:unit-test-stop", + "network-stop:unit-test-stop", + }, owner.Calls); + } + + /// + /// 族合并组合:激活序(Host.Modules 即激活序)= 早段宿主模块 → 全部能力模块(机制测试族的四个槽位) + /// → 晚段宿主模块——等价旧模板序列「热更 → 能力 → 监听」;停用严格逆序:晚段宿主模块的 + /// ServiceOffline / 网络停机先于任何晚于它的模块停用执行。 + /// + [Fact] + public async Task FamilyMergedComposition_InterleavesHostBeforeCapabilitiesBeforeListener() + { + var owner = new RecordingLegacyRuntimeHostOwner(); + var moduleCalls = new List(); + var options = BuildOptions(owner); + options.AddHostModule(new RecordingTrailingHostModule(moduleCalls), CapabilityHostModulePhase.AfterCapabilities); + + var runtime = CapabilityComposition.Compose(new MechanismTestFamily(), options); + var activationOrder = runtime.Host.Modules.Select(module => module.Manifest.Id).ToList(); + + // 早段先于全部能力模块;晚段晚于全部能力模块;尾部观测模块最后。 + Assert.True(activationOrder.IndexOf("host-legacy-runtime") < activationOrder.IndexOf("mech-first"), "早段宿主模块必须先于能力模块"); + foreach (var capabilityId in new[] { "mech-first", "mech-second", "mech-third", "mech-fourth" }) + { + Assert.True(activationOrder.IndexOf(capabilityId) > activationOrder.IndexOf("host-legacy-runtime"), "能力模块必须晚于早段宿主模块: " + capabilityId); + Assert.True(activationOrder.IndexOf(capabilityId) < activationOrder.IndexOf("host-legacy-listener"), "能力模块必须早于晚段宿主模块: " + capabilityId); + } + + Assert.True(activationOrder.IndexOf("host-legacy-listener") < activationOrder.IndexOf("zz-recording-trailing"), "晚段宿主模块必须早于尾部观测模块"); + + await runtime.StartAsync(); + + // 序列级断言:热更装载先于监听(等价旧模板「热更 → 能力 → 监听」的外侧边界)。 + Assert.True(owner.Calls.IndexOf("hotfix-load") >= 0, "早段热更装载必须执行"); + Assert.True(owner.Calls.IndexOf("listen") > owner.Calls.IndexOf("hotfix-load"), "监听必须晚于热更装载"); + Assert.Contains("trailing-activate", moduleCalls); + + await runtime.StopAsync(); + + // 停用严格逆序:尾部观测模块(激活序最后)先停,随后晚段宿主模块(ServiceOffline → 网络停机)。 + Assert.True(moduleCalls.IndexOf("trailing-stop") >= 0, "尾部观测模块必须停用"); + Assert.True(owner.Calls.IndexOf("service-offline:unit-test-stop") > moduleCalls.IndexOf("trailing-stop"), "晚段 ServiceOffline 必须晚于尾部观测模块停用"); + Assert.True(owner.Calls.IndexOf("network-stop:unit-test-stop") > owner.Calls.IndexOf("service-offline:unit-test-stop"), "网络停机必须晚于 ServiceOffline"); + } + + /// + /// 无族组合入口的误用防护:无宿主模块 / 关闭运行面均 fail-fast;正常路径产出业务宿主且无管理面。 + /// + [Fact] + public void HostOnlyComposition_RejectsMisuse() + { + var emptyOptions = new CapabilityCompositionOptions(default(JsonElement), new CollectingCapabilityAssemblyLog()) + { + HostOptions = new CapabilityHostOptions { ServerId = 1, }, + }; + Assert.Throws(() => CapabilityComposition.Compose(emptyOptions)); + + var owner = new RecordingLegacyRuntimeHostOwner(); + var disabledOptions = BuildOptions(owner); + disabledOptions.EnableRuntime = false; + Assert.Throws(() => CapabilityComposition.Compose(disabledOptions)); + } +} diff --git a/Tests/GameFrameX.Tests/DataBase/GameDbCloseIsolationTests.cs b/Tests/GameFrameX.Tests/DataBase/GameDbCloseIsolationTests.cs index 3cf13a5b9..117f618b7 100644 --- a/Tests/GameFrameX.Tests/DataBase/GameDbCloseIsolationTests.cs +++ b/Tests/GameFrameX.Tests/DataBase/GameDbCloseIsolationTests.cs @@ -77,9 +77,10 @@ private static object CreateProxy(Type interfaceType, Type proxyType) private static void SetDefaultImplementation(IDatabaseService service) { - var field = typeof(GameDb).GetField("_dbServiceImplementation", BindingFlags.NonPublic | BindingFlags.Static); + // 实例核抽取后门面服务落在 GameDatabase.ProcessDefault 的实例字段上(静态壳仅转发) + var field = typeof(GameDatabase).GetField("_dbServiceImplementation", BindingFlags.NonPublic | BindingFlags.Instance); Assert.NotNull(field); - field.SetValue(null, service); + field.SetValue(GameDatabase.ProcessDefault, service); } [Fact] diff --git a/Tests/GameFrameX.Tests/Online/OnlineCapabilityStoreModeWarningTests.cs b/Tests/GameFrameX.Tests/Online/OnlineCapabilityStoreModeWarningTests.cs index 9d157ada3..c24c879ef 100644 --- a/Tests/GameFrameX.Tests/Online/OnlineCapabilityStoreModeWarningTests.cs +++ b/Tests/GameFrameX.Tests/Online/OnlineCapabilityStoreModeWarningTests.cs @@ -32,8 +32,8 @@ namespace GameFrameX.Tests.Online; /// -/// Online 存储模式未声明告警判定测试(C302 无声降级防护):组合根纯谓词 -/// OnlineCapabilityCompositionRoot.ShouldWarnStoreModeUndeclared 的三态口径—— +/// Online 存储模式未声明告警判定测试(C302 无声降级防护):策略纯谓词 +/// OnlineCapabilityStoreModePolicy.ShouldWarnStoreModeUndeclared 的三态口径—— /// 族启用(双闸任一开)且 UseGameDbStores 未声明(null)才告警; /// 显式 true / 显式 false / 双闸全关 / 配置段缺失均不告警。 /// @@ -51,7 +51,7 @@ public void Warns_WhenFamilyEnabledAndUseGameDbStoresUndeclared() EnableAdminApi = true, }; - Assert.True(OnlineCapabilityCompositionRoot.ShouldWarnStoreModeUndeclared(online)); + Assert.True(OnlineCapabilityStoreModePolicy.ShouldWarnStoreModeUndeclared(online)); } /// @@ -66,7 +66,7 @@ public void Warns_WhenOnlyAdminGateEnabledAndUndeclared() EnableAdminApi = true, }; - Assert.True(OnlineCapabilityCompositionRoot.ShouldWarnStoreModeUndeclared(online)); + Assert.True(OnlineCapabilityStoreModePolicy.ShouldWarnStoreModeUndeclared(online)); } /// @@ -89,8 +89,8 @@ public void DoesNotWarn_WhenUseGameDbStoresExplicitlyDeclared() UseGameDbStores = false, }; - Assert.False(OnlineCapabilityCompositionRoot.ShouldWarnStoreModeUndeclared(persisted)); - Assert.False(OnlineCapabilityCompositionRoot.ShouldWarnStoreModeUndeclared(volatileExplicit)); + Assert.False(OnlineCapabilityStoreModePolicy.ShouldWarnStoreModeUndeclared(persisted)); + Assert.False(OnlineCapabilityStoreModePolicy.ShouldWarnStoreModeUndeclared(volatileExplicit)); } /// @@ -105,7 +105,7 @@ public void DoesNotWarn_WhenFamilyDisabledOrSectionMissing() EnableAdminApi = false, }; - Assert.False(OnlineCapabilityCompositionRoot.ShouldWarnStoreModeUndeclared(disabled)); - Assert.False(OnlineCapabilityCompositionRoot.ShouldWarnStoreModeUndeclared(null)); + Assert.False(OnlineCapabilityStoreModePolicy.ShouldWarnStoreModeUndeclared(disabled)); + Assert.False(OnlineCapabilityStoreModePolicy.ShouldWarnStoreModeUndeclared(null)); } }