Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 45 additions & 1 deletion GraphQLSharp.Tests/ChainedInterceptorTests.cs
Original file line number Diff line number Diff line change
@@ -1,11 +1,55 @@
using System.Net;
using System.Net.Http.Headers;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace GraphQLSharp.Tests;

[TestClass]
public class ChainedInterceptorTests
{
[DataTestMethod]
[DataRow(false)]
[DataRow(true)]
public async Task PreserveHeaderCallbacksOnEveryAttempt(bool retry)
{
var attempts = new List<string[]>();
var options = new GraphQLClientOptions(new Uri("https://example.com/graphql"))
{
ConfigureHttpRequestHeaders = headers => headers.Add("X-Order", "options"),
Interceptor = new ChainedInterceptor<GraphQLRequest, GraphQLClientOptions>(
new HeaderInterceptor(headers => headers.Add("X-Order", "inner")),
new HeaderInterceptor(headers => headers.Add("X-Order", "middle")),
new RetryInterceptor<GraphQLRequest, GraphQLClientOptions>(),
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<HttpRequestHeaders> configureHeaders)
: IInterceptor<GraphQLRequest, GraphQLClientOptions>
{
public Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(GraphQLRequest request,
GraphQLClientOptions options, CancellationToken cancellationToken,
ExecuteRequestAsync<GraphQLRequest, TData> executeAsync)
{
return executeAsync(request, configureHeaders, cancellationToken);
}
}

[TestMethod]
public async Task CallInterceptorsInCorrectOrder()
{
Expand Down Expand Up @@ -42,4 +86,4 @@ public async Task CallInterceptorsInCorrectOrder()
"After1", "After2", "After3"
]));
}
}
}
4 changes: 2 additions & 2 deletions GraphQLSharp.Tests/TestInterceptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@ public TestInterceptor(Action onBeforeExecute, Action onAfterExecute)
_onAfterExecute = onAfterExecute;
}

public async Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(GraphQLRequest request, GraphQLClientOptions options, CancellationToken cancellationToken, Func<GraphQLRequest, CancellationToken, Task<GraphQLResponse<TData>>> executeAsync)
public async Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(GraphQLRequest request, GraphQLClientOptions options, CancellationToken cancellationToken, ExecuteRequestAsync<GraphQLRequest, TData> executeAsync)
{
_onBeforeExecute?.Invoke();
var response = await executeAsync(request, cancellationToken);
var response = await executeAsync(request, null, cancellationToken);
_onAfterExecute?.Invoke();
return response;
}
Expand Down
7 changes: 4 additions & 3 deletions GraphQLSharp/Client/GraphQLClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -86,13 +86,13 @@ public async Task<GraphQLResponse<T>> ExecuteAsync<T>(TRequest request, Cancella
}
}

private async Task<GraphQLResponse<T>> ExecuteCoreAsync<T>(TRequest request, CancellationToken cancellationToken = default)
private async Task<GraphQLResponse<T>> ExecuteCoreAsync<T>(TRequest request, Action<HttpRequestHeaders> 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);
Expand Down Expand Up @@ -172,7 +172,7 @@ private async Task<GraphQLResponse<T>> ExecuteCoreAsync<T>(TRequest request, Can
}
}

private HttpRequestMessage CreateHttpRequest(TRequest request, HttpClient httpClient)
private HttpRequestMessage CreateHttpRequest(TRequest request, HttpClient httpClient, Action<HttpRequestHeaders> configureHttpRequestHeaders)
{
_ = request.query ?? throw new ArgumentNullException(nameof(request.query));
var uri = _options.Uri ?? throw new ArgumentNullException($"{nameof(IGraphQLClientOptions<TOptions, TRequest>.Uri)} must a non-null URI.");
Expand All @@ -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;
}
}
20 changes: 15 additions & 5 deletions GraphQLSharp/Client/Interception/ChainedInterceptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,33 @@ public class ChainedInterceptor<TRequest, TOptions> : IInterceptor<TRequest, TOp
/// Initializes a new instance of the <see cref="ChainedInterceptor{TRequest, TOptions}"/> class with the specified interceptors.
/// </summary>
/// <param name="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.
/// </param>
public ChainedInterceptor(params IInterceptor<TRequest, TOptions>[] interceptors)
{
this._interceptors = interceptors;
}

public async Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(TRequest request, TOptions options, CancellationToken cancellationToken, Func<TRequest, CancellationToken, Task<GraphQLResponse<TData>>> executeAsync)
public async Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(TRequest request, TOptions options, CancellationToken cancellationToken, ExecuteRequestAsync<TRequest, TData> 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);
}
}
10 changes: 9 additions & 1 deletion GraphQLSharp/Client/Interception/IInterceptor.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
using System.Net.Http.Headers;

namespace GraphQLSharp;

/// <summary>
/// Executes the next step of the request pipeline.
/// configureHttpRequestHeaders is optional and may be null.
/// </summary>
public delegate Task<GraphQLResponse<TData>> ExecuteRequestAsync<TRequest, TData>(TRequest request, Action<HttpRequestHeaders> configureHttpRequestHeaders, CancellationToken cancellationToken);

/// <summary>
/// Interface for intercepting GraphQL requests.
/// Allows for custom processing of requests before they are sent and responses after they are received.
Expand All @@ -12,7 +20,7 @@ public interface IInterceptor<TRequest, TOptions> : IInterceptor
Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(TRequest request,
TOptions options,
CancellationToken cancellationToken,
Func<TRequest, CancellationToken, Task<GraphQLResponse<TData>>> executeAsync);
ExecuteRequestAsync<TRequest, TData> executeAsync);
}

public interface IInterceptor
Expand Down
4 changes: 2 additions & 2 deletions GraphQLSharp/Client/Interception/NoOpInterceptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ public class NoOpInterceptor<TRequest, TOptions> : IInterceptor<TRequest, TOptio

private NoOpInterceptor() { }

public Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(TRequest request, TOptions options, CancellationToken cancellationToken, Func<TRequest, CancellationToken, Task<GraphQLResponse<TData>>> executeAsync)
public Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(TRequest request, TOptions options, CancellationToken cancellationToken, ExecuteRequestAsync<TRequest, TData> executeAsync)
{
return executeAsync(request, cancellationToken);
return executeAsync(request, null, cancellationToken);
}
}
4 changes: 2 additions & 2 deletions GraphQLSharp/Client/Interception/RetryInterceptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,15 @@ protected virtual bool ShouldRetry(HttpResponse r)
return _retryableStatusCodes.Contains(r.StatusCode);
}

public async Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(TRequest request, TOptions options, CancellationToken cancellationToken, Func<TRequest, CancellationToken, Task<GraphQLResponse<TData>>> executeAsync)
public async Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(TRequest request, TOptions options, CancellationToken cancellationToken, ExecuteRequestAsync<TRequest, TData> executeAsync)
{
int tryCount = 0;

while (true)
{
try
{
return await executeAsync(request, cancellationToken);
return await executeAsync(request, null, cancellationToken);
}
catch (GraphQLHttpException ex) when (ShouldRetry(ex.HttpResponse) && ++tryCount < MAX_TRIES)
{
Expand Down
2 changes: 1 addition & 1 deletion GraphQLSharp/GraphQLSharp.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<PackageProjectUrl>https://github.com/Wish-Org/GraphQLSharp</PackageProjectUrl>
<RepositoryUrl>https://github.com/Wish-Org/GraphQLSharp</RepositoryUrl>
<Description>.NET Client for GraphQL - Modern and fast</Description>
<Version>2.24.0</Version>
<Version>3.0.0</Version>
<PackageTags>graphql;client;graphql-client;graphql-generator</PackageTags>
<Authors>Wish-Org</Authors>
<PackageReadmeFile>README.md</PackageReadmeFile>
Expand Down
Loading