From 0665d920a24da835e3de8feab2fbd69ac1222a90 Mon Sep 17 00:00:00 2001 From: Michael Staib Date: Wed, 22 Jul 2026 13:11:25 +0000 Subject: [PATCH] Record delivered subscription events as Ok on client disconnect --- .../Spans/SubscriptionEventSpan.cs | 17 + ...ctivityExecutionDiagnosticEventListener.cs | 18 + ...ggregateFusionExecutionDiagnosticEvents.cs | 16 + .../FusionExecutionDiagnosticEventListener.cs | 9 + .../IFusionExecutionDiagnosticEvents.cs | 23 ++ .../Nodes/EventStreamExecutionNode.cs | 56 ++- .../Execution/OperationPlanExecutor.cs | 12 + .../EventStreamBrokerReadFailureTests.cs | 329 ++++++++++++++++++ 8 files changed, 478 insertions(+), 2 deletions(-) create mode 100644 src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Subscriptions/EventStreamBrokerReadFailureTests.cs diff --git a/src/HotChocolate/Diagnostics/src/Diagnostics.Core/Spans/SubscriptionEventSpan.cs b/src/HotChocolate/Diagnostics/src/Diagnostics.Core/Spans/SubscriptionEventSpan.cs index e1dfe0ae1d0..18933e81b72 100644 --- a/src/HotChocolate/Diagnostics/src/Diagnostics.Core/Spans/SubscriptionEventSpan.cs +++ b/src/HotChocolate/Diagnostics/src/Diagnostics.Core/Spans/SubscriptionEventSpan.cs @@ -8,6 +8,8 @@ namespace HotChocolate.Diagnostics; internal sealed class SubscriptionEventSpan(Activity activity, RequestContext context) : SpanBase(activity) { + private bool _delivered; + public static SubscriptionEventSpan? Start( ActivitySource source, RequestContext context, @@ -32,6 +34,12 @@ internal sealed class SubscriptionEventSpan(Activity activity, RequestContext co return new SubscriptionEventSpan(activity, context); } + /// + /// Marks the event result as fully written to the client so that completing the + /// span records success even if the client disconnects afterwards. + /// + public void SetDelivered() => _delivered = true; + protected override void OnComplete() { if (Activity.Status == ActivityStatusCode.Error) @@ -39,6 +47,15 @@ protected override void OnComplete() return; } + // An event that was fully written to the client is a success even when the + // client drops the connection right after receiving it, so a teardown that + // races the delivery must not leave the span Unset. + if (_delivered) + { + Activity.SetStatus(ActivityStatusCode.Ok); + return; + } + // If the caller dropped the connection while this event was in flight the // event was cancelled intentionally. Per the OpenTelemetry semantic // conventions that is not an error, so the span is left Unset instead of diff --git a/src/HotChocolate/Fusion/src/Fusion.Diagnostics/Listeners/FusionActivityExecutionDiagnosticEventListener.cs b/src/HotChocolate/Fusion/src/Fusion.Diagnostics/Listeners/FusionActivityExecutionDiagnosticEventListener.cs index 297d673d424..15ed77be47f 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Diagnostics/Listeners/FusionActivityExecutionDiagnosticEventListener.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Diagnostics/Listeners/FusionActivityExecutionDiagnosticEventListener.cs @@ -346,9 +346,27 @@ public override IDisposable OnSubscriptionEvent( enricher.EnrichOnSubscriptionEvent(context, node, schemaName, subscriptionId, span.Activity); + // The span is tracked on the request so that SubscriptionEventDelivered can + // mark it once the event result has been written to the client. Events of a + // subscription are processed strictly sequentially, so at most one event span + // is live per request at any time. + context.RequestContext.Features.Set(span); + return span; } + public override void SubscriptionEventDelivered( + OperationPlanContext context, + ExecutionNode node, + string schemaName, + ulong subscriptionId) + { + if (context.RequestContext.Features.TryGet(out var span)) + { + span.SetDelivered(); + } + } + public override void SubscriptionEventError( OperationPlanContext context, ExecutionNode node, diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/AggregateFusionExecutionDiagnosticEvents.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/AggregateFusionExecutionDiagnosticEvents.cs index e24302edc34..07cf6234d4b 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/AggregateFusionExecutionDiagnosticEvents.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/AggregateFusionExecutionDiagnosticEvents.cs @@ -372,6 +372,22 @@ public IDisposable OnSubscriptionEvent( return new AggregateActivityScope(scopes); } + public void SubscriptionEventDelivered( + OperationPlanContext context, + ExecutionNode node, + string schemaName, + ulong subscriptionId) + { + for (var i = 0; i < listeners.Length; i++) + { + listeners[i].SubscriptionEventDelivered( + context, + node, + schemaName, + subscriptionId); + } + } + public IDisposable ExecuteNodeFieldNode(OperationPlanContext context, NodeFieldExecutionNode node) { var scopes = new IDisposable[listeners.Length]; diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/FusionExecutionDiagnosticEventListener.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/FusionExecutionDiagnosticEventListener.cs index e33288ba5a4..c9fe1484c58 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/FusionExecutionDiagnosticEventListener.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/FusionExecutionDiagnosticEventListener.cs @@ -190,6 +190,15 @@ public virtual IDisposable OnSubscriptionEvent( ulong subscriptionId) => EmptyScope; + /// + public virtual void SubscriptionEventDelivered( + OperationPlanContext context, + ExecutionNode node, + string schemaName, + ulong subscriptionId) + { + } + /// public virtual IDisposable ExecuteNodeFieldNode(OperationPlanContext context, NodeFieldExecutionNode node) => EmptyScope; diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/IFusionExecutionDiagnosticEvents.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/IFusionExecutionDiagnosticEvents.cs index bcc4ca2ff2b..bf9e9a91e5b 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/IFusionExecutionDiagnosticEvents.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Diagnostics/IFusionExecutionDiagnosticEvents.cs @@ -388,4 +388,27 @@ IDisposable OnSubscriptionEvent( ExecutionNode node, string schemaName, ulong subscriptionId); + + /// + /// Called when a subscription event result has been fully written to the client. + /// A client disconnect that happens after this call must not change the recorded + /// outcome of the event. + /// + /// + /// The operation plan context. + /// + /// + /// The execution node. + /// + /// + /// The name of the source schema. + /// + /// + /// An internal identifier for the subscription instance. + /// + void SubscriptionEventDelivered( + OperationPlanContext context, + ExecutionNode node, + string schemaName, + ulong subscriptionId); } diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/EventStreamExecutionNode.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/EventStreamExecutionNode.cs index 02bc2263ece..81d513814ae 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/EventStreamExecutionNode.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/Nodes/EventStreamExecutionNode.cs @@ -206,6 +206,7 @@ private sealed class EventStreamSubscriptionEnumerator : IAsyncEnumerator MoveNextAsync() { - if (_disposed || _cancellationToken.IsCancellationRequested) + if (_disposed || _completed || _cancellationToken.IsCancellationRequested) { Current = null!; return false; } - if (!await _subscription.Enumerator.MoveNextAsync().ConfigureAwait(false)) + bool hasResult; + + try + { + hasResult = await _subscription.Enumerator.MoveNextAsync().ConfigureAwait(false); + } + catch (Exception exception) + { + _completed = true; + + // A cancellation signalled while the broker read was in flight (client + // abort, shutdown or enumerator disposal) is the same graceful teardown + // as observing the token before the read, not a subscription event + // error. The broker enumerator runs on the dispose token, which links + // the external cancellation token. + if (exception is OperationCanceledException + && _disposeCts.IsCancellationRequested) + { + Current = null!; + return false; + } + + _diagnosticEvents.SubscriptionEventError( + _context, + _node, + _subscription.Source.SchemaName, + _subscriptionId, + exception); + + _context.AddErrors( + ErrorBuilder.FromException(exception).Build(), + _node._resultSelectionSet, + Path.Root); + + // A failed broker read ends the stream, mirroring how the operation + // subscription node terminates on a failed transport read. No per-event + // scope is open at read stage. + var timestamp = Stopwatch.GetTimestamp(); + Current = new EventMessageResult( + _node.Id, + Activity.Current, + ExecutionStatus.Failed, + Disposable.Empty, + timestamp, + Stopwatch.GetTimestamp(), + Exception: exception, + VariableValueSets: [], + DependentsToExecute: default); + return false; + } + + if (!hasResult) { Current = null!; return false; diff --git a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/OperationPlanExecutor.cs b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/OperationPlanExecutor.cs index eff87c2ec82..0d2eb35c09a 100644 --- a/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/OperationPlanExecutor.cs +++ b/src/HotChocolate/Fusion/src/Fusion.Execution/Execution/OperationPlanExecutor.cs @@ -1240,6 +1240,18 @@ private static async IAsyncEnumerable CreateResponseStream( } yield return result; + + // Execution resumes here only after the consumer finished writing the + // yielded result to the client and asked for the next event. Record the + // delivery before the event scope is disposed at the end of this loop + // iteration, so a client abort that races the resume cannot erase the + // delivered event's success status. An event whose write failed never + // resumes the stream and therefore is never reported as delivered. + context.DiagnosticEvents.SubscriptionEventDelivered( + context, + subscriptionNode, + schemaName, + subscriptionResult.Id); } } finally diff --git a/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Subscriptions/EventStreamBrokerReadFailureTests.cs b/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Subscriptions/EventStreamBrokerReadFailureTests.cs new file mode 100644 index 00000000000..5adf082b2e5 --- /dev/null +++ b/src/HotChocolate/Fusion/test/Fusion.Execution.Tests/Execution/Subscriptions/EventStreamBrokerReadFailureTests.cs @@ -0,0 +1,329 @@ +using System.Buffers; +using System.Collections.Immutable; +using System.Runtime.CompilerServices; +using System.Threading.Channels; +using HotChocolate.Execution; +using HotChocolate.Fusion.Configuration; +using HotChocolate.Fusion.Diagnostics; +using HotChocolate.Fusion.Execution; +using HotChocolate.Fusion.Execution.Clients; +using HotChocolate.Fusion.Execution.Nodes; +using HotChocolate.Fusion.Types; +using HotChocolate.Language; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; + +namespace HotChocolate.Fusion.Subscriptions; + +public sealed class EventStreamBrokerReadFailureTests +{ + private const string BrokerName = "failing"; + + [Fact] + public async Task Subscribe_Should_EndStreamAndRaiseSubscriptionEventError_When_BrokerReadFails() + { + // arrange + // The broker delivers one event and then fails the next read with a connection + // loss. The failed read must be reported through SubscriptionEventError and end + // the subscription stream gracefully instead of surfacing a raw exception. + var topic = CreateTopic(); + var broker = new FailingEventStreamBroker(); + var listener = new CapturingDiagnosticListener(); + var services = CreateServices(topic, broker, listener); + var executor = await services.BuildGatewayAsync(TestContext.Current.CancellationToken); + using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)); + + var events = CollectAllEventsAsync( + executor, + """ + subscription { + onBookChanged { + id + } + } + """, + cts.Token); + + await WaitForSubscriberAsync(broker, cts.Token); + + // act + await broker.PublishAsync("""{"id":1}"""u8.ToArray(), cts.Token); + broker.Fail(new InvalidOperationException( + "The connection to the event stream broker was lost.")); + + // assert + // the delivered event arrives, then the stream completes without throwing + var results = await events; + results.MatchInlineSnapshots( + [ + """ + { + "data": { + "onBookChanged": { + "id": 1 + } + } + } + """ + ]); + + var exception = Assert.IsType(listener.Exception); + Assert.Equal("The connection to the event stream broker was lost.", exception.Message); + Assert.Equal("EVENTS", listener.SchemaName); + } + + private static ServiceCollection CreateServices( + string topic, + FailingEventStreamBroker broker, + CapturingDiagnosticListener listener) + { + var services = new ServiceCollection(); + services.AddHttpClient(); + services.TryAddSingleton(); + services.AddKeyedSingleton( + BrokerName, + (_, _) => new FailingEventStreamBrokerProvider(broker)); + + var builder = services + .AddGraphQLGateway() + .AddInMemoryConfiguration(CreateExecutionSchemaDocument(topic)) + .AddDiagnosticEventListener(_ => listener); + + builder.Services.AddSingleton( + new TestSourceSchemaClientFactory()); + + FusionSetupUtilities.Configure( + builder, + setup => setup.ClientConfigurationModifiers.Add( + _ => new TestSourceSchemaClientConfiguration("EVENTS"))); + + return services; + } + + private static async Task> CollectAllEventsAsync( + IRequestExecutor executor, + string document, + CancellationToken cancellationToken) + { + var request = OperationRequestBuilder.New() + .SetDocument(document) + .Build(); + + var result = await executor.ExecuteAsync(request, cancellationToken); + var stream = result.ExpectResponseStream(); + var events = new List(); + + await foreach (var operationResult in stream + .ReadResultsAsync() + .WithCancellation(cancellationToken)) + { + events.Add(operationResult.ToJson()); + } + + await result.DisposeAsync(); + return events; + } + + private static async Task WaitForSubscriberAsync( + FailingEventStreamBroker broker, + CancellationToken cancellationToken) + { + while (broker.SubscriberCount < 1) + { + await Task.Delay(10, cancellationToken); + } + } + + private static string CreateTopic() + => "fusion." + Guid.NewGuid().ToString("N"); + + private static DocumentNode CreateExecutionSchemaDocument(string topic) + => Utf8GraphQLParser.Parse( + $$""" + schema { + query: Query + subscription: Subscription + } + + type Query + @fusion__type(schema: EVENTS) { + field: String + @fusion__field(schema: EVENTS) + } + + type Subscription + @fusion__type(schema: EVENTS) { + onBookChanged: BookChanged + @fusion__field(schema: EVENTS) + @fusion__eventStream( + schema: EVENTS + topics: ["{{topic}}"] + broker: "{{BrokerName}}" + message: "{ id }" + ) + } + + type BookChanged + @fusion__type(schema: EVENTS) { + id: Int! + @fusion__field(schema: EVENTS) + } + + enum fusion__Schema { + EVENTS + } + + scalar fusion__FieldDefinition + scalar fusion__FieldSelectionMap + scalar fusion__FieldSelectionSet + + directive @fusion__type( + schema: fusion__Schema! + ) repeatable on OBJECT | INTERFACE | UNION | ENUM | INPUT_OBJECT | SCALAR + + directive @fusion__field( + schema: fusion__Schema! + sourceName: String + sourceType: String + provides: fusion__FieldSelectionSet + external: Boolean! = false + ) repeatable on FIELD_DEFINITION + + directive @fusion__eventStream( + schema: fusion__Schema! + topics: [String!] + broker: String + message: fusion__FieldSelectionSet! + cursorField: String + cursorArgument: String + ) on FIELD_DEFINITION + """); + + // Delivers published events in order and then surfaces the injected failure from the + // read, modeling a broker connection loss while the subscription awaits the next event. + private sealed class FailingEventStreamBroker : IEventStreamBroker + { + private readonly Channel _channel = Channel.CreateUnbounded(); + private int _subscriberCount; + + public int SubscriberCount => Volatile.Read(ref _subscriberCount); + + public async ValueTask PublishAsync(ReadOnlyMemory body, CancellationToken cancellationToken) + { + var owner = MemoryPool.Shared.Rent(body.Length); + body.Span.CopyTo(owner.Memory.Span); + var message = new EventMessage(owner, 0..body.Length, body.Length..body.Length); + await _channel.Writer.WriteAsync(message, cancellationToken); + } + + public void Fail(Exception exception) + => _channel.Writer.TryComplete(exception); + + public IAsyncEnumerable SubscribeAsync( + ISubscriptionFieldContext context, + string[] topics, + string? cursor, + CancellationToken cancellationToken) + => SubscribeCoreAsync(cancellationToken); + + private async IAsyncEnumerable SubscribeCoreAsync( + [EnumeratorCancellation] CancellationToken cancellationToken) + { + Interlocked.Increment(ref _subscriberCount); + + await foreach (var message in _channel.Reader + .ReadAllAsync(cancellationToken) + .ConfigureAwait(false)) + { + yield return message; + } + } + + public ValueTask DisposeAsync() + { + _channel.Writer.TryComplete(); + + while (_channel.Reader.TryRead(out var message)) + { + message.Dispose(); + } + + return ValueTask.CompletedTask; + } + } + + private sealed class FailingEventStreamBrokerProvider(FailingEventStreamBroker broker) + : IEventStreamBrokerProvider + { + public IEventStreamBroker Create() => broker; + } + + private sealed class CapturingDiagnosticListener : FusionExecutionDiagnosticEventListener + { + public string? SchemaName { get; private set; } + + public Exception? Exception { get; private set; } + + public override void SubscriptionEventError( + OperationPlanContext context, + ExecutionNode node, + string schemaName, + ulong subscriptionId, + Exception exception) + { + SchemaName = schemaName; + Exception = exception; + } + } + + private sealed class TestSourceSchemaClientFactory : ISourceSchemaClientFactory + { + public bool CanHandle(ISourceSchemaClientConfiguration configuration) + => configuration is TestSourceSchemaClientConfiguration; + + public ISourceSchemaClient CreateClient( + FusionSchemaDefinition schema, + ISourceSchemaClientConfiguration configuration) + => new ThrowingSourceSchemaClient(); + } + + private sealed class TestSourceSchemaClientConfiguration(string name) + : ISourceSchemaClientConfiguration + { + public string Name { get; } = name; + + public SupportedOperationType SupportedOperations => SupportedOperationType.All; + } + + private sealed class ThrowingSourceSchemaClient : ISourceSchemaClient + { + public SourceSchemaClientCapabilities Capabilities => SourceSchemaClientCapabilities.None; + + public async IAsyncEnumerable ExecuteAsync( + OperationPlanContext context, + SourceSchemaClientRequest request, + [EnumeratorCancellation] CancellationToken cancellationToken) + { + await Task.Yield(); + throw new InvalidOperationException( + $"The source schema '{request.SchemaName}' should not have been executed."); +#pragma warning disable CS0162 + yield break; +#pragma warning restore CS0162 + } + + 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; + } +}