XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWarframe

【WinUI】基于Warframe游戏本体的公开服务器以及安装器

公开
关注 0 Fork 0 Star 0
UTF-8
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using XFEWarframe.Core.Data;

namespace XFEWarframe.Core.Services;

public sealed class OfficialEventSynchronizer(StateStore store, ServerOptions options, TimeProvider clock, HttpClient? client = null)
{
    private static readonly HttpClient SharedClient = new(new HttpClientHandler { AllowAutoRedirect = false, AutomaticDecompression = System.Net.DecompressionMethods.All }) { Timeout = TimeSpan.FromSeconds(15) };
    private readonly SemaphoreSlim gate = new(1, 1);
    private readonly HttpClient http = client ?? SharedClient;
    private long Now => clock.GetUtcNow().ToUnixTimeMilliseconds();
    private bool Enabled(JObject state) => OfficialEvents.Enabled(state, options.SyncOfficialEvents);
    public Task<JObject> Status() => store.Project(state => OfficialEvents.Status(state, Now, Enabled(state), options.OfficialEventsIntervalSeconds));

    public async Task<JObject> Synchronize(CancellationToken cancellation = default)
    {
        await gate.WaitAsync(cancellation);
        try
        {
            if (!await store.Project(Enabled)) throw new ApiException(409, "官方活动同步已关闭。");
            using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
            timeout.CancelAfter(TimeSpan.FromSeconds(15));
            var token = timeout.Token;
            using var request = new HttpRequestMessage(HttpMethod.Get, OfficialEvents.Source);
            request.Headers.Accept.ParseAdd("application/json");
            using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, token);
            response.EnsureSuccessStatusCode();
            if (response.Content.Headers.ContentLength is > 4 * 1024 * 1024) throw new InvalidDataException("Official world state exceeds the size limit.");
            await using var stream = await response.Content.ReadAsStreamAsync(token);
            using var buffer = new MemoryStream();
            var bytes = new byte[16384];
            while (true)
            {
                var count = await stream.ReadAsync(bytes, token);
                if (count == 0) break;
                if (buffer.Length + count > 4 * 1024 * 1024) throw new InvalidDataException("Official world state exceeds the size limit.");
                buffer.Write(bytes, 0, count);
            }
            var now = Now;
            var world = OfficialEvents.Validate(System.Text.Encoding.UTF8.GetString(buffer.ToArray()), now);
            await store.Update(state => { if (!Enabled(state)) return false; OfficialEvents.Store(state, world, now); return true; });
            return await Status();
        }
        catch (Exception ex) when (ex is HttpRequestException or IOException or JsonException or InvalidDataException or OperationCanceledException)
        {
            if (cancellation.IsCancellationRequested) throw;
            await store.Update(state => {
                var snapshot = state.Obj("officialEvents"); snapshot["lastAttempt"] = Now;
                snapshot["lastError"] = ex is HttpRequestException web ? $"官方接口请求失败:{web.StatusCode?.ToString() ?? "network"}" : "官方活动快照无效或请求超时;保留上次成功的快照。";
                return false;
            });
            throw new ApiException(502, "同步官方活动失败,已保留上次成功的快照。请查看同步状态。");
        }
        finally { gate.Release(); }
    }

    public async Task Run(CancellationToken cancellation)
    {
        while (!cancellation.IsCancellationRequested)
        {
            try { if (await store.Project(Enabled)) await Synchronize(cancellation); }
            catch (ApiException) { /* Availability is reported separately; game APIs keep serving cached events. */ }
            await Task.Delay(TimeSpan.FromSeconds(options.OfficialEventsIntervalSeconds), cancellation);
        }
    }
}