diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/ApolloOperationBatchExecutionNode.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/ApolloOperationBatchExecutionNode.cs index eca6a064f7b..597a3a524d9 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/ApolloOperationBatchExecutionNode.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/ApolloOperationBatchExecutionNode.cs @@ -197,44 +197,57 @@ private async ValueTask ExecuteSingleAsync( RequiresFileUpload = false }; - SourceSchemaResult? result = null; - var hasSomeErrors = false; + var results = new SourceSchemaResultCollector(initialCapacity: 2); try { var client = context.GetClient(schemaName, lookup.Operation.Type); using var clientScope = diagnosticEvents.ExecuteSourceSchemaRequest(context, this, schemaName); - await foreach (var current in client.ExecuteAsync(context, request, cancellationToken) - .ConfigureAwait(false)) + if (client is HttpSourceSchemaClient httpClient + && HttpSourceSchemaClient.CanExecuteBuffered(lookup.Operation.Type, requiresFileUpload: false)) { - if (result is not null) + await httpClient + .ExecuteBufferedAsync(context, request, results, cancellationToken) + .ConfigureAwait(false); + } + else + { + await foreach (var current in client.ExecuteAsync(context, request, cancellationToken) + .ConfigureAwait(false)) { - current.Dispose(); - throw ThrowHelper.ApolloEntityFetchProducedMultipleResults(); - } - - result = current; + // A second result ends the read, so a source that keeps its stream open is not awaited. + if (results.Count > 0) + { + current.Dispose(); + throw ThrowHelper.ApolloEntityFetchProducedMultipleResults(); + } - if (current.Errors is not null) - { - hasSomeErrors = true; + results.OnResult(0, current); } } + + if (results.Count > 1) + { + throw ThrowHelper.ApolloEntityFetchProducedMultipleResults(); + } } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { - result?.Dispose(); + results.DisposeResults(); return ExecutionStatus.Failed; } catch (Exception exception) { diagnosticEvents.SourceSchemaTransportError(context, this, schemaName, exception); - result?.Dispose(); + results.DisposeResults(); context.AddErrors(exception, variables, operation.ResultSelectionSet); return ExecutionStatus.Failed; } + var result = results.Single; + var hasSomeErrors = results.HasErrors; + if (result is null) { context.AddErrors( @@ -259,7 +272,10 @@ private async ValueTask ExecuteSingleAsync( result, hasSomeErrors); hasPendingMerge = true; - context.EnqueuePendingMerge(pendingMerge); + + // ExecuteAsync reports the completion of this node right after we return, + // and that signal wakes the executor for the merge as well. + context.EnqueuePendingMergeBeforeCompletion(pendingMerge); } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -328,69 +344,44 @@ private async ValueTask ExecuteBatchAsync( // the executor loop so downstream nodes can consume the data after completion. var client = context.GetClient(schemaName, requests[0].OperationType); receivedResults.AsSpan(0, operationCount).Clear(); - var overallStatus = ExecutionStatus.Success; + + var sink = new EntityBatchResultSink( + this, + context, + schemaName, + operationByIndex, + representationByIndex, + variablesByIndex, + receivedResults, + cancellationToken); using var clientScope = diagnosticEvents.ExecuteSourceSchemaRequest(context, this, schemaName); - await foreach (var batchResult in client.ExecuteBatchAsync(context, requests, cancellationToken) - .ConfigureAwait(false)) + if (client is HttpSourceSchemaClient httpClient && httpClient.CanExecuteBatchBuffered(requests)) { - var requestIndex = batchResult.RequestIndex; - var op = operationByIndex[requestIndex]; - var result = batchResult.Result; - var hasErrors = result.Errors is not null; - - receivedResults[requestIndex] = true; - - var pendingMerge = default(PendingMerge); - var hasPendingMerge = false; - - try - { - pendingMerge = PendingMerge.RepresentationSingle( - this, - schemaName, - s_entitiesSource, - op.ResultSelectionSet, - variablesByIndex[requestIndex], - representationByIndex[requestIndex], - result, - hasErrors); - hasPendingMerge = true; - context.EnqueuePendingMerge(pendingMerge); - } - catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) - { - if (hasPendingMerge) - { - pendingMerge.DisposeUnmerged(); - } - - return ExecutionStatus.Failed; - } - catch (Exception exception) + await httpClient + .ExecuteBatchBufferedAsync(context, requests, sink, cancellationToken) + .ConfigureAwait(false); + } + else + { + await foreach (var batchResult in client.ExecuteBatchAsync(context, requests, cancellationToken) + .ConfigureAwait(false)) { - if (hasPendingMerge) - { - pendingMerge.DisposeUnmerged(); - } - else + if (!sink.OnResult(batchResult.RequestIndex, batchResult.Result)) { - result.Dispose(); + break; } - - diagnosticEvents.SourceSchemaStoreError(context, this, schemaName, exception); - context.AddErrors(exception, variablesByIndex[requestIndex], op.ResultSelectionSet); - overallStatus = ExecutionStatus.Failed; - continue; } + } - if (hasErrors && overallStatus == ExecutionStatus.Success) - { - overallStatus = ExecutionStatus.PartialSuccess; - } + if (sink.IsCanceled) + { + return ExecutionStatus.Failed; } + var overallStatus = sink.Status; + // Verify that the downstream service returned a result for every // operation in the batch. A missing result means the service did // not implement the batch protocol correctly. We surface this as @@ -681,6 +672,91 @@ private static SelectionPath GetPrimaryTarget(OperationDefinition operation) _ => throw ThrowHelper.UnknownOperationDefinition(operation.GetType()) }; + /// + /// Queues the merge of each result of a batch as it arrives and records which operations + /// received a result. A result that cannot be queued fails its operation but not the batch. + /// + private sealed class EntityBatchResultSink( + ApolloOperationBatchExecutionNode node, + OperationPlanContext context, + string schemaName, + OperationDefinition[] operationByIndex, + RepresentationValue[] representationByIndex, + ImmutableArray[] variablesByIndex, + bool[] receivedResults, + CancellationToken cancellationToken) + : ISourceSchemaResultSink + { + /// + /// Gets the status of the batch from the results received so far. + /// + public ExecutionStatus Status { get; private set; } = ExecutionStatus.Success; + + /// + /// Gets whether queueing a result was canceled, which stops reading the batch. + /// + public bool IsCanceled { get; private set; } + + public bool OnResult(int requestIndex, SourceSchemaResult result) + { + var op = operationByIndex[requestIndex]; + var hasErrors = result.Errors is not null; + + receivedResults[requestIndex] = true; + + var pendingMerge = default(PendingMerge); + var hasPendingMerge = false; + + try + { + pendingMerge = PendingMerge.RepresentationSingle( + node, + schemaName, + s_entitiesSource, + op.ResultSelectionSet, + variablesByIndex[requestIndex], + representationByIndex[requestIndex], + result, + hasErrors); + hasPendingMerge = true; + context.EnqueuePendingMerge(pendingMerge); + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + if (hasPendingMerge) + { + pendingMerge.DisposeUnmerged(); + } + + IsCanceled = true; + return false; + } + catch (Exception exception) + { + if (hasPendingMerge) + { + pendingMerge.DisposeUnmerged(); + } + else + { + result.Dispose(); + } + + context.DiagnosticEvents.SourceSchemaStoreError(context, node, schemaName, exception); + context.AddErrors(exception, variablesByIndex[requestIndex], op.ResultSelectionSet); + Status = ExecutionStatus.Failed; + return true; + } + + if (hasErrors && Status == ExecutionStatus.Success) + { + Status = ExecutionStatus.PartialSuccess; + } + + return true; + } + } + private static string ValidateOperations(OperationDefinition[] operations) { if (operations.Length == 0 diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/ApolloOperationExecutionNode.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/ApolloOperationExecutionNode.cs index 6dcac66ee98..c01a874f73a 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/ApolloOperationExecutionNode.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/ApolloOperationExecutionNode.cs @@ -248,28 +248,38 @@ protected override async ValueTask OnExecuteAsync( LookupTypeName = _lookup.EntityTypeName }; - SourceSchemaResult? result = null; - var hasSomeErrors = false; + var results = new SourceSchemaResultCollector(initialCapacity: 2); try { var client = context.GetClient(schemaName, _lookup.Operation.Type); using var clientScope = diagnosticEvents.ExecuteSourceSchemaRequest(context, this, schemaName); - await foreach (var current in client.ExecuteAsync(context, request, cancellationToken).ConfigureAwait(false)) + if (client is HttpSourceSchemaClient httpClient + && HttpSourceSchemaClient.CanExecuteBuffered(_lookup.Operation.Type, requiresFileUpload: false)) { - if (result is not null) + await httpClient + .ExecuteBufferedAsync(context, request, results, cancellationToken) + .ConfigureAwait(false); + } + else + { + await foreach (var current in client.ExecuteAsync(context, request, cancellationToken).ConfigureAwait(false)) { - current.Dispose(); - throw ThrowHelper.ApolloEntityFetchProducedMultipleResults(); + // A second result ends the read, so a source that keeps its stream open is not awaited. + if (results.Count > 0) + { + current.Dispose(); + throw ThrowHelper.ApolloEntityFetchProducedMultipleResults(); + } + + results.OnResult(0, current); } + } - result = current; - - if (current.Errors is not null) - { - hasSomeErrors = true; - } + if (results.Count > 1) + { + throw ThrowHelper.ApolloEntityFetchProducedMultipleResults(); } } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) @@ -277,18 +287,20 @@ protected override async ValueTask OnExecuteAsync( // If the execution of the node was cancelled, either the entire request was cancelled // or the execution was halted. In both cases we do not want to produce any errors // and just exit the node as quickly as possible. - result?.Dispose(); + results.DisposeResults(); return ExecutionStatus.Failed; } catch (Exception exception) { diagnosticEvents.SourceSchemaTransportError(context, this, schemaName, exception); - result?.Dispose(); + results.DisposeResults(); context.AddErrors(exception, variables, _resultSelectionSet); return ExecutionStatus.Failed; } + var result = results.Single; + var hasSomeErrors = results.HasErrors; var pendingMerge = default(PendingMerge); var hasPendingMerge = false; @@ -306,14 +318,11 @@ protected override async ValueTask OnExecuteAsync( result, hasSomeErrors); hasPendingMerge = true; - } - if (hasPendingMerge) - { - context.EnqueuePendingMerge(pendingMerge); + // ExecuteAsync reports the completion of this node right after we return, + // and that signal wakes the executor for the merge as well. + context.EnqueuePendingMergeBeforeCompletion(pendingMerge); } - - result = null; } catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) { @@ -335,7 +344,7 @@ protected override async ValueTask OnExecuteAsync( } else { - result?.Dispose(); + results.DisposeResults(); } diagnosticEvents.SourceSchemaStoreError(context, this, schemaName, exception); diff --git a/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Nodes/ApolloOperationExecutionNodeTests.cs b/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Nodes/ApolloOperationExecutionNodeTests.cs index c5939bd1334..3a41405423d 100644 --- a/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Nodes/ApolloOperationExecutionNodeTests.cs +++ b/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Nodes/ApolloOperationExecutionNodeTests.cs @@ -51,6 +51,44 @@ public async Task ExecuteAsync_Should_DisposeUnmergedResult_When_SourceStreamIsC result.ExpectOperationResult().Errors!.Single().Extensions!["code"]); } + [Fact] + public async Task ExecuteAsync_Should_StopReading_When_SourceStreamYieldsSecondResult() + { + // arrange + using var arena = new MemoryArena(); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource( + TestContext.Current.CancellationToken); + timeout.CancelAfter(TimeSpan.FromSeconds(30)); + var client = new YieldTwiceThenWaitClient(arena); + var services = new ServiceCollection(); + services.AddHttpClient(); + var builder = services.AddGraphQLGateway().AddInMemoryConfiguration(ComposeApolloSchema()); + builder.Services.AddSingleton(new TestClientFactory(client)); + FusionSetupUtilities.Configure( + builder, + setup => + { + setup.ClientConfigurationModifiers.Add(_ => new TestClientConfiguration("a")); + setup.ClientConfigurationModifiers.Add(_ => new TestClientConfiguration("b")); + }); + var executor = await services.BuildGatewayAsync(TestContext.Current.CancellationToken); + var request = OperationRequestBuilder.New().SetDocument("{ product { name } }").Build(); + + // act + await using var result = await executor.ExecuteAsync(request, timeout.Token); + + // assert + Assert.True(client.ApolloDispatched, result.ToJson()); + Assert.False(client.WaitStarted); + Assert.True(client.EnumeratorDisposed); + Assert.Equal( + nameof(ObjectDisposedException), + Record.Exception(() => client.First!.Root.GetProperty("data"))?.GetType().Name); + Assert.Equal( + nameof(ObjectDisposedException), + Record.Exception(() => client.Second!.Root.GetProperty("data"))?.GetType().Name); + } + private static DocumentNode ComposeApolloSchema() { const string sourceSchemaA = @@ -167,6 +205,71 @@ public IAsyncEnumerable SubscribeAsync( public ValueTask DisposeAsync() => ValueTask.CompletedTask; } + private sealed class YieldTwiceThenWaitClient(MemoryArena arena) : ISourceSchemaClient + { + private static readonly byte[] s_root = + """{"data":{"product":{"__typename":"Product","id":"1"}}}"""u8.ToArray(); + private static readonly byte[] s_entity = + """{"data":{"_entities":[{"name":"value"}]}}"""u8.ToArray(); + + public SourceSchemaClientCapabilities Capabilities => SourceSchemaClientCapabilities.None; + + public SourceResultDocument? First { get; private set; } + + public SourceResultDocument? Second { get; private set; } + + public bool ApolloDispatched { get; private set; } + + public bool WaitStarted { get; private set; } + + public bool EnumeratorDisposed { get; private set; } + + public async IAsyncEnumerable ExecuteAsync( + OperationPlanContext context, + SourceSchemaClientRequest request, + [EnumeratorCancellation] CancellationToken cancellationToken) + { + if (request.Node is not ApolloOperationExecutionNode) + { + var root = SourceResultDocument.Parse(context.Memory, s_root, s_root.Length); + yield return new SourceSchemaResult(CompactPath.Root, root); + yield break; + } + + ApolloDispatched = true; + + try + { + First = SourceResultDocument.Parse(arena, s_entity, s_entity.Length); + yield return new SourceSchemaResult(CompactPath.Root, First); + Second = SourceResultDocument.Parse(arena, s_entity, s_entity.Length); + yield return new SourceSchemaResult(CompactPath.Root, Second); + + // The stream stays open after its second result. + WaitStarted = true; + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + } + finally + { + EnumeratorDisposed = true; + } + } + + public IAsyncEnumerable ExecuteBatchAsync( + OperationPlanContext context, + ImmutableArray requests, + CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public IAsyncEnumerable SubscribeAsync( + OperationPlanContext context, + SourceSchemaClientRequest request, + CancellationToken cancellationToken) + => throw new NotSupportedException(); + + public ValueTask DisposeAsync() => ValueTask.CompletedTask; + } + private sealed class TestClientFactory(ISourceSchemaClient client) : ISourceSchemaClientFactory { public bool CanHandle(ISourceSchemaClientConfiguration configuration)