diff --git a/GraphQLSharp.Tests/ChainedInterceptorTests.cs b/GraphQLSharp.Tests/ChainedInterceptorTests.cs index a857e5d..2c095f2 100644 --- a/GraphQLSharp.Tests/ChainedInterceptorTests.cs +++ b/GraphQLSharp.Tests/ChainedInterceptorTests.cs @@ -1,4 +1,5 @@ using System.Net; +using System.Net.Http.Headers; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace GraphQLSharp.Tests; @@ -6,6 +7,49 @@ namespace GraphQLSharp.Tests; [TestClass] public class ChainedInterceptorTests { + [DataTestMethod] + [DataRow(false)] + [DataRow(true)] + public async Task PreserveHeaderCallbacksOnEveryAttempt(bool retry) + { + var attempts = new List(); + var options = new GraphQLClientOptions(new Uri("https://example.com/graphql")) + { + ConfigureHttpRequestHeaders = headers => headers.Add("X-Order", "options"), + Interceptor = new ChainedInterceptor( + new HeaderInterceptor(headers => headers.Add("X-Order", "inner")), + new HeaderInterceptor(headers => headers.Add("X-Order", "middle")), + new RetryInterceptor(), + new HeaderInterceptor(headers => headers.Add("X-Order", "outer"))), + HttpClient = new TestHttpClient(msg => + { + attempts.Add(msg.Headers.GetValues("X-Order").ToArray()); + return new HttpResponseMessage(retry && attempts.Count == 1 + ? HttpStatusCode.ServiceUnavailable : HttpStatusCode.OK) + { + Content = new StringContent("""{"data":{}}""") + }; + }) + }; + + await new GraphQLCLient(options).ExecuteAsync("{ shop { id } }"); + + Assert.AreEqual(retry ? 2 : 1, attempts.Count); + foreach (var headers in attempts) + CollectionAssert.AreEqual(new[] { "options", "outer", "middle", "inner" }, headers); + } + + private sealed class HeaderInterceptor(Action configureHeaders) + : IInterceptor + { + public Task> InterceptRequestAsync(GraphQLRequest request, + GraphQLClientOptions options, CancellationToken cancellationToken, + ExecuteRequestAsync executeAsync) + { + return executeAsync(request, configureHeaders, cancellationToken); + } + } + [TestMethod] public async Task CallInterceptorsInCorrectOrder() { @@ -42,4 +86,4 @@ public async Task CallInterceptorsInCorrectOrder() "After1", "After2", "After3" ])); } -} \ No newline at end of file +} diff --git a/GraphQLSharp.Tests/TestInterceptor.cs b/GraphQLSharp.Tests/TestInterceptor.cs index 1e88265..3c533dd 100644 --- a/GraphQLSharp.Tests/TestInterceptor.cs +++ b/GraphQLSharp.Tests/TestInterceptor.cs @@ -11,10 +11,10 @@ public TestInterceptor(Action onBeforeExecute, Action onAfterExecute) _onAfterExecute = onAfterExecute; } - public async Task> InterceptRequestAsync(GraphQLRequest request, GraphQLClientOptions options, CancellationToken cancellationToken, Func>> executeAsync) + public async Task> InterceptRequestAsync(GraphQLRequest request, GraphQLClientOptions options, CancellationToken cancellationToken, ExecuteRequestAsync executeAsync) { _onBeforeExecute?.Invoke(); - var response = await executeAsync(request, cancellationToken); + var response = await executeAsync(request, null, cancellationToken); _onAfterExecute?.Invoke(); return response; } diff --git a/GraphQLSharp/Client/GraphQLClient.cs b/GraphQLSharp/Client/GraphQLClient.cs index 310c194..1039d6d 100644 --- a/GraphQLSharp/Client/GraphQLClient.cs +++ b/GraphQLSharp/Client/GraphQLClient.cs @@ -86,13 +86,13 @@ public async Task> ExecuteAsync(TRequest request, Cancella } } - private async Task> ExecuteCoreAsync(TRequest request, CancellationToken cancellationToken = default) + private async Task> ExecuteCoreAsync(TRequest request, Action configureHttpRequestHeaders, CancellationToken cancellationToken = default) { HttpResponse httpResponse = null; try { var httpClient = _options.HttpClient ?? _defaultHttpClient; - using HttpRequestMessage requestMessage = CreateHttpRequest(request, httpClient); + using HttpRequestMessage requestMessage = CreateHttpRequest(request, httpClient, configureHttpRequestHeaders); using var httpResponseMsg = await httpClient.SendAsync(requestMessage, cancellationToken); //httpResponseMsg needs to disposed so we create a small copy of basic information httpResponse = new HttpResponse(httpResponseMsg); @@ -172,7 +172,7 @@ private async Task> ExecuteCoreAsync(TRequest request, Can } } - private HttpRequestMessage CreateHttpRequest(TRequest request, HttpClient httpClient) + private HttpRequestMessage CreateHttpRequest(TRequest request, HttpClient httpClient, Action configureHttpRequestHeaders) { _ = request.query ?? throw new ArgumentNullException(nameof(request.query)); var uri = _options.Uri ?? throw new ArgumentNullException($"{nameof(IGraphQLClientOptions.Uri)} must a non-null URI."); @@ -187,6 +187,7 @@ private HttpRequestMessage CreateHttpRequest(TRequest request, HttpClient httpCl requestMessage.Headers.UserAgent.Add(_defaultUserAgent); _options.ConfigureHttpRequestHeaders?.Invoke(requestMessage.Headers); + configureHttpRequestHeaders?.Invoke(requestMessage.Headers); return requestMessage; } } \ No newline at end of file diff --git a/GraphQLSharp/Client/Interception/ChainedInterceptor.cs b/GraphQLSharp/Client/Interception/ChainedInterceptor.cs index 9f5660c..7e6b838 100644 --- a/GraphQLSharp/Client/Interception/ChainedInterceptor.cs +++ b/GraphQLSharp/Client/Interception/ChainedInterceptor.cs @@ -11,23 +11,33 @@ public class ChainedInterceptor : IInterceptor class with the specified interceptors. /// /// - /// An array of interceptors to chain together. - /// The first interceptor in the array will be executed first (inner most), followed by the second, and so on. + /// An array of interceptors to chain together, from innermost to outermost. + /// The first interceptor is the innermost (closest to the HTTP call) and the last is the outermost. + /// For interceptors [A, B, C], a request runs C, then B, then A, then the HTTP call, and the + /// response returns through A, then B, then C. + /// Header callbacks are applied in the order the request flows: C's first, then B's, then A's, + /// so an inner interceptor's headers are applied after (and can override) an outer one's. /// public ChainedInterceptor(params IInterceptor[] interceptors) { this._interceptors = interceptors; } - public async Task> InterceptRequestAsync(TRequest request, TOptions options, CancellationToken cancellationToken, Func>> executeAsync) + public async Task> InterceptRequestAsync(TRequest request, TOptions options, CancellationToken cancellationToken, ExecuteRequestAsync executeAsync) { foreach (var interceptor in _interceptors) { var capturedInterceptor = interceptor; var capturedExecuteAsync = executeAsync; - executeAsync = (req, ct) => capturedInterceptor.InterceptRequestAsync(req, options, ct, capturedExecuteAsync); + executeAsync = (req, configureHttpRequestHeaders, ct) => capturedInterceptor.InterceptRequestAsync(req, options, ct, + (innerRequest, configureInnerHttpRequestHeaders, innerCancellationToken) => capturedExecuteAsync(innerRequest, headers => + { + // Apply callbacks in request order, from outermost to innermost. + configureHttpRequestHeaders?.Invoke(headers); + configureInnerHttpRequestHeaders?.Invoke(headers); + }, innerCancellationToken)); } - return await executeAsync(request, cancellationToken); + return await executeAsync(request, null, cancellationToken); } } diff --git a/GraphQLSharp/Client/Interception/IInterceptor.cs b/GraphQLSharp/Client/Interception/IInterceptor.cs index 4e930c1..5e0d835 100644 --- a/GraphQLSharp/Client/Interception/IInterceptor.cs +++ b/GraphQLSharp/Client/Interception/IInterceptor.cs @@ -1,5 +1,13 @@ +using System.Net.Http.Headers; + namespace GraphQLSharp; +/// +/// Executes the next step of the request pipeline. +/// configureHttpRequestHeaders is optional and may be null. +/// +public delegate Task> ExecuteRequestAsync(TRequest request, Action configureHttpRequestHeaders, CancellationToken cancellationToken); + /// /// Interface for intercepting GraphQL requests. /// Allows for custom processing of requests before they are sent and responses after they are received. @@ -12,7 +20,7 @@ public interface IInterceptor : IInterceptor Task> InterceptRequestAsync(TRequest request, TOptions options, CancellationToken cancellationToken, - Func>> executeAsync); + ExecuteRequestAsync executeAsync); } public interface IInterceptor diff --git a/GraphQLSharp/Client/Interception/NoOpInterceptor.cs b/GraphQLSharp/Client/Interception/NoOpInterceptor.cs index be07c6c..fa0ad54 100644 --- a/GraphQLSharp/Client/Interception/NoOpInterceptor.cs +++ b/GraphQLSharp/Client/Interception/NoOpInterceptor.cs @@ -8,8 +8,8 @@ public class NoOpInterceptor : IInterceptor> InterceptRequestAsync(TRequest request, TOptions options, CancellationToken cancellationToken, Func>> executeAsync) + public Task> InterceptRequestAsync(TRequest request, TOptions options, CancellationToken cancellationToken, ExecuteRequestAsync executeAsync) { - return executeAsync(request, cancellationToken); + return executeAsync(request, null, cancellationToken); } } \ No newline at end of file diff --git a/GraphQLSharp/Client/Interception/RetryInterceptor.cs b/GraphQLSharp/Client/Interception/RetryInterceptor.cs index 3c65ca1..17f5475 100644 --- a/GraphQLSharp/Client/Interception/RetryInterceptor.cs +++ b/GraphQLSharp/Client/Interception/RetryInterceptor.cs @@ -24,7 +24,7 @@ protected virtual bool ShouldRetry(HttpResponse r) return _retryableStatusCodes.Contains(r.StatusCode); } - public async Task> InterceptRequestAsync(TRequest request, TOptions options, CancellationToken cancellationToken, Func>> executeAsync) + public async Task> InterceptRequestAsync(TRequest request, TOptions options, CancellationToken cancellationToken, ExecuteRequestAsync executeAsync) { int tryCount = 0; @@ -32,7 +32,7 @@ public async Task> InterceptRequestAsync(TRequest { try { - return await executeAsync(request, cancellationToken); + return await executeAsync(request, null, cancellationToken); } catch (GraphQLHttpException ex) when (ShouldRetry(ex.HttpResponse) && ++tryCount < MAX_TRIES) { diff --git a/GraphQLSharp/GraphQLSharp.csproj b/GraphQLSharp/GraphQLSharp.csproj index 850abf9..518c7e1 100644 --- a/GraphQLSharp/GraphQLSharp.csproj +++ b/GraphQLSharp/GraphQLSharp.csproj @@ -4,7 +4,7 @@ https://github.com/Wish-Org/GraphQLSharp https://github.com/Wish-Org/GraphQLSharp .NET Client for GraphQL - Modern and fast - 2.24.0 + 3.0.0 graphql;client;graphql-client;graphql-generator Wish-Org README.md