节点在线、应用在线、配置在线使用令牌查询
大石头 authored at 2021-12-16 19:49:30
5.46 KiB
Stardust
using NewLife;
using NewLife.Common;
using NewLife.Data;
using NewLife.Log;
using Stardust.Data.Deployment;
using Stardust.Storages;
using XCode;

namespace Stardust.Server.Services;

/// <summary>分布式文件存储服务。延迟初始化文件存储引擎,避免服务启动时资源争抢</summary>
public class FileStorageService(IFileStorage fileStorage) : IHostedService
{
    /// <summary>启动服务。延迟10秒后初始化文件存储</summary>
    /// <param name="cancellationToken">取消令牌</param>
    /// <returns>任务</returns>
    Task IHostedService.StartAsync(CancellationToken cancellationToken)
    {
        // 延迟10秒后初始化,避免和其它服务争抢资源
        // 不阻塞 Host 启动:在后台执行
        _ = InitializeLaterAsync(cancellationToken);

        return Task.CompletedTask;
    }

    /// <summary>停止服务</summary>
    /// <param name="cancellationToken">取消令牌</param>
    /// <returns>任务</returns>
    Task IHostedService.StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;

    /// <summary>延迟初始化文件存储引擎</summary>
    /// <param name="cancellationToken">取消令牌</param>
    private async Task InitializeLaterAsync(CancellationToken cancellationToken)
    {
        await Task.Delay(10_000, cancellationToken);
        await fileStorage.InitializeAsync(cancellationToken);
    }
}

public static class FileStorageExtensions
{
    /// <summary>注册魔方版文件存储</summary>
    /// <param name="services">服务集合</param>
    /// <param name="name">集群名。相同名称的多个应用共享一个文件存储集群,如StarWeb和StarServer。默认为null时使用应用标识,集群部署的多节点应用实例共享文件存储</param>
    /// <returns></returns>
    public static IServiceCollection AddCubeFileStorage(this IServiceCollection services, String name = null)
    {
        if (name.IsNullOrEmpty()) name = StarSetting.Current.AppKey;
        if (name.IsNullOrEmpty()) name = SysConfig.Current.Name;

        //services.AddSingleton<IFileStorage, CubeFileStorage>();
        //services.AddSingleton<IFileStorage>(new CubeFileStorage { Name = name });
        services.AddSingleton<CubeFileStorage>();
        services.AddSingleton<IFileStorage>(sp =>
        {
            var storage = sp.GetRequiredService<CubeFileStorage>();
            storage.Name = name;

            // 从配置读取文件存储行为开关
            var set = sp.GetService<StarServerSetting>();
            if (set != null)
            {
                storage.EnableProvide = set.FileStorageProvide;
                storage.EnableFetch = set.FileStorageFetch;
            }

            return storage;
        });

        // 仅当提供或拉取任一功能开启时,才启动后台文件存储服务(事件总线订阅/扫描定时)。
        // 注意:IFileStorage 已始终注册,此处是否注册后台服务不影响 CubeController 的激活。
        if (StarServerSetting.Current.FileStorageProvide || StarServerSetting.Current.FileStorageFetch)
            services.AddHostedService<FileStorageService>();

        return services;
    }
}

public class CubeFileStorage : DefaultFileStorage
{
    public CubeFileStorage(StarServerSetting setting, IServiceProvider serviceProvider, ITracer tracer, ILog log)
    {
        //NodeName = Environment.MachineName;
        RootPath = setting.UploadPath;
        DownloadUri = "/cube/file?id={Id}";

        ServiceProvider = serviceProvider;
        Tracer = tracer;
        Log = log;
    }

    /// <summary>获取本地文件的元数据</summary>
    protected override IFileInfo GetLocalFileMeta(Int64 attachmentId, String path)
    {
        //if (path.IsNullOrEmpty()) throw new ArgumentNullException(nameof(path));

        var att = Attachment.FindById(attachmentId);

        return new NewFileInfo
        {
            Id = att.Id,
            Name = att.FileName,
            Path = att.FilePath,
            Hash = att.Hash,
            Length = att.Size,
        };
    }

    //public override async Task<Int32> ScanFilesAsync(DateTime startTime, CancellationToken cancellationToken = default)
    //{
    //    if (FileRequestBus is StarEventBus<FileRequest> bus && !bus.IsReady) return -1;

    //    return await base.ScanFilesAsync(startTime, cancellationToken);
    //}

    /// <summary>获取本地不存在的附件列表。用于文件同步</summary>
    /// <param name="startTime">从指定时间开始遍历</param>
    /// <returns></returns>
    protected override IEnumerable<IFileInfo> GetMissingAttachments(DateTime startTime)
    {
        var page = new PageParameter { PageIndex = 1, PageSize = 100, Sort = Attachment.__.Id, Desc = true };

        while (true)
        {
            var list = Attachment.SearchByTime(startTime, page);
            if (list == null || list.Count == 0) break;

            foreach (var att in list)
            {
                var filePath = att.GetFilePath(RootPath);
                if (!filePath.IsNullOrEmpty() && !File.Exists(filePath))
                {
                    yield return new NewFileInfo
                    {
                        Id = att.Id,
                        Name = att.FileName,
                        Path = att.FilePath,
                        Hash = att.Hash,
                        Length = att.Size,
                    };
                }
            }

            if (list.Count < page.PageSize) break;
            page.PageIndex++;
        }
    }
}