XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEExtension.NetCore.ServerInteractive

[DLL] Server interaction extension, including user identity verification and querying in conjunction with AutoConfig

公开
关注 0 Fork 0 Star 0
UTF-8
using XFEExtension.NetCore.AutoConfig;
using XFEExtension.NetCore.CyberComm;

namespace XFEExtension.NetCore.ServerInteractive.TServer.Profiles;

/// <summary>
/// ServerInteractive EXE 的 AutoConfig 运行配置。
/// </summary>
[AutoLoadProfile]
public partial class ServerProfile : XFEProfile
{
    [ProfileProperty]
    private ProfileList<string> _listenUrls = ["http://0.0.0.0:3301/"];

    [ProfileProperty]
    private int _shutdownTimeoutSeconds = 15;

    [ProfileProperty]
    private string? _pfxPath;

    [ProfileProperty]
    private string? _certificatePemPath;

    [ProfileProperty]
    private string? _privateKeyPemPath;

    [ProfileProperty]
    private CyberCommLimitOptions _transportLimits = new();

    /// <summary>
    /// AutoConfig 配置文件的实际路径。
    /// </summary>
    public static string StoragePath => ProfilePath + (string.IsNullOrEmpty(ProfileExtension) ? ".xpf" : ProfileExtension);

    /// <summary>
    /// 校验启动前必须固定的配置。
    /// </summary>
    public static void ValidateConfiguration()
    {
        if (ListenUrls.Count == 0 || ListenUrls.Any(string.IsNullOrWhiteSpace))
            throw new InvalidOperationException("ListenUrls 至少需要一个有效地址");
        if (ShutdownTimeoutSeconds <= 0)
            throw new InvalidOperationException("ShutdownTimeoutSeconds 必须大于 0");
        if (TransportLimits is null)
            throw new InvalidOperationException("TransportLimits 不能为空");
        if (string.IsNullOrWhiteSpace(CertificatePemPath) != string.IsNullOrWhiteSpace(PrivateKeyPemPath))
            throw new InvalidOperationException("CertificatePemPath 与 PrivateKeyPemPath 必须同时配置或同时留空");
    }

    /// <summary>
    /// 创建启动后不可变的 CyberComm 传输限制快照。
    /// </summary>
    public static CyberCommLimitOptions CreateTransportLimits() => TransportLimits with { };

    /// <summary>
    /// 根据 AutoConfig 中的证书路径和外部注入的密码创建 TLS 配置。
    /// </summary>
    public static CyberCommTlsOptions? CreateTlsOptions(string rootPath, string? tlsPassword)
    {
        if (string.IsNullOrWhiteSpace(PfxPath) && string.IsNullOrWhiteSpace(CertificatePemPath))
            return null;

        return new CyberCommTlsOptions
        {
            PfxPath = ResolvePath(rootPath, PfxPath),
            PfxPassword = tlsPassword,
            CertificatePemPath = ResolvePath(rootPath, CertificatePemPath),
            PrivateKeyPemPath = ResolvePath(rootPath, PrivateKeyPemPath)
        };
    }

    private static string? ResolvePath(string rootPath, string? path)
        => string.IsNullOrWhiteSpace(path)
            ? null
            : Path.GetFullPath(Path.IsPathRooted(path) ? path : Path.Combine(rootPath, path));
}