// ==========================================================================================
// 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;
using System.Text.Json;
using GameFrameX.Capability.Hosting.Abstractions;
using GameFrameX.Foundation.Json;
namespace GameFrameX.Capability.Hosting.AdminApi;
///
/// admin API 调度器(去域化 action 调度:action 注册表 + 作用域适配 + 请求标识 + 幂等包裹 + 双层信封 +
/// list_capabilities 元端点与「未安装能力」判定)。
///
/// 维护约束(横切红线,语义与既有 Online admin 管道逐语句等价):
/// 作用域判定只经组合根注入的 (禁止 Handler 自行判定);
/// HTTP 状态恒 200,业务错误只进内层 (外层信封非 0 会被 Admin
/// 判为基础设施异常);未知 action 走 UnknownAction 码,action 属于已禁用能力走
/// CapabilityNotInstalled 码并携带已装能力清单;副作用命令经
/// 包裹(Replay 原样透传首次响应原文;幂等适配器缺省时包裹位退化为直连执行);
/// 为 Unix 秒(Admin 线缆契约)。
///
///
public sealed class AdminApiDispatcher
{
///
/// action 注册表(能力侧贡献)。
///
private readonly AdminActionRegistry _registry;
///
/// 管道错误码映射(能力侧注入)。
///
private readonly AdminApiErrorCodes _errorCodes;
///
/// 作用域适配器(能力侧注入)。
///
private readonly IAdminApiScopeAdapter _scopeAdapter;
///
/// 幂等适配器(能力侧注入;null = 无幂等包裹服务,包裹位退化为直连)。
///
private readonly IAdminApiIdempotencyAdapter _idempotencyAdapter;
///
/// 宿主授权作用域。
///
private readonly AdminApiClaimedScope _authorizedScope;
///
/// 能力报告(null = 无报告面,未安装判定与元端点不可用)。
///
private readonly CapabilityReport _report;
///
/// 能力服务注册表(null = 无服务面,list_capability_services 不可用)。
///
private readonly CapabilityServices _services;
///
/// 初始化 并注册元端点(有报告面 / 服务面时)。
///
/// action 注册表(能力侧已贡献)。
/// 管道错误码映射。
/// 作用域适配器。
/// 宿主授权作用域。
/// 幂等适配器(可空)。
/// 能力报告(可空)。
/// 能力服务注册表(可空)。
public AdminApiDispatcher(AdminActionRegistry registry, AdminApiErrorCodes errorCodes, IAdminApiScopeAdapter scopeAdapter, AdminApiClaimedScope authorizedScope, IAdminApiIdempotencyAdapter idempotencyAdapter = null, CapabilityReport report = null, CapabilityServices services = null)
{
_registry = registry ?? throw new ArgumentNullException(nameof(registry));
_errorCodes = errorCodes ?? throw new ArgumentNullException(nameof(errorCodes));
_scopeAdapter = scopeAdapter ?? throw new ArgumentNullException(nameof(scopeAdapter));
_authorizedScope = authorizedScope ?? throw new ArgumentNullException(nameof(authorizedScope));
_idempotencyAdapter = idempotencyAdapter;
_report = report;
_services = services;
if (report != null)
{
registry.SetCurrentOwnerCapabilityId("mechanism");
registry.Register("list_capabilities", ListCapabilitiesAsync, false);
registry.Register("list_capability_settings", ListCapabilitySettingsAsync, false);
}
if (services != null)
{
registry.SetCurrentOwnerCapabilityId("mechanism");
registry.Register("list_capability_services", ListCapabilityServicesAsync, false);
}
registry.SetCurrentOwnerCapabilityId(null);
}
///
/// 获取已注册 action 名集合(含 list_capabilities 元端点;诊断与测试用)。
///
public IReadOnlyCollection ActionNames
{
get { return _registry.ActionNames; }
}
///
/// 调度一个 admin 请求(横切:action 解析 → 请求标识 → action 注册表/未安装判定 → 作用域守卫 → 幂等包裹 → 双层信封)。
///
/// action 名(路由末段)。
/// 原始请求体 JSON 字符串。
/// HTTP 响应体原文(外层信封 JSON;HTTP 状态恒 200)。
public async Task DispatchAsync(string action, string bodyJson)
{
string requestId;
AdminApiRequest request = null;
try
{
request = new AdminApiRequest(action, bodyJson);
}
catch (JsonException exception)
{
requestId = "req-" + Guid.NewGuid().ToString("N");
return AdminApiEnvelope.Write(AdminApiResponse.Fail(_errorCodes.MalformedJson.Code, _errorCodes.MalformedJson.MessageKey, "Malformed JSON body: " + exception.Message, requestId, NowSeconds()));
}
requestId = request.ReadRequestId();
if (string.IsNullOrEmpty(requestId))
{
requestId = "req-" + Guid.NewGuid().ToString("N");
}
var registration = _registry.Find(request.Action);
if (registration == null)
{
var disabledOwner = _report == null ? null : _report.FindDisabledOwnerOfAction(request.Action);
if (disabledOwner != null)
{
return AdminApiEnvelope.Write(AdminApiResponse.Fail(_errorCodes.CapabilityNotInstalled.Code, _errorCodes.CapabilityNotInstalled.MessageKey, "Capability not installed: " + disabledOwner.Manifest.Id, requestId, NowSeconds(), BuildNotInstalledPayload(disabledOwner)));
}
return WriteFail(_errorCodes.UnknownAction, "Unknown admin action: " + request.Action, requestId);
}
if (!_scopeAdapter.TryReadClaimedScope(request, out var claimedScope))
{
return WriteFail(_errorCodes.ScopeMissing, "Scope key (ServerId) missing or invalid in request body.", requestId);
}
var deniedCode = _scopeAdapter.ValidateClaimed(claimedScope, _authorizedScope);
if (deniedCode != null)
{
return WriteFail(deniedCode, "Scope denied for server " + claimedScope.ServerId + ".", requestId);
}
if (registration.WrapIdempotency && _idempotencyAdapter != null)
{
return await DispatchWithIdempotencyAsync(registration, request, claimedScope, requestId).ConfigureAwait(false);
}
return await DispatchDirectAsync(registration.Handler, request, claimedScope, requestId).ConfigureAwait(false);
}
///
/// 构造「未安装能力」失败载荷(已装能力清单 + 未安装归属)。
///
/// 声明该 action 的已禁用能力条目。
/// 诊断载荷。
private object BuildNotInstalledPayload(CapabilityReportEntry disabledOwner)
{
return new
{
InstalledCapabilities = _report.EnabledIdsInOrder,
NotInstalledCapability = disabledOwner.Manifest.Id,
};
}
///
/// list_capabilities 元端点处理器(能力报告面:启用清单 / 顺序 / 依赖状态 / 缺失功能 / 禁用项)。
///
/// 请求。
/// 已通过守卫的作用域。
/// 取消令牌。
/// 能力报告载荷。
private Task