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

XFEEDToolBox

【WinUI】XFE精英危险工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.IO.Compression;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;

namespace XFEEDToolBox.Core.Galaxy;

/// <summary>Small, compressed catalogue requests with a deadline covering the response body as well as headers.</summary>
internal static class PlaceSearchHttp
{
    internal static async Task<JsonDocument> ReadAsync(HttpClient http,string url,object? payload,CancellationToken token)
    {
        for(var attempt=0;attempt<2;attempt++)
        {
            token.ThrowIfCancellationRequested();
            using var deadline=CancellationTokenSource.CreateLinkedTokenSource(token);
            deadline.CancelAfter(TimeSpan.FromSeconds(8));
            try
            {
                using var request=new HttpRequestMessage(payload is null?HttpMethod.Get:HttpMethod.Post,url);
                request.Headers.AcceptEncoding.ParseAdd("gzip");
                if(payload is not null)request.Content=JsonContent.Create(payload);
                using var response=await http.SendAsync(request,HttpCompletionOption.ResponseHeadersRead,deadline.Token).ConfigureAwait(false);
                response.EnsureSuccessStatusCode();
                await using var raw=await response.Content.ReadAsStreamAsync(deadline.Token).ConfigureAwait(false);
                // Also works with an injected client whose handler already decompressed the body.
                await using var body=response.Content.Headers.ContentEncoding.Contains("gzip",StringComparer.OrdinalIgnoreCase)
                    ?new GZipStream(raw,CompressionMode.Decompress,leaveOpen:true):raw;
                using var buffer=new MemoryStream();var block=new byte[16384];
                int read;
                while((read=await body.ReadAsync(block,deadline.Token).ConfigureAwait(false))>0)
                {
                    if(buffer.Length+read>16*1024*1024)throw new InvalidDataException("地点搜索响应超出大小限制。");
                    buffer.Write(block,0,read);
                }
                deadline.Token.ThrowIfCancellationRequested();
                return JsonDocument.Parse(buffer.GetBuffer().AsMemory(0,checked((int)buffer.Length)));
            }
            catch(OperationCanceledException) when(!token.IsCancellationRequested)
            {
                if(attempt==1)throw new TimeoutException("地点服务响应超时,已自动重试,请稍后再试。");
            }
            catch(HttpRequestException error) when(attempt==0&&Transient(error.StatusCode)){ }
            catch(IOException) when(attempt==0){ }
            await Task.Delay(200,token).ConfigureAwait(false);
        }
        throw new InvalidOperationException("地点搜索未完成。");
    }

    private static bool Transient(HttpStatusCode? status)=>status is null or HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests||(int)status>=500;
}