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
2 changes: 1 addition & 1 deletion Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>
<ItemGroup>
<PackageVersion Include="GraphQLSharp" Version="2.24.0" />
<PackageVersion Include="GraphQLSharp" Version="3.0.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.6.0" />
<PackageVersion Include="MSTest.TestAdapter" Version="2.2.10" />
<PackageVersion Include="MSTest.TestFramework" Version="2.2.10" />
Expand Down
76 changes: 76 additions & 0 deletions ShopifyNet.Tests/Interceptor/RequestAccessTokenInterceptorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
using System.Net;
using System.Net.Http.Json;
using GraphQLSharp;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ShopifyNet.Tests;

[TestClass]
public class RequestAccessTokenInterceptorTests
{
private const string ACCESS_TOKEN_HEADER = "X-Shopify-Access-Token";

/// <summary>
/// Replaces the X-Shopify-Access-Token header set by ShopifyClientOptions with ShopifyGraphQLRequest.AccessToken, when set.
/// </summary>
private class RequestAccessTokenInterceptor : IInterceptor<ShopifyGraphQLRequest, ShopifyClientOptions>
{
public Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(ShopifyGraphQLRequest request, ShopifyClientOptions options, CancellationToken cancellationToken, ExecuteRequestAsync<ShopifyGraphQLRequest, TData> executeAsync)
{
if (request.AccessToken == null)
return executeAsync(request, null, cancellationToken);

return executeAsync(request, headers =>
{
headers.Remove(ACCESS_TOKEN_HEADER);
headers.Add(ACCESS_TOKEN_HEADER, request.AccessToken);
}, cancellationToken);
}
}

private static (ShopifyClient client, List<string[]> sentTokens) CreateClient()
{
var sentTokens = new List<string[]>();
var httpClient = new TestHttpClient(msg =>
{
sentTokens.Add(msg.Headers.TryGetValues(ACCESS_TOKEN_HEADER, out var values) ? values.ToArray() : []);
return new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = JsonContent.Create(new GraphQLResponse())
};
});
var options = new ShopifyClientOptions("test.myshopify.com", "options-token")
{
Interceptor = new RequestAccessTokenInterceptor(),
HttpClient = httpClient,
};
return (new ShopifyClient(options), sentTokens);
}

[TestMethod]
public async Task ShouldReplaceOptionsAccessTokenWithRequestAccessToken()
{
var (client, sentTokens) = CreateClient();

await client.QueryAsync(new ShopifyGraphQLRequest
{
query = "query { shop { id } }",
AccessToken = "request-token",
});

Assert.AreEqual(1, sentTokens.Count);
CollectionAssert.AreEqual(new[] { "request-token" }, sentTokens[0]);
}

[TestMethod]
public async Task ShouldKeepOptionsAccessTokenWhenRequestAccessTokenIsNull()
{
var (client, sentTokens) = CreateClient();

await client.QueryAsync("query { shop { id } }");

Assert.AreEqual(1, sentTokens.Count);
CollectionAssert.AreEqual(new[] { "options-token" }, sentTokens[0]);
}
}
6 changes: 3 additions & 3 deletions ShopifyNet.Tests/TokenBucket/TestInterceptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ public TestInterceptor(IInterceptor<ShopifyGraphQLRequest, ShopifyClientOptions>
this._interceptor = interceptor;
}

public Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(ShopifyGraphQLRequest request, ShopifyClientOptions options, CancellationToken cancellationToken, Func<ShopifyGraphQLRequest, CancellationToken, Task<GraphQLResponse<TData>>> executeAsync)
public Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(ShopifyGraphQLRequest request, ShopifyClientOptions options, CancellationToken cancellationToken, ExecuteRequestAsync<ShopifyGraphQLRequest, TData> executeAsync)
{
return _interceptor.InterceptRequestAsync(request, options, cancellationToken, async (r, ct) =>
return _interceptor.InterceptRequestAsync(request, options, cancellationToken, async (r, h, ct) =>
{
CallCount++;
return await executeAsync(r, ct);
return await executeAsync(r, h, ct);
});
}
}
6 changes: 3 additions & 3 deletions ShopifyNet/Interceptor/TokenBucket/TokenBucketInterceptor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,12 @@ private void RemoveIdleBucketsAsync()
}
}

public async Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(ShopifyGraphQLRequest r, ShopifyClientOptions options, CancellationToken cancellationToken, Func<ShopifyGraphQLRequest, CancellationToken, Task<GraphQLResponse<TData>>> executeAsync)
public async Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(ShopifyGraphQLRequest r, ShopifyClientOptions options, CancellationToken cancellationToken, ExecuteRequestAsync<ShopifyGraphQLRequest, TData> executeAsync)
{
TokenBucket bucket = null;
lock (_tokenToBucket)
{
bucket = _tokenToBucket.GetOrAdd(options.AccessToken, t => new TokenBucket(DEFAULT_GRAPHQL_MAX_AVAILABLE, DEFAULT_GRAPHQL_RESTORE_RATE));
bucket = _tokenToBucket.GetOrAdd(r.AccessToken ?? options.AccessToken, t => new TokenBucket(DEFAULT_GRAPHQL_MAX_AVAILABLE, DEFAULT_GRAPHQL_RESTORE_RATE));
Comment thread
matnun-br marked this conversation as resolved.
Resolved
}

this.RemoveIdleBucketsAsync();
Expand All @@ -70,7 +70,7 @@ public async Task<GraphQLResponse<TData>> InterceptRequestAsync<TData>(ShopifyGr
try
{
//may throw GraphQLErrorsException if options.ThrowOnGraphQLErrors is true
res = await executeAsync(r, cancellationToken);
res = await executeAsync(r, null, cancellationToken);
}
catch (GraphQLErrorsException ex) when (attempt < MAX_ATTEMPTS && ex.response.IsThrottled())
{
Expand Down
10 changes: 10 additions & 0 deletions ShopifyNet/ShopifyGraphQLRequest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,16 @@ public class ShopifyGraphQLRequest : GraphQLRequest
[JsonIgnore]
public int? Cost { get; set; }

/// <summary>
/// Optional per-request access token. Not applied by ShopifyNet itself: an interceptor is expected to read it
/// and set the X-Shopify-Access-Token header through the ExecuteRequestAsync header callback.
/// Because <see cref="ShopifyClientOptions"/> already adds its own token to that header, the callback must call
/// <c>headers.Remove("X-Shopify-Access-Token")</c> before adding this one, otherwise both values are sent.
/// When set, <see cref="TokenBucketInterceptor"/> uses it to select the rate-limit bucket.
/// </summary>
[JsonIgnore]
public string AccessToken { get; set; }

public static implicit operator ShopifyGraphQLRequest(string query)
{
return new ShopifyGraphQLRequest
Expand Down
2 changes: 1 addition & 1 deletion ShopifyNet/ShopifyNet.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<PackageProjectUrl>https://github.com/Wish-Org/ShopifyNet</PackageProjectUrl>
<RepositoryUrl>https://github.com/Wish-Org/ShopifyNet</RepositoryUrl>
<Description>.NET utilities for Shopify GraphQL</Description>
<Version>2.22.0</Version>
<Version>3.0.0</Version>
<PackageTags>shopify graphql types classes schema generator strongly typed</PackageTags>

<!-- Ensure the XML doc file is generated -->
Expand Down
Loading