feat(Event streams): add support for cancellation and IAsyncEnumerable #3543
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
Adjust
EnumerableEventStream
to add support for cancellation and forIAsyncEnumerable
:IEnumerableEventStream
inherits fromIAsyncEnumerable
. That means that we can useawait foreach
on it, for example.EnumerableEventStream
implements it with a newGetAsyncEnumerator
method that mimics the existingGetEnumerator
, but usesReadFromStreamAsync
so that it does not block the calling thread while waiting on the incoming network stream.For example, to process the response stream from Bedrock
ConverseStreamRequest
, before this change we had to do:The problem above is that
foreach (var item in response.Stream.AsEnumerable())
is blocking the current .NET thread while waiting for the events to arrive, so it could cause thread pool exhaustion.With the changes in this pull request, we can write instead:
Notice the
await foreach
that is possible now thatIEnumerableEventStream
implementsIAsyncEnumerable
. The benefit is that the .NET thread is not blocked.It is also easy to add support for cancellation. For example:
Motivation and Context
The semantics of AWS event streams map well to .NET
IAsyncEnumerable
, but it's hard to build anIAsyncEnumerable
from such a stream.EnumerableEventStream
does provide an asyncStartProcessingAsync
method, but only a synchronous enumerator. So the happy path with the current API is to use a synchronous enumerator, which has the downside of blocking the current .NET thread while enumerating the events. This can lead to the thread pool starvation.This addresses #3542
Testing
Added an integration test. To run it, the test code needs to be adjusted to comment out the
Ignore
attribute, give credentials and a region.Screenshots (if appropriate)
Types of changes
Checklist
License