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

namespace Stardust.Server.Services;

public class AppSessionManager : SessionManager
{
    /// <summary>上行数据包事件交换机</summary>
    public EventHub<IPacket> Hub { get; set; } = new();

    public AppSessionManager(IServiceProvider serviceProvider, ITracer tracer, ILog log) : base(serviceProvider)
    {
        Topic = "AppCommands";
        Hub.Tracer = tracer;
        Hub.Log = log;

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

    /// <summary>向管理器添加会话</summary>
    /// <param name="session"></param>
    public override void Add(ICommandSession session)
    {
        if (session is WsCommandSession ws)
            ws.Dispatcher = Hub;

        base.Add(session);
    }
}

class AppCommandSession(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("WebSocket send", false, "The message is invalid or has expired." + message);

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

            return Task.CompletedTask;
        }

        {
            Log?.WriteLog("WebSocket send", true, message);

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

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