Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed Complexity Middleware #1137

Merged
merged 3 commits into from
Oct 16, 2019
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
3 changes: 2 additions & 1 deletion examples/AspNetCore.StarWars/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,8 @@ public void ConfigureServices(IServiceCollection services)
.Create(),
new QueryExecutionOptions
{
TracingPreference = TracingPreference.Always
MaxOperationComplexity = 10,
UseComplexityMultipliers = true
});


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ChilliCream.Testing;
using HotChocolate.Execution.Configuration;
using HotChocolate.Language;
using HotChocolate.Utilities;
Expand Down Expand Up @@ -368,5 +367,91 @@ input FooInput {
new SnapshotNameExtension("complexity", count));
}
}

[Fact]
public async Task Validate_Multiple_Levels_Valid()
{
// arrange
ISchema schema = SchemaBuilder.New()
.AddDocumentFromString(
@"
type Query {
foo(i: Int = 2): Foo
@cost(complexity: 1 multipliers: [""i""])
}

type Foo {
bar: Bar
qux: String
}

type Bar {
baz: String
}
")
.Use(next => context =>
{
context.Result = "baz";
return Task.CompletedTask;
})
.Create();

IQueryExecutor executor = schema.MakeExecutable(new QueryExecutionOptions
{
UseComplexityMultipliers = true,
MaxOperationComplexity = 4
});

IReadOnlyQueryRequest request = QueryRequestBuilder.New()
.SetQuery("query { foo { bar { baz } } }")
.Create();

IExecutionResult result = await executor.ExecuteAsync(request);

result.MatchSnapshot();
}

[Fact]
public async Task Validate_Multiple_Levels_Invalid()
{
// arrange
ISchema schema = SchemaBuilder.New()
.AddDocumentFromString(
@"
type Query {
foo(i: Int = 2): Foo
@cost(complexity: 1 multipliers: [""i""])
}

type Foo {
bar: Bar
qux: String
}

type Bar {
baz: String
}
")
.Use(next => context =>
{
context.Result = "baz";
return Task.CompletedTask;
})
.Create();

IQueryExecutor executor = schema.MakeExecutable(new QueryExecutionOptions
{
UseComplexityMultipliers = true,
MaxOperationComplexity = 4
});

IReadOnlyQueryRequest request = QueryRequestBuilder.New()
.SetQuery("query { foo(i: 2) { bar { baz } qux } }")
.Create();

IExecutionResult result = await executor.ExecuteAsync(request);

result.MatchSnapshot();
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"Data": {},
"Extensions": {},
"Errors": [
{
"Message": "The operation that shall be executed has a complexity of 5.\nThe maximum allowed query complexity is 4.",
"Code": null,
"Path": null,
"Locations": [
{
"Line": 1,
"Column": 1
}
],
"Exception": null,
"Extensions": {}
}
],
"ContextData": {}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"Data": {
"foo": {
"bar": {
"baz": "baz"
}
}
},
"Extensions": {},
"Errors": [],
"ContextData": {}
}
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,7 @@ public Task InvokeAsync(IQueryContext context)
IError error = ErrorBuilder.New()
.SetMessage(string.Format(
CultureInfo.InvariantCulture,
CoreResources
.MaxComplexityMiddleware_NotAllowed,
CoreResources.MaxComplexityMiddleware_NotAllowed,
complexity,
_options.MaxOperationComplexity))
.AddLocation(context.Operation.Definition)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,20 +51,19 @@ public override MaxComplexityVisitorContext AddField(
{
IDirective directive = fieldDefinition.Directives
.FirstOrDefault(t => t.Type is CostDirectiveType);
int complexity;

CostDirective cost = directive == null
? DefaultCost
: directive.ToObject<CostDirective>();

complexity = Complexity + CalculateComplexity(
Complexity = Complexity + CalculateComplexity(
new ComplexityContext(
fieldDefinition, fieldSelection,
FieldPath, _variables, cost));

if (complexity > MaxComplexity)
if (Complexity > MaxComplexity)
{
MaxComplexity = complexity;
MaxComplexity = Complexity;
}

return new MaxComplexityWithMultipliersVisitorContext(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,8 @@
<ProjectReference Include="..\Core\Core.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Squadron.Redis" Version="0.3.0" />
</ItemGroup>

</Project>
25 changes: 4 additions & 21 deletions src/Core/PersistedQueries.Redis.Tests/RedisQueryStorageTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,36 +8,19 @@
using Snapshooter.Xunit;
using Xunit;
using Snapshooter;
using Squadron;

namespace HotChocolate.PersistedQueries.Redis
{
public class RedisQueryStorageTests
: IClassFixture<RedisResource>
{
private ConnectionMultiplexer _connectionMultiplexer;
private IDatabase _database;

public RedisQueryStorageTests()
public RedisQueryStorageTests(RedisResource redisResource)
{
string endpoint =
Environment.GetEnvironmentVariable("REDIS_ENDPOINT")
?? "localhost:6379";

string password =
Environment.GetEnvironmentVariable("REDIS_PASSWORD");

var configuration = new ConfigurationOptions
{
Ssl = !string.IsNullOrEmpty(password),
AbortOnConnectFail = false,
Password = password
};

configuration.EndPoints.Add(endpoint);

_connectionMultiplexer =
ConnectionMultiplexer.Connect(configuration);

_database = _connectionMultiplexer.GetDatabase();
_database = redisResource.GetConnection().GetDatabase();
}

[Fact]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,36 +5,19 @@
using Xunit;
using HotChocolate.Utilities;
using Snapshooter.Xunit;
using Squadron;

namespace HotChocolate.PersistedQueries.Redis
{
public class ServiceCollectionExtensionsTests
: IClassFixture<RedisResource>
{
private ConnectionMultiplexer _connectionMultiplexer;
private IDatabase _database;

public ServiceCollectionExtensionsTests()
public ServiceCollectionExtensionsTests(RedisResource redisResource)
{
string endpoint =
Environment.GetEnvironmentVariable("REDIS_ENDPOINT")
?? "localhost:6379";

string password =
Environment.GetEnvironmentVariable("REDIS_PASSWORD");

var configuration = new ConfigurationOptions
{
Ssl = !string.IsNullOrEmpty(password),
AbortOnConnectFail = false,
Password = password
};

configuration.EndPoints.Add(endpoint);

_connectionMultiplexer =
ConnectionMultiplexer.Connect(configuration);

_database = _connectionMultiplexer.GetDatabase();
_database = redisResource.GetConnection().GetDatabase();
}

[Fact]
Expand Down
33 changes: 9 additions & 24 deletions src/Core/Subscriptions.Redis.Tests/RedisIntegrationTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,37 +8,22 @@
using HotChocolate.Types;
using HotChocolate.Execution;
using HotChocolate.Language;
using Squadron;

namespace HotChocolate.Subscriptions.Redis
{
public class RedisIntegrationTests
: IClassFixture<RedisResource>
{
private readonly ConnectionMultiplexer _connection;
private readonly IEventSender _sender;
private readonly ConfigurationOptions _configuration;

public RedisIntegrationTests()
public RedisIntegrationTests(RedisResource redisResource)
{
string endpoint =
Environment.GetEnvironmentVariable("REDIS_ENDPOINT")
?? "localhost:6379";

string password =
Environment.GetEnvironmentVariable("REDIS_PASSWORD");

_configuration = new ConfigurationOptions
{
Ssl = !string.IsNullOrEmpty(password),
AbortOnConnectFail = false,
Password = password
};

_configuration.EndPoints.Add(endpoint);

var redisEventRegistry = new RedisEventRegistry(
ConnectionMultiplexer.Connect(_configuration),
_connection = redisResource.GetConnection();
_sender = new RedisEventRegistry(
_connection,
new JsonPayloadSerializer());

_sender = redisEventRegistry;
}

[Fact]
Expand All @@ -48,7 +33,7 @@ public Task Subscribe()
{
// arrange
var services = new ServiceCollection();
services.AddRedisSubscriptionProvider(_configuration);
services.AddRedisSubscriptionProvider(_connection);

IServiceProvider serviceProvider = services.BuildServiceProvider();

Expand Down Expand Up @@ -90,7 +75,7 @@ public Task Subscribe_With_ObjectValue()
{
// arrange
var services = new ServiceCollection();
services.AddRedisSubscriptionProvider(_configuration);
services.AddRedisSubscriptionProvider(_connection);

IServiceProvider serviceProvider = services.BuildServiceProvider();

Expand Down
22 changes: 4 additions & 18 deletions src/Core/Subscriptions.Redis.Tests/RedisTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,36 +2,22 @@
using System.Threading;
using System.Threading.Tasks;
using HotChocolate.Language;
using Squadron;
using StackExchange.Redis;
using Xunit;

namespace HotChocolate.Subscriptions.Redis
{
public class RedisTests
: IClassFixture<RedisResource>
{
private readonly IEventRegistry _registry;
private readonly IEventSender _sender;

public RedisTests()
public RedisTests(RedisResource redisResource)
{
string endpoint =
Environment.GetEnvironmentVariable("REDIS_ENDPOINT")
?? "localhost:6379";

string password =
Environment.GetEnvironmentVariable("REDIS_PASSWORD");

var configuration = new ConfigurationOptions
{
Ssl = !string.IsNullOrEmpty(password),
AbortOnConnectFail = false,
Password = password
};

configuration.EndPoints.Add(endpoint);

var redisEventRegistry = new RedisEventRegistry(
ConnectionMultiplexer.Connect(configuration),
redisResource.GetConnection(),
new JsonPayloadSerializer());

_sender = redisEventRegistry;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,8 @@
<ProjectReference Include="..\Subscriptions.InMemory\Subscriptions.InMemory.csproj" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Squadron.Redis" Version="0.3.0" />
</ItemGroup>

</Project>
Loading