Skip to content

Commit

Permalink
Added ability to mark requests as warmup (#7798)
Browse files Browse the repository at this point in the history
  • Loading branch information
tobias-tengler authored Dec 3, 2024
1 parent 06da1e7 commit b669e1f
Show file tree
Hide file tree
Showing 14 changed files with 274 additions and 12 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public static IRequestExecutorBuilder UseQueryCachePipeline(
.UseDocumentValidation()
.UseOperationCache()
.UseOperationResolver()
.UseSkipWarmupExecution()
.UseOperationVariableCoercion()
.UseOperationExecution();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,9 @@ public enum ExecutionResultKind
/// A subscription response stream.
/// </summary>
SubscriptionResult,

/// <summary>
/// A no-op result for warmup requests.
/// </summary>
WarmupResult,
}
Original file line number Diff line number Diff line change
Expand Up @@ -74,4 +74,11 @@ public static OperationRequestBuilder SetUser(
this OperationRequestBuilder builder,
ClaimsPrincipal claimsPrincipal)
=> builder.SetGlobalState(nameof(ClaimsPrincipal), claimsPrincipal);

/// <summary>
/// Marks this request as a warmup request that will bypass security measures and skip execution.
/// </summary>
public static OperationRequestBuilder MarkAsWarmupRequest(
this OperationRequestBuilder builder)
=> builder.SetGlobalState(WellKnownContextData.IsWarmupRequest, true);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
namespace HotChocolate.Execution;

public sealed class WarmupExecutionResult : ExecutionResult
{
public override ExecutionResultKind Kind => ExecutionResultKind.WarmupResult;

public override IReadOnlyDictionary<string, object?>? ContextData => null;
}
Original file line number Diff line number Diff line change
Expand Up @@ -328,4 +328,9 @@ public static class WellKnownContextData
/// The key to access the compiled requirements.
/// </summary>
public const string FieldRequirements = "HotChocolate.Types.ObjectField.Requirements";

/// <summary>
/// The key to determine whether the request is a warmup request.
/// </summary>
public const string IsWarmupRequest = "HotChocolate.AspNetCore.Warmup.IsWarmupRequest";
}
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,10 @@ public static IRequestExecutorBuilder UseOperationVariableCoercion(
this IRequestExecutorBuilder builder) =>
builder.UseRequest(OperationVariableCoercionMiddleware.Create());

public static IRequestExecutorBuilder UseSkipWarmupExecution(
this IRequestExecutorBuilder builder) =>
builder.UseRequest(SkipWarmupExecutionMiddleware.Create());

public static IRequestExecutorBuilder UseReadPersistedOperation(
this IRequestExecutorBuilder builder) =>
builder.UseRequest(ReadPersistedOperationMiddleware.Create());
Expand Down Expand Up @@ -191,6 +195,7 @@ public static IRequestExecutorBuilder UsePersistedOperationPipeline(
.UseDocumentValidation()
.UseOperationCache()
.UseOperationResolver()
.UseSkipWarmupExecution()
.UseOperationVariableCoercion()
.UseOperationExecution();
}
Expand All @@ -215,6 +220,7 @@ public static IRequestExecutorBuilder UseAutomaticPersistedOperationPipeline(
.UseDocumentValidation()
.UseOperationCache()
.UseOperationResolver()
.UseSkipWarmupExecution()
.UseOperationVariableCoercion()
.UseOperationExecution();
}
Expand All @@ -229,6 +235,7 @@ internal static void AddDefaultPipeline(this IList<RequestCoreMiddleware> pipeli
pipeline.Add(DocumentValidationMiddleware.Create());
pipeline.Add(OperationCacheMiddleware.Create());
pipeline.Add(OperationResolverMiddleware.Create());
pipeline.Add(SkipWarmupExecutionMiddleware.Create());
pipeline.Add(OperationVariableCoercionMiddleware.Create());
pipeline.Add(OperationExecutionMiddleware.Create());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
namespace HotChocolate.Execution;

public static class WarmupRequestExecutorExtensions
{
public static bool IsWarmupRequest(this IRequestContext requestContext)
=> requestContext.ContextData.ContainsKey(WellKnownContextData.IsWarmupRequest);
}
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@ private OnlyPersistedOperationsAllowedMiddleware(

public ValueTask InvokeAsync(IRequestContext context)
{
// if all operations are allowed we can skip this middleware.
if(!_options.OnlyAllowPersistedDocuments)
// if all operations are allowed or the request is a warmup request, we can skip this middleware.
if(!_options.OnlyAllowPersistedDocuments || context.IsWarmupRequest())
{
return _next(context);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
namespace HotChocolate.Execution.Pipeline;

internal sealed class SkipWarmupExecutionMiddleware(RequestDelegate next)
{
public async ValueTask InvokeAsync(IRequestContext context)
{
if (context.IsWarmupRequest())
{
context.Result = new WarmupExecutionResult();
return;
}

await next(context).ConfigureAwait(false);
}

public static RequestCoreMiddleware Create()
=> (_, next) =>
{
var middleware = new SkipWarmupExecutionMiddleware(next);
return context => middleware.InvokeAsync(context);
};
}
100 changes: 100 additions & 0 deletions src/HotChocolate/Core/test/Execution.Tests/WarmupRequestTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
using HotChocolate.Execution.Caching;
using HotChocolate.Language;
using Microsoft.Extensions.DependencyInjection;
using Moq;

namespace HotChocolate.Execution;

public class WarmupRequestTests
{
[Fact]
public async Task Warmup_Request_Warms_Up_Caches()
{
// arrange
var executor = await new ServiceCollection()
.AddGraphQL()
.AddQueryType<Query>()
.BuildRequestExecutorAsync();

var documentId = "f614e9a2ed367399e87751d41ca09105";
var warmupRequest = OperationRequestBuilder.New()
.SetDocument("query test($name: String!) { greeting(name: $name) }")
.SetDocumentId(documentId)
.MarkAsWarmupRequest()
.Build();

var regularRequest = OperationRequestBuilder.New()
.SetDocumentId(documentId)
.SetVariableValues(new Dictionary<string, object?> { ["name"] = "Foo" })
.Build();

// act 1
var warmupResult = await executor.ExecuteAsync(warmupRequest);

// assert 1
Assert.IsType<WarmupExecutionResult>(warmupResult);

var provider = executor.Services.GetCombinedServices();
var documentCache = provider.GetRequiredService<IDocumentCache>();
var operationCache = provider.GetRequiredService<IPreparedOperationCache>();

Assert.True(documentCache.TryGetDocument(documentId, out _));
Assert.Equal(1, operationCache.Count);

// act 2
var regularResult = await executor.ExecuteAsync(regularRequest);
var regularOperationResult = regularResult.ExpectOperationResult();

// assert 2
Assert.Null(regularOperationResult.Errors);
Assert.NotNull(regularOperationResult.Data);
Assert.NotEmpty(regularOperationResult.Data);

Assert.True(documentCache.TryGetDocument(documentId, out _));
Assert.Equal(1, operationCache.Count);
}

[Fact]
public async Task Warmup_Request_Can_Skip_Persisted_Operation_Check()
{
// arrange
var executor = await new ServiceCollection()
.AddGraphQL()
.ConfigureSchemaServices(services =>
{
services.AddSingleton<IOperationDocumentStorage>(_ => new Mock<IOperationDocumentStorage>().Object);
})
.AddQueryType<Query>()
.ModifyRequestOptions(options =>
{
options.PersistedOperations.OnlyAllowPersistedDocuments = true;
})
.UsePersistedOperationPipeline()
.BuildRequestExecutorAsync();

var documentId = "f614e9a2ed367399e87751d41ca09105";
var warmupRequest = OperationRequestBuilder.New()
.SetDocument("query test($name: String!) { greeting(name: $name) }")
.SetDocumentId(documentId)
.MarkAsWarmupRequest()
.Build();

// act
var warmupResult = await executor.ExecuteAsync(warmupRequest);

// assert
Assert.IsType<WarmupExecutionResult>(warmupResult);

var provider = executor.Services.GetCombinedServices();
var documentCache = provider.GetRequiredService<IDocumentCache>();
var operationCache = provider.GetRequiredService<IPreparedOperationCache>();

Assert.True(documentCache.TryGetDocument(documentId, out _));
Assert.Equal(1, operationCache.Count);
}

public class Query
{
public string Greeting(string name) => $"Hello {name}";
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,7 @@ private static IRequestExecutorBuilder UseFusionDefaultPipeline(
.UseDocumentValidation()
.UseOperationCache()
.UseOperationResolver()
.UseSkipWarmupExecution()
.UseOperationVariableCoercion()
.UseDistributedOperationExecution();
}
Expand All @@ -588,6 +589,7 @@ private static IRequestExecutorBuilder UseFusionPersistedOperationPipeline(
.UseDocumentValidation()
.UseOperationCache()
.UseOperationResolver()
.UseSkipWarmupExecution()
.UseOperationVariableCoercion()
.UseDistributedOperationExecution();
}
Expand All @@ -612,6 +614,7 @@ private static IRequestExecutorBuilder UseFusionAutomaticPersistedOperationPipel
.UseDocumentValidation()
.UseOperationCache()
.UseOperationResolver()
.UseSkipWarmupExecution()
.UseOperationVariableCoercion()
.UseDistributedOperationExecution();
}
Expand Down
4 changes: 4 additions & 0 deletions website/src/docs/docs.json
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,10 @@
"path": "dependency-injection",
"title": "Dependency injection"
},
{
"path": "warmup",
"title": "Warmup"
},
{
"path": "global-state",
"title": "Global State"
Expand Down
12 changes: 2 additions & 10 deletions website/src/docs/hotchocolate/v15/performance/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,9 @@ In this section we will look at some ways of how we can improve the performance

# Startup performance

The first GraphQL request issued against a Hot Chocolate server will most of the time take a little longer than subsequent requests. This is because Hot Chocolate has to build up the GraphQL schema and prepare for the execution of requests.
Instead of the schema being created lazily, you can move its creation to the server startup and also specify warmup tasks.

We can however delegate this task to the startup of the application instead of the first request, by call `InitializeOnStartup()` on the `IRequestExecutorBuilder`.

```csharp
builder.Services
.AddGraphQLServer()
.InitializeOnStartup()
```

This will create the schema and warmup the request executor as soon as the app starts. This also brings the added benefit that schema errors are surfaced at app startup and not on the first request.
[Learn more server warmup](/docs/hotchocolate/v15/server/warmup)

# Persisted operations

Expand Down
101 changes: 101 additions & 0 deletions website/src/docs/hotchocolate/v15/server/warmup.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
---
title: Warmup
---

By default the creation of Hot Chocolate's schema is lazy. If a request is about to be executed against the schema or the schema is otherwise needed, it will be constructed on the fly.

Depending on the size of your schema this might be undesired, since it will cause initial requests to run longer than they would, if the schema was already constructed.

In an environment with a load balancer, you might also want to utilize something like a Readiness Probe to determine when your server is ready (meaning fully initialized) to handle requests.

# Initializing the schema on startup

If you want the schema creation process to happen at server startup, rather than lazily, you can chain in a call to `InitializeOnStartup()` on the `IRequestExecutorBuilder`.

```csharp
builder.Services
.AddGraphQLServer()
.InitializeOnStartup()
```

This will cause a hosted service to be executed as part of the server startup process, taking care of the schema creation. This process is blocking, meaning Kestrel won't answer requests until the construction of the schema is done. If you're using standard ASP.NET Core health checks, this will already suffice to implement a simple Readiness Probe.

This also has the added benefit that schema misconfigurations will cause errors at startup, tightening the feedback loop while developing.

# Warming up the executor

Creating the schema at startup is already a big win for the performance of initial requests. Though, you might want to go one step further and already initialize in-memory caches like the document and operation cache, before serving any requests.

For this the `InitializeOnStartup()` method contains an argument called `warmup` that allows you to pass a callback where you can execute requests against the newly created schema.

```csharp
builder.Services
.AddGraphQLServer()
.InitializeOnStartup(
warmup: async (executor, cancellationToken) => {
await executor.ExecuteAsync("{ __typename }");
});
```

The warmup process is also blocking, meaning the server won't start answering requests until both the schema creation and the warmup process is finished.

Since the execution of an operation could have side-effects, you might want to only warmup the executor, but skip the actual execution of the request. For this you can mark an operation as a warmup request.

```csharp
var request = OperationRequestBuilder.New()
.SetDocument("{ __typename }")
.MarkAsWarmupRequest()
.Build();

await executor.ExecuteAsync(request);
```

Requests marked as warmup requests will be able to skip security measures like persisted operations and will finish without actually executing the specified operation.

Keep in mind that the operation name is part of the operation cache. If your client is sending an operation name, you also want to include that operation name in the warmup request, or the actual request will miss the cache.

```csharp
var request = OperationRequestBuilder.New()
.SetDocument("query testQuery { __typename }")
.SetOperationName("testQuery")
.MarkAsWarmupRequest()
.Build();
```

## Skipping reporting

If you've implemented a custom diagnostic event listener as described [here](/docs/hotchocolate/v15/server/instrumentation#execution-events) you might want to skip reporting certain events in the case of a warmup request.

You can use the `IRequestContext.IsWarmupRequest()` method to determine whether a request is a warmup request or not.

```csharp
public class MyExecutionEventListener : ExecutionDiagnosticEventListener
{
public override void RequestError(IRequestContext context,
Exception exception)
{
if (context.IsWarmupRequest())
{
return;
}

// Reporting
}
}

```

## Keeping the executor warm

By default the warmup only takes place at server startup. If you're using [dynamic schemas](/docs/hotchocolate/v15/defining-a-schema/dynamic-schemas) for instance, your schema might change throughout the lifetime of the server.
In this case the warmup will not apply to subsequent schema changes, unless you set the `keepWarm` argument to `true`.

```csharp
builder.Services
.AddGraphQLServer()
.InitializeOnStartup(
keepWarm: true,
warmup: /* ... */);
```

If set to `true`, the schema and its warmup task will be executed in the background, while requests are still handled by the old schema. Once the warmup is finished requests will be served by the new and already warmed up schema.

0 comments on commit b669e1f

Please sign in to comment.