using System.IO.Compression; using System.Net; using System.Net.Http.Json; using System.Text.Json; namespace XFEEDToolBox.Core.Galaxy; /// Small, compressed catalogue requests with a deadline covering the response body as well as headers. internal static class PlaceSearchHttp { internal static async Task 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; }