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 QueryResult creation in QueryCacheMiddleware #7441

Merged
merged 2 commits into from
Sep 6, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ public static ValueTask<IRequestExecutor> CreateExceptionExecutor(
{
context.Result =
OperationResultBuilder
.FromResult(context.Result!.ExpectQueryResult())
.FromResult(context.Result!.ExpectSingleResult())
.SetContextData("ex", queryString)
.Build();
}
Expand Down
4 changes: 4 additions & 0 deletions src/Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
<PackageVersion Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.ObjectPool" Version="8.0.0" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="8.0.0" />
<PackageVersion Include="Microsoft.Net.Http.Headers" Version="8.0.4" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="8.0.0" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite" Version="8.0.0" />
<PackageVersion Include="System.Diagnostics.DiagnosticSource" Version="8.0.0" />
Expand All @@ -105,6 +106,7 @@
<PackageVersion Include="Microsoft.Extensions.Http" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.ObjectPool" Version="7.0.0" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="7.0.0" />
<PackageVersion Include="Microsoft.Net.Http.Headers" Version="2.2.0" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="7.0.0" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite" Version="7.0.0" />
<PackageVersion Include="System.Diagnostics.DiagnosticSource" Version="7.0.0" />
Expand All @@ -127,6 +129,7 @@
<PackageVersion Include="Microsoft.Extensions.Http" Version="6.0.0" />
<PackageVersion Include="Microsoft.Extensions.ObjectPool" Version="6.0.0" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="6.0.0" />
<PackageVersion Include="Microsoft.Net.Http.Headers" Version="2.2.0" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="6.0.0" />
<PackageVersion Include="Npgsql.EntityFrameworkCore.PostgreSQL.NetTopologySuite" Version="6.0.0" />
<PackageVersion Include="System.Diagnostics.DiagnosticSource" Version="6.0.0" />
Expand All @@ -143,6 +146,7 @@
<PackageVersion Include="Microsoft.Extensions.Http" Version="6.0.0" />
<PackageVersion Include="Microsoft.Extensions.ObjectPool" Version="6.0.0" />
<PackageVersion Include="Microsoft.Extensions.Options" Version="6.0.0" />
<PackageVersion Include="Microsoft.Net.Http.Headers" Version="2.2.0" />
<PackageVersion Include="System.Diagnostics.DiagnosticSource" Version="6.0.0" />
<PackageVersion Include="System.IO.Pipelines" Version="6.0.0" />
<PackageVersion Include="System.Net.Http.Json" Version="6.0.0" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using HotChocolate.Execution.Serialization;
using HotChocolate.Utilities;
using Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
#if !NET6_0_OR_GREATER
using Microsoft.Net.Http.Headers;
#endif
Expand Down Expand Up @@ -180,10 +181,10 @@ public async ValueTask FormatAsync(
response.StatusCode = statusCode;

if (result.ContextData is not null
&& result.ContextData.TryGetValue(CacheControlHeaderValue, out var value)
&& value is string cacheControlHeaderValue)
&& result.ContextData.TryGetValue(WellKnownContextData.CacheControlHeaderValue, out var value)
&& value is CacheControlHeaderValue cacheControlHeaderValue)
{
response.Headers.CacheControl = cacheControlHeaderValue;
response.GetTypedHeaders().CacheControl = cacheControlHeaderValue;
}

OnWriteResponseHeaders(operationResult, format, response.Headers);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using HotChocolate.Types;
using HotChocolate.Types.Introspection;
using HotChocolate.Utilities;
using Microsoft.Net.Http.Headers;
using IHasDirectives = HotChocolate.Types.IHasDirectives;

namespace HotChocolate.Caching;
Expand All @@ -13,10 +14,6 @@ namespace HotChocolate.Caching;
/// </summary>
internal sealed class CacheControlConstraintsOptimizer : IOperationOptimizer
{
private const string _cacheControlValueTemplate = "{0}, max-age={1}";
private const string _cacheControlPrivateScope = "private";
private const string _cacheControlPublicScope = "public";

public void OptimizeOperation(OperationOptimizerContext context)
{
if (context.Definition.Operation is not OperationType.Query ||
Expand All @@ -31,18 +28,12 @@ public void OptimizeOperation(OperationOptimizerContext context)

if (constraints.MaxAge is not null)
{
var cacheType = constraints.Scope switch
var headerValue = new CacheControlHeaderValue
{
CacheControlScope.Private => _cacheControlPrivateScope,
CacheControlScope.Public => _cacheControlPublicScope,
_ => throw ThrowHelper.UnexpectedCacheControlScopeValue(constraints.Scope),
Private = constraints.Scope == CacheControlScope.Private,
MaxAge = TimeSpan.FromSeconds(constraints.MaxAge.Value),
};

var headerValue = string.Format(
_cacheControlValueTemplate,
cacheType,
constraints.MaxAge);

context.ContextData.Add(
WellKnownContextData.CacheControlConstraints,
new ImmutableCacheConstraints(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@
<InternalsVisibleTo Include="HotChocolate.Caching.Http.Tests" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Net.Http.Headers" />
</ItemGroup>

<ItemGroup>
<Compile Update="Properties\CacheControlResources.Designer.cs">
<DesignTime>True</DesignTime>
Expand Down
30 changes: 11 additions & 19 deletions src/HotChocolate/Caching/src/Caching/QueryCacheMiddleware.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using HotChocolate.Execution;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using static HotChocolate.WellKnownContextData;

namespace HotChocolate.Caching;
Expand Down Expand Up @@ -28,34 +29,25 @@ public async ValueTask InvokeAsync(IRequestContext context)
return;
}

if (context.Operation?.ContextData is null ||
!context.Operation.ContextData.TryGetValue(CacheControlHeaderValue, out var value) ||
value is not string cacheControlHeaderValue)
if (context.Operation?.ContextData is null
|| !context.Operation.ContextData.TryGetValue(WellKnownContextData.CacheControlHeaderValue, out var value)
|| value is not CacheControlHeaderValue cacheControlHeaderValue)
{
return;
}

var queryResult = context.Result?.ExpectQueryResult();
// only single operation results can be cached.
var operationResult = context.Result?.ExpectSingleResult();

if (queryResult is { Errors: null })
if (operationResult is { Errors: null })
{
var contextData =
queryResult.ContextData is not null
? new ExtensionData(queryResult.ContextData)
operationResult.ContextData is not null
? new ExtensionData(operationResult.ContextData)
: new ExtensionData();

contextData.Add(CacheControlHeaderValue, cacheControlHeaderValue);

context.Result = new OperationResult(
queryResult.Data,
queryResult.Errors,
queryResult.Extensions,
contextData,
queryResult.Items,
queryResult.Incremental,
queryResult.Label,
queryResult.Path,
queryResult.HasNext);
contextData.Add(WellKnownContextData.CacheControlHeaderValue, cacheControlHeaderValue);
context.Result = operationResult.WithContextData(contextData);
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{
"Key": "Cache-Control",
"Value": [
"public, max-age=1000"
"max-age=1000"
]
}
],
Expand All @@ -15,5 +15,5 @@
]
}
],
"Body": "{}"
"Body": "{\"data\":{\"field\":\"\"}}"
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@
]
}
],
"Body": "{}"
"Body": "{\"data\":{\"field\":\"\"}}"
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{
"Key": "Cache-Control",
"Value": [
"public, max-age=0"
"max-age=0"
]
}
],
Expand All @@ -15,5 +15,5 @@
]
}
],
"Body": "{}"
"Body": "{\"data\":{\"field\":\"\"}}"
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,5 @@
]
}
],
"Body": "{}"
"Body": "{\"data\":{\"field\":\"\"}}"
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{
"Key": "Cache-Control",
"Value": [
"public, max-age=2000"
"max-age=2000"
]
}
],
Expand All @@ -15,5 +15,5 @@
]
}
],
"Body": "{}"
"Body": "{\"data\":{\"field\":\"\"}}"
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
{
"Key": "Cache-Control",
"Value": [
"public, max-age=0"
"max-age=0"
]
}
],
Expand All @@ -15,5 +15,5 @@
]
}
],
"Body": "{}"
"Body": "{\"data\":{\"field\":\"\"}}"
}
Original file line number Diff line number Diff line change
Expand Up @@ -97,25 +97,39 @@ public static bool IsStreamResult(this IExecutionResult result)
=> result.Kind is BatchResult or DeferredResult or SubscriptionResult;

/// <summary>
/// Expect a query result.
/// Expects a single GraphQL operation result.
/// </summary>
public static IOperationResult ExpectQueryResult(this IExecutionResult result)
public static OperationResult ExpectSingleResult(this IExecutionResult result)
{
if (result is IOperationResult qr)
if (result is OperationResult qr)
{
return qr;
}

throw new ArgumentException(
ExecutionResultExtensions_ExpectQueryResult_NotQueryResult);
ExecutionResultExtensions_ExpectOperationResult_NotOperationResult);
}

/// <summary>
/// Expects a batch of operation results.
/// </summary>
public static OperationResultBatch ExpectOperationResultBatch(this IExecutionResult result)
{
if (result is OperationResultBatch qr)
{
return qr;
}

throw new ArgumentException(
ExecutionResultExtensions_ExpectOperationResultBatch_NotOperationResultBatch);
}

/// <summary>
/// Expect a stream result.
/// </summary>
public static IResponseStream ExpectResponseStream(this IExecutionResult result)
public static ResponseStream ExpectResponseStream(this IExecutionResult result)
{
if (result is IResponseStream rs)
if (result is ResponseStream rs)
{
return rs;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,32 @@ public OperationResult WithExtensions(
requestIndex: RequestIndex,
variableIndex: VariableIndex);

/// <summary>
/// Creates a new <see cref="OperationResult"/> with the specified context data.
/// </summary>
/// <param name="contextData">
/// The context data that shall be added to the result.
/// </param>
/// <returns>
/// Returns a new <see cref="OperationResult"/> that represents the result.
/// </returns>
public OperationResult WithContextData(
IReadOnlyDictionary<string, object?>? contextData)
=> new OperationResult(
data: Data,
errors: Errors,
extensions: Extensions,
contextData: contextData,
items: Items,
incremental: Incremental,
label: Label,
path: Path,
hasNext: HasNext,
cleanupTasks: CleanupTasks,
isDataSet: IsDataSet,
requestIndex: RequestIndex,
variableIndex: VariableIndex);

/// <inheritdoc />
public IReadOnlyDictionary<string, object?> ToDictionary()
=> OperationResultHelper.ToDictionary(this);
Expand Down
Loading
Loading