节点在线、应用在线、配置在线使用令牌查询
大石头 authored at 2021-12-16 19:49:30
71.58 KiB
Stardust
using NewLife;
using NewLife.Caching;
using NewLife.Log;
using NewLife.Remoting;
using NewLife.Remoting.Extensions.Services;
using NewLife.Remoting.Models;
using NewLife.Remoting.Services;
using NewLife.Security;
using NewLife.Serialization;
using Stardust.Data;
using Stardust.Data.Deployment;
using Stardust.Data.Nodes;
using Stardust.Data.Platform;
using Stardust.Models;
using XCode;
using XCode.Configuration;

namespace Stardust.Server.Services;

/// <summary>节点服务。处理 StarAgent 节点的注册登录、心跳保活、在线状态管理和命令下发</summary>
public class NodeService : DefaultDeviceService<Node, NodeOnline>
{
    private readonly ITokenService _tokenService;
    private readonly IPasswordProvider _passwordProvider;
    private readonly StarServerSetting _setting;
    private readonly NodeSessionManager _sessionManager;
    private readonly ICacheProvider _cacheProvider;
    private readonly ITracer _tracer;
    private readonly DnsService _dnsService;
    private readonly InstallService _installService;

    /// <summary>实例化节点服务</summary>
    /// <param name="tokenService">令牌服务</param>
    /// <param name="passwordProvider">密码提供者</param>
    /// <param name="setting">服务端设置</param>
    /// <param name="sessionManager">节点会话管理器</param>
    /// <param name="cacheProvider">缓存提供者</param>
    /// <param name="tracer">跟踪器</param>
    /// <param name="dnsService">DDNS 服务</param>
    /// <param name="installService">安装引导服务</param>
    /// <param name="serviceProvider">服务提供者</param>
    public NodeService(ITokenService tokenService, IPasswordProvider passwordProvider, StarServerSetting setting, NodeSessionManager sessionManager, ICacheProvider cacheProvider, ITracer tracer, DnsService dnsService, InstallService installService, IServiceProvider serviceProvider) : base(sessionManager, passwordProvider, cacheProvider, serviceProvider)
    {
        _tokenService = tokenService;
        _passwordProvider = passwordProvider;
        _setting = setting;
        _sessionManager = sessionManager;
        _cacheProvider = cacheProvider;
        _tracer = tracer;
        _dnsService = dnsService;
        _installService = installService;

        Name = "Node";

        // 密钥校验失败时仍交由本类 Register 按自动注册策略(AutoRegister/NodeCodeLevel)决定是否放行,
        // 硬件变更校验由 CheckNode 负责,避免框架默认直接拒绝、绕过平台自身的接入策略
        AllowSecretResetOnAuthFailure = true;
        AllowIdentityMismatch = true;
    }

    #region 登录注销
    /// <summary>节点登录。平台设置的默认语言优先于核心配置</summary>
    /// <param name="context">设备上下文</param>
    /// <param name="request">登录请求</param>
    /// <param name="source">来源</param>
    /// <returns>登录响应</returns>
    public override ILoginResponse Login(DeviceContext context, ILoginRequest request, String source)
    {
        var rs = base.Login(context, request, source);
        if (rs is LoginResponse response) response.DefaultLanguage = _setting.GetDefaultLanguage(response.DefaultLanguage);

        return rs;
    }

    /// <summary>验证设备合法性</summary>
    public override Boolean Authorize(DeviceContext context, ILoginRequest request)
    {
        if (context.Device is not Node node) return false;

        using var span = _tracer?.NewSpan($"{Name}Authorize", new { request.Code, request.ClientId });

        var inf = request as LoginInfo;
        var ip = context.UserHost;
        node = CheckNode(node, inf.Node, inf.ProductCode, ip, _setting.NodeCodeLevel);
        if (node == null)
        {
            WriteHistory(node, HistoryAction.NodeAuthentication, false, L.TLog("Hardware information changed too much."), ip);
            return false;
        }

        // 没有密码时无需验证
        if (node.Secret.IsNullOrEmpty()) return true;
        if (node.Secret.EqualIgnoreCase(request.Secret)) return true;

        if (_setting.SaltTime > 0 && _passwordProvider is SaltPasswordProvider saltProvider)
        {
            // 使用盐值偏差时间,允许客户端时间与服务端时间有一定偏差
            saltProvider.SaltTime = _setting.SaltTime;
        }
        if (request.Secret.IsNullOrEmpty() || !_passwordProvider.Verify(node.Secret, request.Secret))
        {
            WriteHistory(context, HistoryAction.NodeAuthentication, false, L.TLog("Secret validation failed."));
            return false;
        }

        return true;
    }

    /// <summary>自动注册</summary>
    /// <param name="context"></param>
    /// <param name="request"></param>
    /// <returns></returns>
    /// <exception cref="ApiException"></exception>
    public override IDeviceModel Register(DeviceContext context, ILoginRequest request)
    {
        using var span = _tracer?.NewSpan($"{Name}Register", new { request.Code, request.ClientId });

        var inf = request as LoginInfo;
        var node = context.Device as Node ?? QueryDevice(request.Code) as Node;
        var ip = context.UserHost;

        try
        {
            // 校验唯一编码,防止客户端拷贝配置
            if (node == null)
            {
                node = AutoRegister(null, inf, ip, _setting);
            }
            else
            {
                //// 登录密码未设置或者未提交,则执行动态注册
                //if (node == null || node.Secret.IsNullOrEmpty() || secret.IsNullOrEmpty())
                //    node = AutoRegister(node, inf, ip, setting);
                //else if (node.Secret.MD5() != secret)
                //    node = AutoRegister(node, inf, ip, setting);
                //else if (setting.NodeCodeLevel > 0)
                //    node = AutoRegister(node, inf, ip, setting);
                node = AutoRegister(node, inf, ip, _setting);
            }

            node?.WriteHistory(HistoryAction.DynamicRegistration, true, inf.ToJson(false, false, false), ip);
        }
        catch (Exception ex)
        {
            span?.SetError(ex, null);

            node?.WriteHistory(HistoryAction.DynamicRegistration, false, inf.ToJson(false, false, false), ip);

            throw;
        }

        return node;
    }

    /// <summary>鉴权后的登录处理。修改设备信息、创建在线记录和写日志</summary>
    /// <remarks>
    /// LoginTime 和 Fill 数据在本方法中设置后,由基类 <c>DefaultDeviceService.Login</c>
    /// 统一调用 <c>(context.Online as IEntity)?.Update()</c> 持久化,此处无需单独保存。
    /// </remarks>
    /// <param name="context">上下文</param>
    /// <param name="request">登录请求</param>
    public override void OnLogin(DeviceContext context, ILoginRequest request)
    {
        using var span = _tracer?.NewSpan($"{Name}OnLogin", new { request.Code, request.ClientId });

        var node = context.Device as Node;
        var inf = request as LoginInfo;
        var ip = context.UserHost;
        if (!inf.ProductCode.IsNullOrEmpty()) node.ProductCode = inf.ProductCode;

        // 设置默认项目
        if (node.ProjectId == 0 || node.ProjectName == "默认")
        {
            var project = GalaxyProject.FindByName(inf.Project);
            if (project != null)
                node.ProjectId = project.Id;
        }

        node.UpdateIP = ip;
        node.FixNameByRule();

        // 记录旧IP,用于DDNS检测(Login会更新LastLoginIP)
        var oldIp = node.LastLoginIP;

        node.Login(inf.Node, ip);

        var online = context.Online = GetOnline(context) ?? CreateOnline(context);
        if (online is NodeOnline olt)
        {
            olt.LoginTime = DateTime.Now;
            if (inf.Node != null) olt.Fill(inf.Node);
        }

        // 登录历史
        WriteHistory(context, HistoryAction.NodeAuthentication, true, L.TLog("[{0}/{1}] authenticated {2}", node.Name, node.Code, inf.ToJson(false, false, false)));

        // 旧版客户端在网络未就绪时上报 @pid 形式的客户端标识,无法按主机归组,且进程重启就换一个
        if (!context.ClientId.IsNullOrEmpty() && context.ClientId[0] == '@')
            XTrace.WriteLine("Node [{0}] logged in with a host-less client id [{1}], which cannot be grouped by host; upgrade the agent to report a stable instance identity", node.Code, context.ClientId);

        // 检查节点上线恢复
        NodeOnlineService.CheckOnline(node);

        // DDNS检测。节点上线时检测IP变化并更新DNS记录
        _ = _dnsService.CheckNodeIPChange(node, ip, oldIp);
    }

    /// <summary>注销</summary>
    /// <param name="reason">注销原因</param>
    /// <param name="ip">IP地址</param>
    /// <returns></returns>
    public override IOnlineModel? Logout(DeviceContext context, String? reason, String source)
    {
        using var span = _tracer?.NewSpan($"{Name}Logout", new { context.Code, context.ClientId, reason, source });

        //var node = context.Device as Node;
        //var ip = context.UserHost;
        //var online = GetOnline(node, ip);
        //if (online == null) return null;

        //var msg = $"{reason} [{node}]]登录于{online.CreateTime},最后活跃于{online.UpdateTime}";
        //node.WriteHistory("节点下线", true, msg, ip);
        //online.Delete();

        //RemoveOnline(node);

        //// 计算在线时长
        //if (online.CreateTime.Year > 2000)
        //{
        //    node.OnlineTime += (Int32)(DateTime.Now - online.CreateTime).TotalSeconds;
        //    node.Update();
        //}

        //NodeOnlineService.CheckOffline(node, "注销");

        var online = base.Logout(context, reason, source);
        if (online is NodeOnline online2 && context.Device is Node node)
        {
            // 注销时基类已通过 SettleOnline 结算在线时长并清空 LoginTime
            NodeOnlineService.CheckOffline(node, "注销");
        }

        return online;
    }

    /// <summary>校验节点信息,如果大量不一致则认为是新节点</summary>
    /// <param name="node"></param>
    /// <param name="di"></param>
    /// <param name="productCode"></param>
    /// <param name="ip"></param>
    /// <param name="minLevel"></param>
    /// <returns></returns>
    private static Node CheckNode(Node node, NodeInfo di, String productCode, String ip, Int32 minLevel)
    {
        // 校验唯一编码,防止客户端拷贝配置
        var uuid = di.UUID;
        var guid = di.MachineGuid;
        var serial = di.SerialNumber;
        var board = di.Board;
        var diskid = di.DiskID;

        // 自动截断,避免超长导致对比时不一致
        uuid = TrimLength(uuid, Node.GetFieldLength("Uuid"));
        guid = TrimLength(guid, Node.GetFieldLength("MachineGuid"));
        serial = TrimLength(serial, Node.GetFieldLength("SerialNumber"));
        board = TrimLength(board, Node.GetFieldLength("Board"));
        diskid = TrimLength(diskid, Node.GetFieldLength("DiskID"));

        var level = 5;
        if (!uuid.IsNullOrEmpty() && uuid != node.Uuid)
        {
            node.WriteHistory(HistoryAction.IdentityMismatch, false, L.TLog("Unique identifier mismatch (new != old): {0} != {1}", uuid, node.Uuid), ip);
            level--;
        }
        if (!guid.IsNullOrEmpty() && guid != node.MachineGuid)
        {
            node.WriteHistory(HistoryAction.IdentityMismatch, false, L.TLog("Machine identifier mismatch (new != old): {0} != {1}", guid, node.MachineGuid), ip);
            level--;
        }
        if (!serial.IsNullOrEmpty() && serial != node.SerialNumber)
        {
            node.WriteHistory(HistoryAction.IdentityMismatch, false, L.TLog("Computer serial number mismatch (new != old): {0} != {1}", serial, node.SerialNumber), ip);
            level--;
        }
        if (!board.IsNullOrEmpty() && board != node.Board)
        {
            node.WriteHistory(HistoryAction.IdentityMismatch, false, L.TLog("Motherboard mismatch (new != old): {0} != {1}", board, node.Board), ip);
            //flag = false;
        }
        //if (!diskid.IsNullOrEmpty() && diskid != node.DiskID)
        //{
        //    node.WriteHistory("登录校验", false, $"磁盘序列号不符!(新!=旧){diskid}!={node.DiskID}", ip);
        //    level--;
        //}
        if (!node.ProductCode.IsNullOrEmpty() && !productCode.IsNullOrEmpty() && !node.ProductCode.EqualIgnoreCase(productCode))
        {
            node.WriteHistory(HistoryAction.IdentityMismatch, false, L.TLog("Product code mismatch (new != old): {0} != {1}", productCode, node.ProductCode), ip);
            //level--;
        }

        // 机器名
        if (di.MachineName != node.MachineName)
        {
            node.WriteHistory(HistoryAction.IdentityMismatch, false, L.TLog("Machine name mismatch (new != old): {0} != {1}", di.MachineName, node.MachineName), ip);
        }

        // 网卡地址
        if (di.Macs != node.MACs)
        {
            var dims = di.Macs?.Split(",") ?? [];
            var nodems = node.MACs?.Split(",") ?? [];
            // 任意匹配则通过
            if (!nodems.Any(e => dims.Contains(e)))
            {
                node.WriteHistory(HistoryAction.IdentityMismatch, false, L.TLog("MAC address mismatch (new != old): {0} != {1}", di.Macs, node.MACs), ip);
                level--;
            }
        }

        // 磁盘。可能有TF卡和U盘
        if (diskid != node.DiskID)
        {
            var dims = diskid?.Split(",") ?? [];
            var nodems = node.DiskID?.Split(",") ?? [];
            // 任意匹配则通过
            if (!nodems.Any(e => dims.Contains(e)))
            {
                node.WriteHistory(HistoryAction.IdentityMismatch, false, L.TLog("Disk serial number mismatch (new != old): {0} != {1}", diskid, node.DiskID), ip);
                level--;
            }
        }

        if (level < minLevel) return null;

        return node;
    }

    private static String TrimLength(String value, Int32 length)
    {
        if (value.IsNullOrEmpty()) return value;
        if (length <= 0 || value.Length < length) return value;

        return value[..length];
    }

    private Node AutoRegister(Node node, LoginInfo inf, String ip, StarServerSetting set)
    {
        if (!set.AutoRegister) throw new ApiException(ApiCode.Forbidden, L.T("Automatic registration is forbidden."));

        // 检查白名单
        //var ip = UserHost;
        if (!IsMatchWhiteIP(set.WhiteIP, ip)) throw new ApiException(ApiCode.Forbidden, L.T("Illegal source; registration is forbidden."));

        var di = inf.Node;
        using var span = _tracer?.NewSpan(nameof(AutoRegister), new { inf.ProductCode, di.UUID, di.MachineGuid, di.Macs, di.DiskID });

        var code = BuildCode(di, inf.ProductCode, set);
        if (code.IsNullOrEmpty()) code = Rand.NextString(8);
        span?.AppendTag($"code={code}");

        // 如果节点编码有改变,则倾向于新建节点
        if (node == null || node.Code != code) node = Node.FindByCode(code);

        if (node == null)
        {
            node = QueryByInfo(inf.ProductCode, di, set.NodeCodeLevel).FirstOrDefault();
            if (node != null)
            {
                var msg = L.TLog("Node [{0}/{1}] is highly similar to the existing node [{2}]; using the existing node", inf.Code, di.Macs, node.Code);
                XTrace.WriteLine(msg);
                span?.AppendTag(msg);
                node.WriteHistory(HistoryAction.MatchedExistingNode, true, msg, ip);
            }
        }

        var name = "";
        if (name.IsNullOrEmpty()) name = di.MachineName;
        if (name.IsNullOrEmpty()) name = di.UserName;

        node ??= new Node
        {
            Enable = true,

            CreateIP = ip,
            CreateTime = DateTime.Now,
        };

        // 如果未打开动态注册,则把节点修改为禁用
        node.Enable = set.AutoRegister;

        // 移动端受系统限制无法常驻,新节点默认关闭下线告警,避免间歇在线产生告警噪音
        if (node.ID == 0)
        {
            var osKind = OSKindHelper.Parse(di.OSName, di.OSVersion);
            if (osKind is OSKinds.Android or OSKinds.iOS) node.AlarmOnOffline = false;
        }

        if (node.Name.IsNullOrEmpty()) node.Name = name;

        // 优先使用节点散列来生成节点证书,确保节点路由到其它接入网关时保持相同证书代码
        node.Code = code;

        node.Secret = Rand.NextString(16);
        node.UpdateIP = ip;
        node.UpdateTime = DateTime.Now;

        node.Save();
        //autoReg = true;

        // 第一个注册的StarAgent提高采样频率,便于测试和演示
        if (node.ID == 1)
        {
            node.Period = 5;
            node.Update();
        }

        return node;
    }

    public static IList<Node> QueryByInfo(String productCode, NodeInfo di, Int32 level)
    {
        // 该硬件的所有节点信息
        var list = Node.SearchAny(di.UUID, di.MachineGuid, di.Macs, di.SerialNumber, di.DiskID);

        // 当前节点信息,取较老者
        list = list.Where(e => e.ProductCode.IsNullOrEmpty() || e.ProductCode == productCode).OrderBy(e => e.ID).ToList();

        // 找到节点
        //node ??= list.FirstOrDefault();
        // 节点编码辨识度。UUID+Guid+SerialNumber+DiskId+MAC,只要其中几个相同,就认为是同一个节点,默认2
        //var level = set.NodeCodeLevel;
        if (level <= 0) level = 2;

        // 按匹配度排序,匹配度越高,越靠前。注意不同节点的匹配度可能相同。
        var rs = new MySortedList<Int32, Node>();
        foreach (var node in list)
        {
            var n = 0;
            if (!di.UUID.IsNullOrEmpty() && node.Uuid == di.UUID) n++;
            if (!di.MachineGuid.IsNullOrEmpty() && node.MachineGuid == di.MachineGuid) n++;
            //if (!di.Macs.IsNullOrEmpty() && node.MACs == di.Macs) n++;
            if (!di.SerialNumber.IsNullOrEmpty() && node.SerialNumber == di.SerialNumber) n++;
            //if (!di.DiskID.IsNullOrEmpty() && node.DiskID == di.DiskID) n++;

            // 网卡地址
            if (di.Macs == node.MACs)
                n++;
            else
            {
                var dims = di.Macs?.Split(",") ?? [];
                var nodems = node.MACs?.Split(",") ?? [];
                if (dims != null && nodems != null) n += dims.Count(e => nodems.Contains(e));
            }

            // 磁盘。可能有TF卡和U盘
            var diskid = di.DiskID;
            if (diskid == node.DiskID)
                n++;
            else
            {
                var dims = diskid?.Split(",") ?? [];
                var nodems = node.DiskID?.Split(",") ?? [];
                //if (dims != null && nodems != null) n += dims.Count(e => nodems.Contains(e));
                // 在虚拟机云服务器中,磁盘序列化可能大范围一致,因此只计算一个匹配
                if (dims != null && nodems != null && dims.Any(e => nodems.Contains(e))) n++;
            }

            if (n >= level) rs.Add(10 - n, node);
        }

        return rs.Values;
    }

    /// <summary>
    /// 是否匹配白名单,未设置则直接通过
    /// </summary>
    /// <param name="whiteIp"></param>
    /// <param name="ip"></param>
    /// <returns></returns>
    private static Boolean IsMatchWhiteIP(String whiteIp, String ip)
    {
        if (ip.IsNullOrEmpty()) return true;
        if (whiteIp.IsNullOrEmpty()) return true;

        var ss = whiteIp.Split(",");
        foreach (var item in ss)
        {
            if (item.IsMatch(ip)) return true;
        }

        return false;
    }

    private String BuildCode(NodeInfo di, String productCode, StarServerSetting set)
    {
        using var span = _tracer?.NewSpan(nameof(BuildCode), new { set.NodeCodeFormula });

        //var set = Setting.Current;
        //var uid = $"{di.UUID}@{di.MachineGuid}@{di.Macs}";
        var ss = (set.NodeCodeFormula + "").Split('(', ')');
        if (ss.Length >= 2)
        {
            var uid = ss[1];
            uid = uid.Replace("{ProductCode}", productCode);
            foreach (var pi in di.GetType().GetProperties())
            {
                uid = uid.Replace($"{{{pi.Name}}}", pi.GetValue(di) + "");
            }
            span?.AppendTag($"uid={uid}");

            var p1 = uid.IndexOf('{');
            if (p1 > 0)
            {
                var p2 = uid.IndexOf('}', p1 + 1);
                if (p2 > 0)
                {
                    // 有些标识符刚好带有大括号,导致误判以为是未解析变量
                    var len = p2 - p1 - 1;
                    if (len >= 2 && len < 10)
                        XTrace.WriteLine("The node code formula contains unresolved variables, uid={0}", uid);
                }
            }
            //if (uid.Contains('{') || uid.Contains('}')) XTrace.WriteLine("The node code formula contains unresolved variables, uid={0}", uid);
            if (!uid.IsNullOrEmpty())
            {
                XTrace.WriteLine("Generated node code uid={0} alg={1}", uid, ss[0]);

                // 使用产品类别加密一下,确保不同类别有不同编码
                var buf = uid.GetBytes();
                //code = buf.Crc().GetBytes().ToHex();
                switch (ss[0].ToLower())
                {
                    case "crc": buf = buf.Crc().GetBytes(); break;
                    case "crc16": buf = buf.Crc16().GetBytes(); break;
                    case "md5": buf = buf.MD5(); break;
                    case "md5_16": buf = uid.MD5_16().ToHex(); break;
                    default:
                        break;
                }
                var code = buf.ToHex();
                span?.AppendTag($"code={code}");

                return code;
            }
        }

        return null;
    }
    #endregion

    #region 心跳保活
    /// <summary>节点心跳。平台设置的默认语言优先于核心配置</summary>
    /// <param name="context">设备上下文</param>
    /// <param name="request">心跳请求</param>
    /// <param name="response">心跳响应</param>
    /// <returns>心跳响应</returns>
    public override IPingResponse Ping(DeviceContext context, IPingRequest? request, IPingResponse? response)
    {
        var rs = base.Ping(context, request, response);
        if (rs is PingResponse ping) ping.DefaultLanguage = _setting.GetDefaultLanguage(ping.DefaultLanguage);

        return rs;
    }

    public override IOnlineModel OnPing(DeviceContext context, IPingRequest? request)
    {
        if (context.Device is not Node node) return null;

        using var span = _tracer?.NewSpan($"{Name}OnPing", new { context.Code, context.ClientId });

        var inf = request as PingInfo;
        if (!inf.IP.IsNullOrEmpty()) node.IP = inf.IP;
        if (!inf.Gateway.IsNullOrEmpty()) node.Gateway = inf.Gateway;

        node.UpdateIP = context.UserHost;
        node.FixArea();
        node.FixNameByRule();

        // 在心跳中更新客户端所有的框架。因此客户端长期不重启,而中途可能安装了新版NET运行时
        if (!inf.Framework.IsNullOrEmpty())
        {
            //node.Framework = inf.Framework?.Split(',').LastOrDefault();
            node.Frameworks = inf.Framework;
            // 选取最大的版本,而不是最后一个,例如6.0.3字符串大于6.0.13
            Version max = null;
            var fs = inf.Framework.Split(',');
            if (fs != null)
            {
                foreach (var f in fs)
                {
                    if (Version.TryParse(f, out var v) && (max == null || max < v))
                        max = v;
                }
                node.Framework = max?.ToString();
            }
        }

        // 每10分钟更新一次节点信息,确保活跃
        if (node.LastActive.AddMinutes(10) < DateTime.Now) node.LastActive = DateTime.Now;
        //node.SaveAsync();
        node.Update();

        var online = base.OnPing(context, request) as NodeOnline;

        // DDNS检测。心跳时检测IP变化并更新DNS记录
        _ = _dnsService.CheckNodeIPChange(node, context.UserHost);

        return online;
    }

    private static Int32 _totalCommands;
    private static IList<NodeCommand> _commands = [];
    private static DateTime _nextTime;

    public override CommandModel[]? AcquireCommands(DeviceContext context)
    {
        // 缓存最近1000个未执行命令,用于快速过滤,避免大量节点在线时频繁查询命令表
        if (_nextTime < DateTime.Now || _totalCommands != NodeCommand.Meta.Count)
        {
            _totalCommands = NodeCommand.Meta.Count;
            _commands = NodeCommand.AcquireCommands(-1, 1000);
            _nextTime = DateTime.Now.AddMinutes(1);
        }

        if (context.Device is not Node node) return null;
        var nodeId = node.ID;

        // 是否有本节点
        if (!_commands.Any(e => e.NodeID == nodeId)) return null;

        using var span = _tracer?.NewSpan(nameof(AcquireCommands), new { nodeId });

        var cmds = NodeCommand.AcquireCommands(nodeId, 100);
        if (cmds.Count == 0) return null;

        var rs = new List<CommandModel>();
        foreach (var item in cmds)
        {
            // 命令要提前下发,在客户端本地做延迟处理,这里不应该过滤掉
            //// 命令是否已经开始
            //if (item.StartTime > DateTime.Now) continue;

            // 带有过期时间的命令,加大重试次数
            var maxTimes = item.Expire.Year > 2000 ? 100 : 10;
            if (item.Times > maxTimes || item.Expire.Year > 2000 && item.Expire < DateTime.Now)
                item.Status = CommandStatus.取消;
            else
            {
                // 如果命令正在处理中,则短期内不重复下发。客户端StarAgent具备去重能力,不需要服务端过滤
                //if (item.Status == CommandStatus.处理中 && item.UpdateTime.AddSeconds(30) > DateTime.Now) continue;

                // 即时指令,或者已到开始时间的未来指令,才增加次数
                if (item.StartTime.Year < 2000 || item.StartTime < DateTime.Now)
                    item.Times++;
                item.Status = CommandStatus.处理中;

                var commandModel = BuildCommand(item.Node, item);

                rs.Add(commandModel);
            }
            item.UpdateTime = DateTime.Now;
        }
        cmds.Update(false);

        span?.Value = rs.Count;

        return rs.ToArray();
    }

    /// <summary>结算在线时长。将本次会话时长累加到节点的 OnlineTime</summary>
    /// <param name="online">在线实体</param>
    /// <param name="device">设备信息</param>
    protected override void OnSettleOnline(IOnlineModel online, IDeviceModel device)
    {
        if (online is not NodeOnline online2 || device is not Node node) return;

        var end = online2.UpdateTime > online2.LoginTime ? online2.UpdateTime : DateTime.Now;
        var delta = (Int32)(end - online2.LoginTime).TotalSeconds;
        if (delta > 0)
        {
            node.OnlineTime += delta;
            node.Update();
        }
    }

    /// <summary>设置设备的长连接上线/下线</summary>
    /// <param name="context">上下文</param>
    /// <param name="online"></param>
    /// <returns></returns>
    public override void SetOnline(DeviceContext context, Boolean online)
    {
        var node = context.Device as Node;

        // 优先使用 context.Online(登录时设置的新对象),避免 GetOnline 返回缓存旧对象
        if ((context.Online ?? GetOnline(context)) is NodeOnline olt)
        {
            // 下线时检查是否有活跃会话,避免旧会话断开时覆盖新会话的状态
            if (!online && node != null)
            {
                var session = _sessionManager.Get(node.Code);
                if (session != null && session.Active)
                    return;
            }

            olt.LongLink = online;
            olt.Update();
        }
    }

    /// <summary>创建在线</summary>
    /// <param name="context">上下文</param>
    /// <returns></returns>
    public override IOnlineModel? CreateOnline(DeviceContext context)
    {
        if (context.Device is not Node node) return null;

        var online = base.CreateOnline(context) as NodeOnline;
        online.Token = context.Token;

        return online;
    }

    /// <summary>弱网重连宽限期(秒)。默认900秒。会话标识随进程重启或网络切换变化</summary>
    public Int32 OnlineReuseSeconds { get; set; } = 900;

    /// <summary>获取在线。会话标识未命中时,宽限期内沿用同一节点的上一条在线记录</summary>
    /// <remarks>
    /// 弱网节点或代理重启会带来新的会话标识。若每次重连都新建在线记录,在线时长与心跳计数会被切成多段,
    /// 历史查询噪声大。宽限期内沿用同一记录,只刷新会话标识,登录时间由登录流程重设。
    /// </remarks>
    /// <param name="context">上下文</param>
    /// <returns>在线对象,需要新建时返回空</returns>
    public override IOnlineModel? GetOnline(DeviceContext context)
    {
        var online = base.GetOnline(context);
        if (online != null) return online;

        if (context.Device is not Node node || node.ID <= 0) return null;

        var last = NodeOnline.FindAllByNodeId(node.ID).OrderByDescending(e => e.UpdateTime).FirstOrDefault();
        if (last == null) return null;

        // 超过宽限期视为真正离线,等超时清理后重新建记录
        if ((DateTime.Now - last.UpdateTime).TotalSeconds > OnlineReuseSeconds) return null;

        var sid = GetSessionId(context);
        if (!sid.IsNullOrEmpty()) last.SessionID = sid;

        return last;
    }
    #endregion

    #region 升级更新
    /// <summary>升级检查。新版优先匹配 ProductRelease + ProductPackage,回退到旧 NodeVersion 逻辑</summary>
    /// <param name="context">上下文</param>
    /// <param name="channel">更新通道</param>
    /// <returns></returns>
    public override IUpgradeInfo? Upgrade(DeviceContext context, String? channel) => Upgrade(context, channel, null);

    /// <summary>升级检查。指定版本时用于控制台手工升级到指定版本</summary>
    /// <param name="context">上下文</param>
    /// <param name="channel">更新通道</param>
    /// <param name="version">指定版本。为空时按策略匹配;指定版本时忽略去重与通道限制,但仍校验产品编码与安装包匹配</param>
    /// <returns></returns>
    public IUpgradeInfo? Upgrade(DeviceContext context, String? channel, String? version)
    {
        // 默认Release通道
        if (!Enum.TryParse<NodeChannels>(channel, true, out var ch)) ch = NodeChannels.Release;
        if (ch < NodeChannels.Release) ch = NodeChannels.Release;

        var node = context.Device as Node;
        var ip = context.UserHost;

        // ---- 手工指定版本:用于控制台升级到指定版本 ----
        if (!version.IsNullOrEmpty()) return TryUpgradeFromVersion(node, version, ch, ip);

        // ---- 新路径:ProductRelease + ProductPackage 匹配 ----
        var upgradeInfo = TryUpgradeFromRelease(node, ch);
        if (upgradeInfo != null) return upgradeInfo;

        // ---- 回退路径:旧 NodeVersion 逻辑(兼容已有记录) ----
        var list = NodeVersion.GetValids(ch);
        list = list.Where(e => e.ProductCode.IsNullOrEmpty() || e.ProductCode.EqualIgnoreCase(node.ProductCode)).ToList();
        if (list.Count == 0) return null;

        using var span = _tracer?.NewSpan(nameof(Upgrade), new { node.Name, node.Code, node.Runtime, node.Framework, node.Frameworks, ip, vers = list.Count });

        // 应用过滤规则,使用最新的一个版本。命中后即使被去重拦截也不再回退到旧版本,避免降级与来回横跳
        var pv = list.Where(e => e.Match(node)).OrderByDescending(e => e.ID).FirstOrDefault();
        if (pv == null) return null;

        var key = BuildUpgradeKey(pv);
        if (!AllowUpgrade(node, pv.Version, key, pv.Force)) return null;

        RecordUpgrade(node, ch, pv.Version, key, $"[{pv.ID}] {pv.Version} {pv.Executor}", ip);

        return new UpgradeInfo
        {
            Version = pv.Version,
            Source = pv.Source,
            FileHash = pv.FileHash,
            FileSize = pv.Size,
            Preinstall = pv.Preinstall,
            Executor = pv.Executor,
            Force = pv.Force,
            Description = pv.Description,
        };
    }

    /// <summary>按指定版本升级。用于控制台手工升级到指定版本,忽略自动去重与通道限制</summary>
    /// <param name="node">节点</param>
    /// <param name="version">目标版本号</param>
    /// <param name="channel">通道</param>
    /// <param name="ip">操作IP</param>
    /// <returns></returns>
    private UpgradeInfo TryUpgradeFromVersion(Node node, String version, NodeChannels channel, String ip)
    {
        // 允许指定已停用的发布版本,便于回退或重装同版本
        var releases = ProductRelease.FindAll().Where(e => e.Version.EqualIgnoreCase(version)).ToList();
        if (releases.Count == 0) return null;

        // 通用版本或与节点产品编码一致,避免把 .NET 包发给原生 Agent
        var release = releases.FirstOrDefault(e => e.ProductCode.IsNullOrEmpty() || e.ProductCode.EqualIgnoreCase(node.ProductCode));
        if (release == null) return null;

        var pkg = release.MatchPackage(node);
        if (pkg == null) return null;

        var key = BuildUpgradeKey(release, pkg);
        RecordUpgrade(node, channel, release.Version, key, $"手动升级 Release[{release.Id}] {release.Version} Package[{pkg.TargetRuntime}] {pkg.FileName}", ip);

        // 双层取值:Package优先级高于Release,客户端自行处理空Executor
        var executor = !pkg.Executor.IsNullOrEmpty() ? pkg.Executor : release.Executor;
        var preinstall = !pkg.Preinstall.IsNullOrEmpty() ? pkg.Preinstall : release.Preinstall;

        return new UpgradeInfo
        {
            Version = release.Version,
            Source = pkg.Source,
            FileHash = pkg.FileHash,
            FileSize = pkg.Size,
            Preinstall = preinstall,
            Executor = executor,
            Force = release.Force,
            Description = release.Remark,
        };
    }

    /// <summary>尝试从新的 ProductRelease 表中匹配升级</summary>
    private UpgradeInfo TryUpgradeFromRelease(Node node, NodeChannels channel)
    {
        var releases = ProductRelease.GetValids(channel);
        if (releases.Count == 0) return null;

        // 只使用通用版本或与节点产品编码一致的版本,避免把 .NET 包发给原生 Agent
        if (!node.ProductCode.IsNullOrEmpty())
            releases = releases.Where(e => e.ProductCode.IsNullOrEmpty() || e.ProductCode.EqualIgnoreCase(node.ProductCode)).ToList();
        else
            releases = releases.Where(e => e.ProductCode.IsNullOrEmpty()).ToList();
        if (releases.Count == 0) return null;

        var ip = node.UpdateIP;

        foreach (var release in releases)
        {
            var pkg = release.MatchPackage(node);
            if (pkg == null) continue;

            // 命中最新的可升级版本后,即使被去重拦截也不再回退到旧版本,避免降级与来回横跳
            var key = BuildUpgradeKey(release, pkg);
            if (!AllowUpgrade(node, release.Version, key, release.Force)) return null;

            RecordUpgrade(node, channel, release.Version, key, $"Release[{release.Id}] {release.Version} Package[{pkg.TargetRuntime}] {pkg.FileName}", ip);

            // 双层取值:Package优先级高于Release,客户端自行处理空Executor
            var executor = !pkg.Executor.IsNullOrEmpty() ? pkg.Executor : release.Executor;
            var preinstall = !pkg.Preinstall.IsNullOrEmpty() ? pkg.Preinstall : release.Preinstall;

            return new UpgradeInfo
            {
                Version = release.Version,
                Source = pkg.Source,
                FileHash = pkg.FileHash,
                FileSize = pkg.Size,
                Preinstall = preinstall,
                Executor = executor,
                Force = release.Force,
                Description = release.Remark,
            };
        }

        return null;
    }

    /// <summary>构造升级指纹。版本、发布记录与安装包哈希共同决定是否需要重新下发,允许同版本号重新打包后再次升级</summary>
    /// <param name="release">产品发布版本</param>
    /// <param name="package">产品安装包</param>
    /// <returns></returns>
    private static String BuildUpgradeKey(ProductRelease release, ProductPackage package) => $"{release.Version}:{release.Id}:{package?.FileHash}";

    /// <summary>构造升级指纹。用于旧版 NodeVersion 升级策略</summary>
    /// <param name="version">节点版本策略</param>
    /// <returns></returns>
    private static String BuildUpgradeKey(NodeVersion version) => $"{version.Version}:{version.ID}:{version.FileHash}";

    /// <summary>判断是否需要向节点下发升级指令</summary>
    /// <remarks>
    /// 一、目标版本与最后版本不同,视为新的升级目标,立即下发;管理员清空最后版本后也会重新下发
    /// 二、同一版本号重新打包或客户端已上报失败时指纹不一致,允许重新下发
    /// 三、同一份安装包:非强制升级下发一次即视为完成;强制升级按退避间隔等待节点确认,次数用完则停止
    /// </remarks>
    /// <param name="node">节点</param>
    /// <param name="version">目标版本</param>
    /// <param name="key">升级指纹</param>
    /// <param name="force">是否强制升级,即升级后重启</param>
    /// <returns></returns>
    private static Boolean AllowUpgrade(Node node, String version, String key, Boolean force)
    {
        if (node.LastVersion != version) return true;
        if (node.LastUpgradeKey != key) return true;

        if (node.UpgradeAttempts >= Node.MaxUpgradeAttempts) return false;

        if (!force) return false;

        var last = node.LastUpgradeTime;
        return last.Year <= 2000 || last.Add(GetUpgradeBackoff(node.UpgradeAttempts)) <= DateTime.Now;
    }

    /// <summary>同一份安装包两次下发之间的最小间隔。失败后逐级退避,避免反复下载大安装包</summary>
    /// <param name="attempts">已下发次数</param>
    /// <returns></returns>
    private static TimeSpan GetUpgradeBackoff(Int32 attempts) => attempts switch
    {
        <= 1 => TimeSpan.FromMinutes(10),
        2 => TimeSpan.FromMinutes(30),
        3 => TimeSpan.FromHours(2),
        4 => TimeSpan.FromHours(6),
        _ => TimeSpan.FromHours(24),
    };

    /// <summary>记录一次升级下发。目标版本不变则累加次数,切换目标版本后重新计数</summary>
    /// <param name="node">节点</param>
    /// <param name="channel">通道</param>
    /// <param name="version">目标版本</param>
    /// <param name="key">升级指纹</param>
    /// <param name="detail">发布版本与安装包明细</param>
    /// <param name="ip">操作IP</param>
    private static void RecordUpgrade(Node node, NodeChannels channel, String version, String key, String detail, String ip)
    {
        var last = node.LastVersion;
        var attempts = last == version ? node.UpgradeAttempts + 1 : 1;

        node.Channel = channel;
        node.LastVersion = version;
        node.LastUpgradeKey = key;
        node.LastUpgradeTime = DateTime.Now;
        node.UpgradeAttempts = attempts;
        node.Update();

        node.WriteHistory(HistoryAction.AutoUpdate, true, L.TLog("Auto update dispatched: channel={0} from={1} last={2} attempts={3} => {4}; awaiting node confirmation", channel, node.Version, last, attempts, detail), ip);
    }

    /// <summary>检查节点是否符合规则,并推送dotNet运行时安装指令</summary>
    /// <remarks>只按 NodeVersion 的 dotNet 升级策略推送;DotNetPackage 安装包表仅用于手工推送</remarks>
    /// <param name="node">节点</param>
    /// <param name="baseUri">服务端基础地址,用于拼接默认下载源</param>
    /// <param name="ip">操作IP,用于写节点历史</param>
    /// <returns>推送的版本策略,未推送时返回null</returns>
    public NodeVersion CheckDotNet(Node node, Uri baseUri, String ip)
    {
        // 原生 Agent(Go/Rust/C++)没有 .NET 运行时,禁止推送 framework/install
        if (node.ProductCode.EqualIgnoreCase("StarAgent-Go", "StarAgent-Rust", "StarAgent-Cpp")) return null;

        // 检查 NodeVersion 中是否有启用的 dotNet 策略
        // 如果旧表存在 dotNet 记录但全部被禁用,说明管理员已明确关闭 dotNet 推送,直接跳过
        var allNv = NodeVersion.Meta.Cache.FindAll(e => e.ProductCode.EqualIgnoreCase("dotNet")).ToList();
        if (allNv.Count > 0 && allNv.All(e => !e.Enable))
            return null;

        // 找到所有产品版本
        var list = NodeVersion.GetValids(0).Where(e => e.ProductCode.EqualIgnoreCase("dotNet")).ToList();
        if (list.Count == 0) return null;

        using var span = _tracer?.NewSpan(nameof(CheckDotNet), new { node.Name, node.Code, node.Runtime, node.Framework, node.Frameworks, ip, vers = list.Count });

        // 应用过滤规则
        list = list.OrderByDescending(e => e.ID).Where(e => e.Match(node)).ToList();
        if (list.Count == 0) return null;

        // 每个版本都要检查,如果已经推送,则推送下一个
        foreach (var pv in list)
        {
            span?.AppendTag($"[{pv.ID}]{pv.Version}");

            // 准备安装框架所需要的参数
            var fmodel = new FrameworkModel { Version = pv.Version, BaseUrl = pv.Source, Force = pv.Force };
            // 如果没有指定源,则使用默认源
            if (fmodel.BaseUrl.IsNullOrEmpty()) fmodel.BaseUrl = new Uri(baseUri, "/files/dotnet/").ToString();
            span?.AppendTag($" source={fmodel.BaseUrl}");

            // 检查是否已经升级过这个版本
            var key = $"nodeNet:{node.Code}-{fmodel.Version}";
            if (_cacheProvider.Cache.Get<String>(key) == pv.Version) return null;
            _cacheProvider.Cache.Set(key, pv.Version, 600);

            var model = new CommandInModel
            {
                Code = node.Code,
                Command = "framework/install",
                Argument = fmodel.ToJson(),
                Expire = 60,
            };
            _ = SendCommand(node, model, $"NodeVersion:{pv.Version}");

            node.WriteHistory(HistoryAction.PushDotNet, true, $"version={node.Framework} => [{pv.ID}] {pv.Version} {fmodel.BaseUrl}", ip);

            return pv;
        }

        return null;
    }

    /// <summary>获取原生 Agent 的引导安装信息(.NET 运行时 + 完整版 StarAgent)</summary>
    /// <remarks>原生 Agent 只做采集与指令响应,需要完整能力时由它下载安装运行时与 .NET 版 StarAgent。
    /// 选包逻辑与安装引导页共用 <see cref="InstallService"/>,避免两处各写一套。</remarks>
    /// <param name="node">节点</param>
    /// <returns>引导安装信息;非原生 Agent,或服务端未维护对应安装包时返回null</returns>
    public BootstrapModel? GetBootstrap(Node node) => _installService.GetBootstrap(node);
    #endregion

    #region 下行指令
    /// <summary>向节点发送命令。通知节点更新、安装和启停应用等</summary>
    /// <param name="model"></param>
    /// <param name="token">应用令牌</param>
    /// <returns></returns>
    public override Task<CommandReplyModel?> SendCommand(DeviceContext context, CommandInModel model, CancellationToken cancellationToken = default)
    {
        if (model.Code.IsNullOrEmpty()) throw new ApiException(ApiCode.BadRequest, L.T("Node must be specified."));
        if (model.Command.IsNullOrEmpty()) throw new ApiException(ApiCode.BadRequest, L.T("Command must be specified."));

        var (jwt, ex) = _tokenService.DecodeToken(context.Token);
        if (ex != null) throw ex;

        var app = App.FindByName(jwt?.Subject);
        if (app == null) throw new ApiException(ApiCode.Unauthorized, L.T("The application [{0}] carried by the token does not exist. Check that the application exists and is enabled in the registry.", jwt?.Subject + ""));

        // 安全V-2:未配置密钥的应用(如种子StarWeb)可被匿名冒用登录,禁止其向节点下发命令,防止全节点RCE
        if (app.Secret.IsNullOrEmpty())
            throw new ApiException(ApiCode.Forbidden, L.T("[{0}] has no secret configured; node commands are forbidden. Set a Secret for this application in the registry.", app));

        // 节点在鉴权之后查找,避免匿名请求借错误码探测节点是否存在;无效节点按参数错误返回4xx,不抛未处理异常
        var node = Node.FindByCode(model.Code);
        if (node == null) throw new ApiException(ApiCode.NotFound, L.T("Node [{0}] does not exist.", model.Code));

        if (!app.AllowControlNodes.IsNullOrEmpty())
        {
            if (app.AllowControlNodes != "*" && !node.Code.EqualIgnoreCase(app.AllowControlNodes.Split(",")))
                throw new ApiException(ApiCode.Forbidden, L.T("[{0}] is not allowed to operate node [{1}].\nFor security, applications cannot send control commands to arbitrary nodes by default.\nIn the registry, edit the controllable nodes of [{0}], add [{2}], or set it to * for all nodes.", app, node, node.Code));
        }
        else if (!_setting.AllowControlNodesWhenEmpty)
            throw new ApiException(ApiCode.Forbidden, L.T("[{0}] has no controllable nodes configured.\nFor security, applications cannot send control commands to arbitrary nodes by default.\nIn the registry, edit the controllable nodes of [{0}], add [{1}], or set it to * for all nodes. Internal environments may set AllowControlNodesWhenEmpty=true to allow apps without explicit nodes.", app, node.Code));

        return SendCommand(node, model, app + "", cancellationToken);
    }

    /// <summary>向节点发送命令。(内部用)</summary>
    /// <param name="node">目标节点</param>
    /// <param name="model">命令参数</param>
    /// <param name="createUser">创建人</param>
    /// <param name="cancellationToken">取消令牌</param>
    /// <returns>命令响应。超时返回 null,reply.Status 反映设备端执行结果</returns>
    public async Task<CommandReplyModel> SendCommand(Node node, CommandInModel model, String createUser = null, CancellationToken cancellationToken = default)
    {
        var cmd = new NodeCommand
        {
            NodeID = node.ID,
            Command = model.Command,
            Argument = model.Argument,
            Times = 0,
            Status = CommandStatus.就绪,

            TraceId = DefaultSpan.Current?.TraceId,
            CreateUser = createUser,
        };
        if (model.StartTime > 0) cmd.StartTime = DateTime.Now.AddSeconds(model.StartTime);
        if (model.Expire > 0) cmd.Expire = DateTime.Now.AddSeconds(model.Expire);
        cmd.Insert();

        var commandModel = BuildCommand(node, cmd);
        var code = node.Code;

        // 通过SessionManager发布命令,内置timeout机制等待响应(跨实例广播)
        var reply = await _sessionManager.PublishAsync(code, commandModel, null, model.Timeout, cancellationToken);
        if (reply != null)
        {
            // 埋点
            using var span = _tracer?.NewSpan($"mq:NodeCommandReply", reply);

            return reply;
        }

        // fire-and-forget(timeout<=0)时 PublishAsync 立即返回 null,命令已写入 NodeCommand 并推送给节点,
        // 但这里仍需返回命令 Id 与当前状态,供调用方(如流水线)记录 CommandId 以便按回包事件精确命中
        return new CommandReplyModel { Id = cmd.Id, Status = cmd.Status };
    }
    #endregion

    #region 事件上报
    public override Int32 CommandReply(DeviceContext context, CommandReplyModel model)
    {
        var node = context.Device as Node;
        var cmd = NodeCommand.FindById((Int32)model.Id);
        if (cmd == null) return 0;

        // 安全V-17:防止水平越权,只允许命令所属节点回包(禁止伪造其它节点的命令状态)
        if (node == null || cmd.NodeID != node.ID)
            throw new ApiException(ApiCode.Forbidden, L.T("[{0}] attempted to reply to command [{1}] that belongs to node [{2}]", node?.Name, cmd.Id, cmd.NodeID));

        var ip = context.UserHost;
        var oldStatus = cmd.Status;

        cmd.Status = model.Status;
        cmd.Result = model.Data;
        cmd.Update();

        // 重启类命令回包时补写节点历史:命令回包只更新 NodeCommand,节点历史里原本看不到“谁在什么时候重启了节点”。
        // 代理侧不再重复上报同一事件,避免一次重启出现两条记录;仅在状态真正变化时写,网络重试的重复回包不会重复记历史
        if (oldStatus != model.Status && cmd.Command.EqualIgnoreCase("node/restart", "node/reboot") &&
            (model.Status == CommandStatus.已完成 || model.Status == CommandStatus.错误))
        {
            var success = model.Status == CommandStatus.已完成;
            NodeHistory.Create(node, HistoryAction.Restart, success, cmd.Command, cmd.CreateUser, ip).Insert();
        }

        // 通过会话管理器内置的响应事件总线广播响应(跨实例广播不阻塞)
        _ = _sessionManager.PublishResponseAsync(model, default);

        // 流水线续跑:按命令回包事件驱动步骤/run 状态更新(不轮询、不等待)
        _ = Task.Run(() => ProcessPipelineReplyAsync(cmd, model, ip));

        return 1;
    }

    /// <summary>按命令回包事件驱动流水线步骤/run 状态机更新,并在编译成功后续发部署。
    /// 仅处理关联了流水线步骤的命令(普通命令 FindAllByCommandId 返回空,直接跳过)。
    /// 同一命令回包可能因网络重试/多实例到达多次,用「条件更新(仅当步骤仍 Running 才迁移到终态)」保证续跑幂等、不双发部署。</summary>
    private async Task ProcessPipelineReplyAsync(NodeCommand cmd, CommandReplyModel model, String ip)
    {
        try
        {
            // 仅处理关联了流水线步骤的命令(普通命令 FindAllByCommandId 返回空,直接跳过)
            var step = AppPipelineStep.FindAllByCommandId(cmd.Id).FirstOrDefault();
            if (step == null) return;

            // 防重入快路径:步骤已非 Running(可能已被处理或重试)直接跳过,避免不必要工作
            if (step.Status != "Running") return;

            var run = AppPipelineRun.FindById(step.RunId);
            if (run == null) return;

            // 已取消/失败的 run 不再续跑,避免取消后又下发部署
            if (run.Status is PipelineStatus.Cancelled or PipelineStatus.Failed) return;

            var isError = model.Status == CommandStatus.错误;
            var isCancel = model.Status == CommandStatus.取消;
            // 已完成 等视为成功(仅 错误/取消 为失败)
            var isSuccess = !isError && !isCancel;

            var finishedTime = DateTime.Now;
            var targetStatus = isSuccess ? "Success" : (isCancel ? "Cancelled" : "Failed");

            if (step.StepType.EqualIgnoreCase("Build"))
            {
                // 原子迁移:仅当 DB 中该步骤仍为 Running 时才置终态;影响行数为 0 表示已被其他线程/实例处理,直接返回,
                // 杜绝并发回包(网络重试)重复续跑导致双发部署/双写历史/双设版本
                // 成功回包同样带上构建日志尾部,便于在步骤详情中排查
                if (TransitionStepToTerminal(step.Id, targetStatus, finishedTime, AppPipelineStep.CutMessage(model.Data)) == 0) return;
                // 本线程已抢到续跑权,同步内存对象供后续逻辑使用
                step.Status = targetStatus;
                step.FinishedTime = finishedTime;

                var pipeline = AppPipeline.FindById(run.PipelineId);
                var app = pipeline != null ? AppDeploy.FindById(pipeline.DeployId) : null;

                if (isSuccess)
                {
                    // 写编译成功历史(粒度日志由 Agent PostEvents 负责)
                    if (pipeline != null)
                        AppDeployHistory.Create(pipeline.DeployId, cmd.NodeID, "deploy/compile/Build-Upload", true, L.T("Build completed, run={0}", run.Id), ip).Insert();

                    // 取版本 + 使用版本(必须在部署下发前;等价于 Web「使用版本」按钮 app.Version=ver.Version)
                    var version = pipeline != null ? FindRunVersion(run, step, pipeline.DeployId) : null;
                    if (version != null)
                    {
                        run.AppVersionId = version.Id;
                        if (app != null)
                        {
                            app.Version = version.Version;
                            app.Update();
                        }
                        if (pipeline != null)
                            AppDeployHistory.Create(pipeline.DeployId, 0, "pipeline/version", true, L.T("Using version {0} (Id={1})", version.Version, version.Id), ip).Insert();
                    }
                    else
                    {
                        if (pipeline != null)
                            AppDeployHistory.Create(pipeline.DeployId, 0, "pipeline/version", false, L.T("No deployable version was found."), ip).Insert();
                    }
                    run.BuildFinishedTime = DateTime.Now;

                    if (pipeline == null || !pipeline.AutoDeploy)
                    {
                        run.Status = PipelineStatus.Success;
                        run.Remark = pipeline == null ? L.T("The pipeline configuration does not exist.") : L.T("Auto deploy is disabled; the pipeline ends.");
                        run.Update();
                        if (pipeline != null)
                            AppDeployHistory.Create(pipeline.DeployId, 0, "pipeline/autoDeploy", true, L.T("Auto deploy is disabled; the pipeline ends."), ip).Insert();
                    }
                    else
                    {
                        if (version == null)
                        {
                            // 编译成功但未产出可部署版本(如未开启上传),无法自动部署
                            run.Status = PipelineStatus.Failed;
                            run.Remark = L.T("The build succeeded but produced no deployable version (upload may be disabled); auto deploy is not possible.");
                            run.Update();
                            AppDeployHistory.Create(pipeline.DeployId, 0, "pipeline/autoDeploy", false, run.Remark, ip).Insert();
                            return;
                        }
                        run.Status = PipelineStatus.Deploying;
                        run.DeployStartedTime = DateTime.Now;
                        run.Update();
                        AppDeployHistory.Create(pipeline.DeployId, 0, "pipeline/autoDeploy", true, L.T("Starting auto deploy, run={0}, version={1}", run.Id, version.Version), ip).Insert();
                        await DispatchDeployAsync(run, pipeline, app, ip);

                        // 收尾:本次实际下发的部署命令数为 0(节点为空 / 全部 Skipped / 全部下发失败)时直接完成判定,
                        // 否则永远卡 Deploying(没有回包事件来触发完成判定)
                        var deploySteps = AppPipelineStep.FindAllByRunIdAndStepType(run.Id, "Deploy");
                        if (!deploySteps.Any(e => e.Status == "Running"))
                        {
                            run.DeployFinishedTime = DateTime.Now;
                            if (deploySteps.Any(e => e.Status == "Failed"))
                            {
                                run.Status = PipelineStatus.Failed;
                                run.Remark = L.T("Failed to dispatch the deploy command.");
                            }
                            else if (!deploySteps.Any(e => e.Status == "Success") && !deploySteps.Any(e => e.Status == "Skipped"))
                            {
                                // 没有任何部署步骤(通常因为未配置部署节点),不能标记为成功
                                run.Status = PipelineStatus.Failed;
                                run.Remark = L.T("No deployable node was found; check the pipeline deploy node configuration.");
                            }
                            else
                            {
                                run.Status = PipelineStatus.Success;
                            }
                            run.Update();
                            if (pipeline != null)
                                AppDeployHistory.Create(pipeline.DeployId, 0, "deploy/install", run.Status == PipelineStatus.Success, run.Status == PipelineStatus.Success ? L.T("Deployment completed.") : run.Remark, ip).Insert();
                            return;
                        }
                    }
                }
                else
                {
                    run.BuildFinishedTime = DateTime.Now;
                    run.Status = isCancel ? PipelineStatus.Cancelled : PipelineStatus.Failed;
                    run.Remark = AppPipelineStep.CutMessage(model.Data, 480);
                    run.Update();
                }
            }
            else if (step.StepType.EqualIgnoreCase("Deploy"))
            {
                // 原子迁移:仅当 DB 中该步骤仍为 Running 时才置终态,影响行数为 0 表示已处理,直接返回
                if (TransitionStepToTerminal(step.Id, targetStatus, finishedTime, AppPipelineStep.CutMessage(model.Data)) == 0) return;
                step.Status = targetStatus;
                step.FinishedTime = finishedTime;

                var pipeline = AppPipeline.FindById(run.PipelineId);

                if (isSuccess)
                {
                    // 完成判定:基于最新 DB 数据(用 FindAll 绕过实体缓存,确保读到其他部署步骤的最新状态),避免读旧快照卡 Deploying
                    var deploySteps = AppPipelineStep.FindAllByRunIdAndStepType(run.Id, "Deploy");
                    if (!deploySteps.Any(e => e.Status == "Running"))
                    {
                        run.DeployFinishedTime = DateTime.Now;
                        run.Status = PipelineStatus.Success;
                        run.Update();
                        // 写部署完成历史(与 Build 分支风格一致)
                        if (pipeline != null)
                            AppDeployHistory.Create(pipeline.DeployId, step.NodeId, "deploy/install/Deploy", true, L.T("Deployment succeeded."), ip).Insert();
                    }
                }
                else
                {
                    run.Status = isCancel ? PipelineStatus.Cancelled : PipelineStatus.Failed;
                    run.Remark = AppPipelineStep.CutMessage(model.Data, 480);
                    run.Update();
                }
            }
        }
        catch (Exception ex)
        {
            XTrace.WriteException(ex);
        }
    }

    /// <summary>匹配本次运行产出的部署版本。优先提交号一致;提交号缺失时只接受构建开始后生成且同样无提交号的版本,
    /// 避免并发构建或手工上传时误取其它版本的包。</summary>
    /// <param name="run">运行记录</param>
    /// <param name="step">构建步骤</param>
    /// <param name="deployId">部署集编号</param>
    /// <returns>匹配的版本,未找到返回 null</returns>
    private static AppDeployVersion FindRunVersion(AppPipelineRun run, AppPipelineStep step, Int32 deployId)
    {
        // 允许 5 分钟时钟偏差:版本创建时间可能因拦截器取时与步骤取时存在毫秒级逆序
        var since = (step.StartedTime.Year > 2000 ? step.StartedTime : run.CreateTime).AddMinutes(-5);
        var list = AppDeployVersion.FindAllByDeployIdAfter(deployId, since, 20);
        if (list.Count == 0) return null;

        if (!run.CommitId.IsNullOrEmpty())
        {
            var hit = list.FirstOrDefault(e => IsSameCommit(run.CommitId, e.CommitId));
            if (hit != null) return hit;

            // 非 git 源码目录的版本没有提交号,仅当全部候选都无提交号时接受
            if (list.All(e => e.CommitId.IsNullOrEmpty())) return list[0];

            // 附注标签推送的 after 是标签对象 SHA,与提交 SHA 不同;本次窗口内只有一个候选时视为本次产物
            if (list.Count == 1) return list[0];

            return null;
        }

        return list[0];
    }

    /// <summary>提交号比对。兼容 webhook 全量与 git rev-parse 全量、以及任意一方为短号的情况</summary>
    private static Boolean IsSameCommit(String? a, String? b)
    {
        if (a.IsNullOrEmpty() || b.IsNullOrEmpty()) return false;

        return a.StartsWithIgnoreCase(b) || b.StartsWithIgnoreCase(a);
    }

    /// <summary>原子地把步骤从 Running 迁移到指定终态,保证同一命令回包(含网络重试 / 多实例)只被处理一次。
    /// 仅当数据库当前状态仍为 Running 时才更新,返回受影响行数(0 表示已被其他线程 / 实例处理)。</summary>
    /// <param name="stepId">步骤 Id</param>
    /// <param name="targetStatus">目标终态(Success/Failed/Cancelled)</param>
    /// <param name="finishedTime">结束时间</param>
    /// <param name="message">失败/取消时的错误信息;成功传 null(不写入)</param>
    private static Int32 TransitionStepToTerminal(Int64 stepId, String targetStatus, DateTime finishedTime, String message)
    {
        // 参数化条件更新:仅当 Id 匹配且当前 Status='Running' 时才更新;
        // 数据库层原子保证并发(含多实例)下只有一个线程能抢到续跑权,影响行数为 0 即已被处理。
        // Message 列宽 2000,而回包错误输出(含构建日志尾巴)可达 6000+ 字符,
        // 必须截断保留尾部(真正的失败原因在末尾),否则 SqlServer 报 truncated 异常导致步骤永远卡在 Running
        return AppPipelineStep.Update(
            new[] { nameof(AppPipelineStep.Status), nameof(AppPipelineStep.FinishedTime), nameof(AppPipelineStep.Message) },
            new Object[] { targetStatus, finishedTime, AppPipelineStep.CutMessage(message) },
            new[] { nameof(AppPipelineStep.Id), nameof(AppPipelineStep.Status) },
            new Object[] { stepId, "Running" }
        );
    }

    /// <summary>为每个部署节点建立「部署」步骤并下发 deploy/install 命令,记录各自 CommandId。
    /// 仅在 StarServer 进程内调用(CommandReply 只在此进程触发),直接操作 NodeCommand 与 PipelineStep。
    /// 克制原则:一条流水线对应一个分支,仅部署流水线「显式勾选」的部署节点;未勾选任何节点时不做任何部署,避免误部署。</summary>
    private async Task DispatchDeployAsync(AppPipelineRun run, AppPipeline pipeline, AppDeploy app, String ip)
    {
        var nodeIds = (pipeline.DeployNodeIds ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries);

        // 未勾选任何部署节点:不回退、不乱部署,仅记录明确日志并结束(上层据此标记 Failed,避免假成功)
        if (nodeIds.Length == 0)
        {
            AppDeployHistory.Create(pipeline.DeployId, 0, "pipeline/autoDeploy", false, L.T("Auto deploy was not triggered: no deploy node is selected for the pipeline."), ip).Insert();
            return;
        }

        // 部署步骤序号在 Build 步骤(索引 0)基础上递增,保证步骤顺序正确
        var idx = 1;
        foreach (var nid in nodeIds)
        {
            var dn = AppDeployNode.FindById(nid.ToInt());

            var deployStep = new AppPipelineStep
            {
                RunId = run.Id,
                StepType = "Deploy",
                StepIndex = idx++,
                NodeId = dn?.NodeId ?? 0,
                Status = "Running",
                StartedTime = DateTime.Now,
                CreateTime = DateTime.Now,
            };

            if (dn == null)
            {
                deployStep.Status = "Skipped";
                deployStep.Message = L.T("Deployment node [{0}] does not exist.", nid);
                AppDeployHistory.Create(pipeline.DeployId, 0, "pipeline/autoDeploy", false, deployStep.Message, ip).Insert();
            }
            else if (!dn.Enable)
            {
                deployStep.Status = "Skipped";
                deployStep.Message = L.T("Deployment node [{0}] is disabled.", dn.NodeName);
                AppDeployHistory.Create(pipeline.DeployId, dn.NodeId, "pipeline/autoDeploy", false, deployStep.Message, ip).Insert();
            }
            else if (dn.DeployId != pipeline.DeployId)
            {
                deployStep.Status = "Skipped";
                deployStep.Message = L.T("Deployment node [{0}] DeployId mismatch.", dn.NodeName);
                AppDeployHistory.Create(pipeline.DeployId, dn.NodeId, "pipeline/autoDeploy", false, deployStep.Message, ip).Insert();
            }
            else
            {
                var node = Node.FindByID(dn.NodeId);
                if (node == null)
                {
                    deployStep.Status = "Skipped";
                    deployStep.Message = L.T("Node [{0}] does not exist.", dn.NodeId);
                    AppDeployHistory.Create(pipeline.DeployId, dn.NodeId, "pipeline/autoDeploy", false, deployStep.Message, ip).Insert();
                }
                else
                {
                    try
                    {
                        // 使用版本后再下发:app.Version 已在上一步设为刚编译的新版本,Agent 拉部署任务时按 app.Version 取新包
                        // 注意:不强制启用被禁节点,仅对已启用节点创建 Deploy 步骤(被禁/不存在节点在上方已置 Skipped)

                        var deployName = dn.DeployName;
                        if (deployName.IsNullOrEmpty()) deployName = app?.Name;
                        var args = new { dn.Id, DeployName = deployName, app?.AppName }.ToJson();

                        var cmdModel = new CommandInModel
                        {
                            Command = "deploy/install",
                            Argument = args,
                            Timeout = 0, // fire-and-forget,不等待回包
                        };
                        var reply = await SendCommand(node, cmdModel, "Pipeline");
                        deployStep.CommandId = (Int32)(reply?.Id ?? 0);
                        AppDeployHistory.Create(pipeline.DeployId, dn.NodeId, "deploy/install", true, L.T("Deploy command dispatched to node {0} (CommandId={1}).", dn.NodeName, deployStep.CommandId), ip).Insert();
                    }
                    catch (Exception ex)
                    {
                        deployStep.Status = "Failed";
                        deployStep.FinishedTime = DateTime.Now;
                        deployStep.Message = AppPipelineStep.CutMessage(ex.Message);
                        AppDeployHistory.Create(pipeline.DeployId, dn.NodeId, "deploy/install", false, L.T("Failed to dispatch the deploy command to node {0}: {1}", dn.NodeName, ex.Message), ip).Insert();
                    }
                }
            }

            if (deployStep.Status != "Running") deployStep.FinishedTime = DateTime.Now;
            deployStep.Insert();
        }
    }

    public override Int32 PostEvents(DeviceContext context, EventModel[] events)
    {
        var node = context.Device as Node;
        var ip = context.UserHost;
        var his = new List<NodeHistory>();
        var dis = new List<AppDeployHistory>();
        foreach (var model in events)
        {
            var success = !model.Type.EqualIgnoreCase("error");

            // 代理升级结果:成功即停止重试;失败则清空指纹并让退避立即到期,使下一轮检查重新下发
            if (node != null && model.Name.EqualIgnoreCase(HistoryAction.Upgrade))
            {
                if (model.Type.EqualIgnoreCase("success"))
                    node.UpgradeAttempts = Node.MaxUpgradeAttempts;
                else if (!success)
                {
                    node.LastUpgradeKey = null;
                    node.LastUpgradeTime = DateTime.Now.Add(-GetUpgradeBackoff(node.UpgradeAttempts));
                }

                node.Update();
            }

            if (model.Name.EqualIgnoreCase("ServiceController"))
            {
                var appId = 0;
                var p = model.Type.LastIndexOf('-');
                if (p > 0)
                {
                    success = !model.Type[(p + 1)..].EqualIgnoreCase("error");
                    appId = AppDeploy.FindByName(model.Type[..p])?.Id ?? 0;
                }

                //_deployService.WriteHistory(appId, _node?.ID ?? 0, model.Name, success, model.Remark, UserHost);
                var dhi = AppDeployHistory.Create(appId, node?.ID ?? 0, model.Name, success, model.Remark, ip);
                dis.Add(dhi);
            }

            var history = NodeHistory.Create(node, model.Name, success, model.Remark, Environment.MachineName, ip);
            var time = model.Time.ToDateTime().ToLocalTime();
            if (time.Year > 2000) history.CreateTime = time;
            his.Add(history);
        }

        his.Insert();
        dis.Insert();

        return events.Length;
    }
    #endregion

    #region 辅助
    public override IDeviceModel? QueryDevice(String code) => Node.FindByCode(code);

    public override IOnlineModel? QueryOnline(String sessionId) => NodeOnline.FindBySessionId(sessionId, true);

    protected override String GetSessionId(DeviceContext context) => context.Code ?? base.GetSessionId(context);

    private CommandModel BuildCommand(Node node, NodeCommand cmd)
    {
        var model = cmd.ToModel();
        model.TraceId = DefaultSpan.Current + "";

        // 新版本使用UTC时间
        if (node.CompileTime.Year >= 2025)
        {
            if (model.StartTime.Year > 2000)
                model.StartTime = model.StartTime.ToUniversalTime();
            if (model.Expire.Year > 2000)
                model.Expire = model.Expire.ToUniversalTime();
        }

        return model;
    }

    private void WriteHistory(Node node, String action, Boolean success, String remark, String ip = null)
    {
        var hi = NodeHistory.Create(node, action, success, remark, Environment.MachineName, ip);
        hi.Insert();
    }

    public override void WriteHistory(DeviceContext context, String action, Boolean success, String remark)
    {
        var hi = NodeHistory.Create(context.Device as Node, action, success, remark, Environment.MachineName, context.UserHost);
        hi.Insert();
    }
    #endregion
}

public class MySortedList<TKey, TValue>
{
    public List<TKey> Keys { get; private set; } = [];

    public List<TValue> Values { get; private set; } = [];

    public void Add(TKey key, TValue value)
    {
        // 二分法搜索
        var idx = Keys.BinarySearch(key);
        if (idx >= 0)
        {
            // 找到已有元素,在其后面插入
            Keys.Insert(idx + 1, key);
            Values.Insert(idx + 1, value);
        }
        else
        {
            // 补码得到索引。判断是否在最后
            idx = ~idx;
            if (idx >= Keys.Count)
            {
                Keys.Add(key);
                Values.Add(value);
            }
            else
            {
                Keys.Insert(idx, key);
                Values.Insert(idx, value);
            }
        }
    }
}