using System.Net; using System.Net.Http.Json; using System.Text.Json; using Admin.NET.Plugin.AiDOP.DataPlatform.Core; namespace Admin.NET.DataPlatform.Worker; internal sealed class PurchaseHandoffClient(HttpClient http, Uri endpoint, byte[] key) : IAidopPackageHandoff { public async Task SubmitAsync(PurchaseHandoffPackage package, CancellationToken token) => await SendAsync(HttpMethod.Post, endpoint, package.ComputeDigest(), package, token) ?? throw new PurchaseHandoffException("HANDOFF_INVALID_RECEIPT", true); public Task FindReceiptAsync(Guid batch, string digest, CancellationToken token) => SendAsync(HttpMethod.Get, new Uri(endpoint.AbsoluteUri.TrimEnd('/') + "/" + batch.ToString("D")), digest, null, token); private async Task SendAsync(HttpMethod method, Uri uri, string digest, PurchaseHandoffPackage? package, CancellationToken token) { using var deadline = CancellationTokenSource.CreateLinkedTokenSource(token); deadline.CancelAfter(TimeSpan.FromSeconds(30)); using var request = new HttpRequestMessage(method, uri); request.Headers.Add(PurchaseDispatchProof.DigestHeader, digest); request.Headers.Add(PurchaseDispatchProof.ProofHeader, Convert.ToBase64String(PurchaseDispatchProof.Sign(key, method.Method, uri.AbsolutePath, digest))); if (package is not null) request.Content = JsonContent.Create(package, options: JsonSerializerOptions.Web); try { using var response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, deadline.Token); if (method == HttpMethod.Get && response.StatusCode is HttpStatusCode.NotFound or HttpStatusCode.PreconditionFailed) return null; if (!response.IsSuccessStatusCode) { var retry = response.StatusCode is HttpStatusCode.Unauthorized or HttpStatusCode.RequestTimeout or HttpStatusCode.TooManyRequests || (int)response.StatusCode >= 500; var code = retry ? "HANDOFF_TEMPORARY" : $"HANDOFF_HTTP_{(int)response.StatusCode}"; throw new PurchaseHandoffException(code, retry); } return await response.Content.ReadFromJsonAsync(cancellationToken: deadline.Token) ?? throw new PurchaseHandoffException("HANDOFF_INVALID_RECEIPT", true); } catch (OperationCanceledException) when (!token.IsCancellationRequested) { throw new PurchaseHandoffException("HANDOFF_TIMEOUT", true); } catch (HttpRequestException) { throw new PurchaseHandoffException("HANDOFF_UNREACHABLE", true); } catch (JsonException) { throw new PurchaseHandoffException("HANDOFF_INVALID_RECEIPT", true); } } } internal sealed class PurchaseHandoffException(string code, bool retry) : Exception(code) { public string Code { get; } = code; public bool Retry { get; } = retry; }