节点在线、应用在线、配置在线使用令牌查询
大石头 authored at 2021-12-16 19:49:30
57.21 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;

    /// <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="serviceProvider">服务提供者</param>
    public NodeService(ITokenService tokenService, IPasswordProvider passwordProvider, StarServerSetting setting, NodeSessionManager sessionManager, ICacheProvider cacheProvider, ITracer tracer, DnsService dnsService, IServiceProvider serviceProvider) : base(sessionManager, passwordProvider, cacheProvider, serviceProvider)
    {
        _tokenService = tokenService;
        _passwordProvider = passwordProvider;
        _setting = setting;
        _sessionManager = sessionManager;
        _cacheProvider = cacheProvider;
        _tracer = tracer;
        _dnsService = dnsService;

        Name = "Node";
    }

    #region 登录注销
    /// <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, L.T("Node authentication"), false, L.T("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, L.T("Node authentication"), false, L.T("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(L.T("Dynamic registration"), true, inf.ToJson(false, false, false), ip);
        }
        catch (Exception ex)
        {
            span?.SetError(ex, null);

            node?.WriteHistory(L.T("Dynamic registration"), 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, L.T("Node authentication"), true, L.T("[{0}/{1}] authenticated {2}", node.Name, node.Code, inf.ToJson(false, false, false)));

        // 检查节点上线恢复
        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._.Uuid);
        guid = TrimLength(guid, Node._.MachineGuid);
        serial = TrimLength(serial, Node._.SerialNumber);
        board = TrimLength(board, Node._.Board);
        diskid = TrimLength(diskid, Node._.DiskID);

        var level = 5;
        if (!uuid.IsNullOrEmpty() && uuid != node.Uuid)
        {
            node.WriteHistory(L.T("Login validation"), false, L.T("Unique identifier mismatch (new != old): {0} != {1}", uuid, node.Uuid), ip);
            level--;
        }
        if (!guid.IsNullOrEmpty() && guid != node.MachineGuid)
        {
            node.WriteHistory(L.T("Login validation"), false, L.T("Machine identifier mismatch (new != old): {0} != {1}", guid, node.MachineGuid), ip);
            level--;
        }
        if (!serial.IsNullOrEmpty() && serial != node.SerialNumber)
        {
            node.WriteHistory(L.T("Login validation"), false, L.T("Computer serial number mismatch (new != old): {0} != {1}", serial, node.SerialNumber), ip);
            level--;
        }
        if (!board.IsNullOrEmpty() && board != node.Board)
        {
            node.WriteHistory(L.T("Login validation"), false, L.T("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(L.T("Login validation"), false, L.T("Product code mismatch (new != old): {0} != {1}", productCode, node.ProductCode), ip);
            //level--;
        }

        // 机器名
        if (di.MachineName != node.MachineName)
        {
            node.WriteHistory(L.T("Login validation"), false, L.T("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(L.T("Login validation"), false, L.T("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(L.T("Login validation"), false, L.T("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, FieldItem field)
    {
        if (value.IsNullOrEmpty()) return value;
        if (field.Length <= 0 || value.Length < field.Length) return value;

        return value[..field.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.T("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(L.T("Matched existing node"), 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 心跳保活
    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;
    }
    #endregion

    #region 升级更新
    /// <summary>升级检查。新版优先匹配 ProductRelease + ProductPackage,回退到旧 NodeVersion 逻辑</summary>
    /// <param name="channel">更新通道</param>
    /// <returns></returns>
    public override IUpgradeInfo? Upgrade(DeviceContext context, String? channel)
    {
        // 默认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;

        // ---- 新路径: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.OrderByDescending(e => e.ID).FirstOrDefault(e => e.Version != node.LastVersion && e.Match(node));
        if (pv == null) return null;

        // 检查是否已经升级过这个版本
        if (node.LastVersion == pv.Version) return null;

        node.WriteHistory(L.T("Auto update"), true, $"channel={ch} version={node.Version} last={node.LastVersion} => [{pv.ID}] {pv.Version} {pv.Executor}", ip);

        node.Channel = ch;
        node.LastVersion = pv.Version;
        node.Update();

        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>尝试从新的 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)
        {
            // 检查是否已经升级过这个版本
            if (node.LastVersion == release.Version) continue;

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

            node.WriteHistory(L.T("Auto update"), true, $"channel={channel} version={node.Version} last={node.LastVersion} => Release[{release.Id}] {release.Version} Package[{pkg.TargetRuntime}] {pkg.FileName}", ip);

            node.Channel = channel;
            node.LastVersion = release.Version;
            node.Update();

            // 双层取值: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>检查节点是否符合规则,并推送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(L.T("Push dotNet"), true, $"version={node.Framework} => [{pv.ID}] {pv.Version} {fmodel.BaseUrl}", ip);

            return pv;
        }

        return null;
    }
    #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 ArgumentNullException(nameof(model.Code), L.T("Node must be specified."));
        if (model.Command.IsNullOrEmpty()) throw new ArgumentNullException(nameof(model.Command));

        var node = Node.FindByCode(model.Code);
        if (node == null) throw new ArgumentOutOfRangeException(nameof(model.Code), L.T("Invalid node."));

        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("No permission to perform this operation."));

        // 安全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));

        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.Unauthorized, L.T("No permission to perform this operation."));

        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));

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

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

        // 流水线续跑:按命令回包事件驱动步骤/run 状态更新(不轮询、不等待)
        var ip = context.UserHost;
        _ = 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, isSuccess ? null : 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 ? AppDeployVersion.FindAllByDeployId(pipeline.DeployId, 1).FirstOrDefault() : 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.FindAll(AppPipelineStep._.RunId == run.Id & AppPipelineStep._.StepType == "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 = model.Data;
                    run.Update();
                }
            }
            else if (step.StepType.EqualIgnoreCase("Deploy"))
            {
                // 原子迁移:仅当 DB 中该步骤仍为 Running 时才置终态,影响行数为 0 表示已处理,直接返回
                if (TransitionStepToTerminal(step.Id, targetStatus, finishedTime, isSuccess ? null : model.Data) == 0) return;
                step.Status = targetStatus;
                step.FinishedTime = finishedTime;

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

                if (isSuccess)
                {
                    // 完成判定:基于最新 DB 数据(用 FindAll 绕过实体缓存,确保读到其他部署步骤的最新状态),避免读旧快照卡 Deploying
                    var deploySteps = AppPipelineStep.FindAll(AppPipelineStep._.RunId == run.Id & AppPipelineStep._.StepType == "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 = model.Data;
                    run.Update();
                }
            }
        }
        catch (Exception ex)
        {
            XTrace.WriteException(ex);
        }
    }

    /// <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 即已被处理
        return AppPipelineStep.Update(
            new[] { nameof(AppPipelineStep.Status), nameof(AppPipelineStep.FinishedTime), nameof(AppPipelineStep.Message) },
            new Object[] { targetStatus, finishedTime, 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 = 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 (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);
            }
        }
    }
}