节点在线、应用在线、配置在线使用令牌查询
大石头 authored at 2021-12-16 19:49:30
1.76 KiB
Stardust
using System.Net.WebSockets;
using NewLife.Remoting.Extensions.Services;
using NewLife.Remoting.Models;
using NewLife.Remoting.Services;
using Stardust.Data;
using Stardust.Data.Nodes;

namespace Stardust.Server.Services;

public class NodeSessionManager : SessionManager
{
    public NodeSessionManager(IServiceProvider serviceProvider) : base(serviceProvider)
    {
        Topic = "NodeCommands";

        var lifeTime = serviceProvider.GetService<IHostApplicationLifetime>();
        lifeTime.ApplicationStopping.Register(() =>
        {
            // 关闭时,清除所有会话
            CloseAll(nameof(lifeTime.ApplicationStopping));
        });
    }
}

class NodeCommandSession(WebSocket socket) : WsCommandSession(socket)
{
    public override Task HandleAsync(CommandModel command, String message, CancellationToken cancellationToken)
    {
        if (command == null || command.Id == 0 || command.Expire.Year > 2000 && command.Expire < DateTime.UtcNow)
        {
            Log?.WriteLog(HistoryAction.WebSocketSend, false, "The message is invalid or has expired." + message);

            var log = NodeCommand.FindById((Int32)command.Id);
            if (log != null)
            {
                log.Status = CommandStatus.取消;
                log.Update();
            }

            return Task.CompletedTask;
        }

        {
            Log?.WriteLog(HistoryAction.WebSocketSend, true, message);

            var log = NodeCommand.FindById((Int32)command.Id);
            if (log != null)
            {
                log.Times++;
                log.Status = CommandStatus.处理中;
                log.UpdateTime = DateTime.Now;
                log.Update();
            }
        }

        return base.HandleAsync(command, message, cancellationToken);
    }
}