Skip to content
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 @@ -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,
Expand All @@ -32,13 +34,28 @@ internal sealed class SubscriptionEventSpan(Activity activity, RequestContext co
return new SubscriptionEventSpan(activity, context);
}

/// <summary>
/// Marks the event result as fully written to the client so that completing the
/// span records success even if the client disconnects afterwards.
/// </summary>
public void SetDelivered() => _delivered = true;

protected override void OnComplete()
{
if (Activity.Status == ActivityStatusCode.Error)
{
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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<SubscriptionEventSpan>(out var span))
{
span.SetDelivered();
}
}

public override void SubscriptionEventError(
OperationPlanContext context,
ExecutionNode node,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,15 @@ public virtual IDisposable OnSubscriptionEvent(
ulong subscriptionId)
=> EmptyScope;

/// <inheritdoc />
public virtual void SubscriptionEventDelivered(
OperationPlanContext context,
ExecutionNode node,
string schemaName,
ulong subscriptionId)
{
}

/// <inheritdoc />
public virtual IDisposable ExecuteNodeFieldNode(OperationPlanContext context, NodeFieldExecutionNode node)
=> EmptyScope;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -388,4 +388,27 @@ IDisposable OnSubscriptionEvent(
ExecutionNode node,
string schemaName,
ulong subscriptionId);

/// <summary>
/// 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.
/// </summary>
/// <param name="context">
/// The operation plan context.
/// </param>
/// <param name="node">
/// The execution node.
/// </param>
/// <param name="schemaName">
/// The name of the source schema.
/// </param>
/// <param name="subscriptionId">
/// An internal identifier for the subscription instance.
/// </param>
void SubscriptionEventDelivered(
OperationPlanContext context,
ExecutionNode node,
string schemaName,
ulong subscriptionId);
Comment thread
michaelstaib marked this conversation as resolved.
Resolved
}
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,7 @@ private sealed class EventStreamSubscriptionEnumerator : IAsyncEnumerator<EventM
private readonly IDisposable _subscriptionScope;
private readonly BrokerSubscription _subscription;
private readonly SourceSchemaResult[] _resultBuffer = new SourceSchemaResult[1];
private bool _completed;
private bool _disposed;

public EventStreamSubscriptionEnumerator(
Expand Down Expand Up @@ -244,13 +245,64 @@ public EventStreamSubscriptionEnumerator(

public async ValueTask<bool> 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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1240,6 +1240,18 @@ private static async IAsyncEnumerable<OperationResult> 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);
Comment on lines +1244 to +1254
}
}
finally
Expand Down
Loading
Loading