Fix race condition in SSE GET request initialization (#1212)

This commit is contained in:
Stephen Toub 2026-01-29 23:04:51 -05:00 • committed by GitHub
commit f9dec13660
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 6 additions and 5 deletions

View file

@ -154,11 +154,6 @@ internal sealed class StreamableHttpHandler(
{ {
await using var _ = await session.AcquireReferenceAsync(cancellationToken); await using var _ = await session.AcquireReferenceAsync(cancellationToken);
InitializeSseResponse(context); InitializeSseResponse(context);
// We should flush headers to indicate a 200 success quickly, because the initialization response
// will be sent in response to a different POST request. It might be a while before we send a message
// over this response body.
await context.Response.Body.FlushAsync(cancellationToken);
await session.Transport.HandleGetRequestAsync(context.Response.Body, cancellationToken); await session.Transport.HandleGetRequestAsync(context.Response.Body, cancellationToken);
} }
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)

View file

@ -125,6 +125,12 @@ public sealed class StreamableHttpServerTransport : ITransport
var primingItem = await _storeSseWriter.WriteEventAsync(SseItem.Prime<JsonRpcMessage>(), cancellationToken).ConfigureAwait(false); var primingItem = await _storeSseWriter.WriteEventAsync(SseItem.Prime<JsonRpcMessage>(), cancellationToken).ConfigureAwait(false);
await _httpSseWriter.WriteAsync(primingItem, cancellationToken).ConfigureAwait(false); await _httpSseWriter.WriteAsync(primingItem, cancellationToken).ConfigureAwait(false);
} }
else
{
// If there's no priming write, flush the stream to ensure HTTP response headers are
// sent to the client now that the transport is ready to accept messages via SendMessageAsync.
await sseResponseStream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
} }
// Wait for the response to be written before returning from the handler. // Wait for the response to be written before returning from the handler.