-
Notifications
You must be signed in to change notification settings - Fork 498
Add support for Lambda Response Streaming #2288
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
normj
wants to merge
21
commits into
feature/response-streaming
Choose a base branch
from
normj/response-streaming
base: feature/response-streaming
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+3,366
−427
Open
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
0cdb159
Task 4
normj 0aa892b
Task 5
normj 5e29c21
Task 4 (after redesign)
normj 603612d
Task 5
normj 63224bf
Task 6
normj 14c993b
Task 8
normj 0b8dd52
Task 10
normj 414a449
Refactoring
normj 21d82d8
Cleanup
normj 556b726
Remove tests
normj 4d5dee2
Clean up and rework Semaphore locks
normj d8322ff
Merge branch 'normj/response-streaming' of https://github.com/aws/aws…
normj 645771e
Start working on supporting having a prelude chuck in the response st…
normj 1f17a58
Rework to support class library programming model
normj 99b83c2
Rework encoding and add support for using API Gateway
normj ab93ce9
Backfill tests after refactor
normj bd0170e
Merge branch 'dev' into normj/response-streaming
normj d60bb93
Add integ tests
normj 9b308ae
Improve test error message
normj d0861c6
Debugging integ tests
normj 3c86629
Update change file
normj File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
18 changes: 18 additions & 0 deletions
18
.autover/changes/c27a62e6-91ca-4a59-9406-394866cdfa62.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,18 @@ | ||
| { | ||
| "Projects": [ | ||
| { | ||
| "Name": "Amazon.Lambda.RuntimeSupport", | ||
| "Type": "Minor", | ||
| "ChangelogMessages": [ | ||
| "(Preview) Add response streaming support" | ||
| ] | ||
| }, | ||
| { | ||
| "Name": "Amazon.Lambda.Core", | ||
| "Type": "Minor", | ||
| "ChangelogMessages": [ | ||
| "(Preview) Add response streaming support" | ||
| ] | ||
| } | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -4,6 +4,8 @@ | |
| *.suo | ||
| *.user | ||
|
|
||
| **/.kiro/ | ||
|
|
||
| #################### | ||
| # Build/Test folders | ||
| #################### | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
89 changes: 89 additions & 0 deletions
89
Libraries/src/Amazon.Lambda.Core/ResponseStreaming/HttpResponseStreamPrelude.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| #if NET8_0_OR_GREATER | ||
| using System.Collections.Generic; | ||
| using System.Net; | ||
| using System.Runtime.Versioning; | ||
| using System.Text.Json; | ||
|
|
||
| namespace Amazon.Lambda.Core.ResponseStreaming | ||
| { | ||
| /// <summary> | ||
| /// The HTTP response prelude to be sent as the first chunk of a streaming response when using <see cref="LambdaResponseStreamFactory.CreateHttpStream"/>. | ||
| /// </summary> | ||
| [RequiresPreviewFeatures(LambdaResponseStreamFactory.ParameterizedPreviewMessage)] | ||
| public class HttpResponseStreamPrelude | ||
| { | ||
| /// <summary> | ||
| /// The Http status code to include in the response prelude. | ||
| /// </summary> | ||
| public HttpStatusCode? StatusCode { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// The response headers to include in the response prelude. This collection supports setting single value for the same headers. | ||
| /// </summary> | ||
| public IDictionary<string, string> Headers { get; set; } = new Dictionary<string, string>(); | ||
|
|
||
| /// <summary> | ||
| /// The response headers to include in the response prelude. This collection supports setting multiple values for the same headers. | ||
| /// </summary> | ||
| public IDictionary<string, IList<string>> MultiValueHeaders { get; set; } = new Dictionary<string, IList<string>>(); | ||
|
|
||
| /// <summary> | ||
| /// The list of cookies to include in the response prelude. This is used for Lambda Function URL responses, which support a separate "cookies" field in the response JSON for setting cookies, rather than requiring cookies to be set via the "Set-Cookie" header. | ||
| /// </summary> | ||
| public IList<string> Cookies { get; set; } = new List<string>(); | ||
|
|
||
| internal byte[] ToByteArray() | ||
| { | ||
| var bufferWriter = new System.Buffers.ArrayBufferWriter<byte>(); | ||
| using (var writer = new Utf8JsonWriter(bufferWriter)) | ||
| { | ||
| writer.WriteStartObject(); | ||
|
|
||
| if (StatusCode.HasValue) | ||
| writer.WriteNumber("statusCode", (int)StatusCode); | ||
|
|
||
| if (Headers?.Count > 0) | ||
| { | ||
| writer.WriteStartObject("headers"); | ||
| foreach (var header in Headers) | ||
| { | ||
| writer.WriteString(header.Key, header.Value); | ||
| } | ||
| writer.WriteEndObject(); | ||
| } | ||
|
|
||
| if (MultiValueHeaders?.Count > 0) | ||
| { | ||
| writer.WriteStartObject("multiValueHeaders"); | ||
| foreach (var header in MultiValueHeaders) | ||
| { | ||
| writer.WriteStartArray(header.Key); | ||
| foreach (var value in header.Value) | ||
| { | ||
| writer.WriteStringValue(value); | ||
| } | ||
| writer.WriteEndArray(); | ||
| } | ||
| writer.WriteEndObject(); | ||
| } | ||
|
|
||
| if (Cookies?.Count > 0) | ||
| { | ||
| writer.WriteStartArray("cookies"); | ||
| foreach (var cookie in Cookies) | ||
| { | ||
| writer.WriteStringValue(cookie); | ||
| } | ||
| writer.WriteEndArray(); | ||
| } | ||
|
|
||
| writer.WriteEndObject(); | ||
| } | ||
|
|
||
| return bufferWriter.WrittenSpan.ToArray(); | ||
| } | ||
| } | ||
| } | ||
| #endif |
40 changes: 40 additions & 0 deletions
40
Libraries/src/Amazon.Lambda.Core/ResponseStreaming/ILambdaResponseStream.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,40 @@ | ||
| // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| #if NET8_0_OR_GREATER | ||
| using System; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace Amazon.Lambda.Core.ResponseStreaming | ||
| { | ||
| /// <summary> | ||
| /// Interface for writing streaming responses in AWS Lambda functions. | ||
| /// Obtained by calling <see cref="LambdaResponseStreamFactory.CreateStream"/> within a handler. | ||
| /// </summary> | ||
| internal interface ILambdaResponseStream : IDisposable | ||
| { | ||
| /// <summary> | ||
| /// Asynchronously writes a portion of a byte array to the response stream. | ||
| /// </summary> | ||
| /// <param name="buffer">The byte array containing data to write.</param> | ||
| /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes.</param> | ||
| /// <param name="count">The number of bytes to write.</param> | ||
| /// <param name="cancellationToken">Optional cancellation token.</param> | ||
| /// <returns>A task representing the asynchronous operation.</returns> | ||
| /// <exception cref="InvalidOperationException">Thrown if the stream is already completed or an error has been reported.</exception> | ||
| Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default); | ||
|
|
||
|
|
||
| /// <summary> | ||
| /// Gets the total number of bytes written to the stream so far. | ||
| /// </summary> | ||
| long BytesWritten { get; } | ||
|
|
||
|
|
||
| /// <summary> | ||
| /// Gets whether an error has been reported. | ||
| /// </summary> | ||
| bool HasError { get; } | ||
| } | ||
| } | ||
| #endif |
123 changes: 123 additions & 0 deletions
123
Libraries/src/Amazon.Lambda.Core/ResponseStreaming/LambdaResponseStream.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| #if NET8_0_OR_GREATER | ||
|
|
||
| using System; | ||
| using System.IO; | ||
| using System.Runtime.Versioning; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace Amazon.Lambda.Core.ResponseStreaming | ||
| { | ||
| /// <summary> | ||
| /// A write-only, non-seekable <see cref="Stream"/> subclass that streams response data | ||
| /// to the Lambda Runtime API. Returned by <see cref="LambdaResponseStreamFactory.CreateStream"/>. | ||
| /// Integrates with standard .NET stream consumers such as <see cref="System.IO.StreamWriter"/>. | ||
| /// </summary> | ||
| [RequiresPreviewFeatures(LambdaResponseStreamFactory.ParameterizedPreviewMessage)] | ||
| public class LambdaResponseStream : Stream | ||
| { | ||
| private readonly ILambdaResponseStream _responseStream; | ||
|
|
||
| internal LambdaResponseStream(ILambdaResponseStream responseStream) | ||
| { | ||
| _responseStream = responseStream; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// The number of bytes written to the Lambda response stream so far. | ||
| /// </summary> | ||
| public long BytesWritten => _responseStream.BytesWritten; | ||
|
|
||
| /// <summary> | ||
| /// Asynchronously writes a byte array to the response stream. | ||
| /// </summary> | ||
| /// <param name="buffer">The byte array to write.</param> | ||
| /// <param name="cancellationToken">Optional cancellation token.</param> | ||
| /// <returns>A task representing the asynchronous operation.</returns> | ||
| /// <exception cref="InvalidOperationException">Thrown if the stream is already completed or an error has been reported.</exception> | ||
| public async Task WriteAsync(byte[] buffer, CancellationToken cancellationToken = default) | ||
| { | ||
| if (buffer == null) | ||
| throw new ArgumentNullException(nameof(buffer)); | ||
|
|
||
| await WriteAsync(buffer, 0, buffer.Length, cancellationToken); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Asynchronously writes a portion of a byte array to the response stream. | ||
| /// </summary> | ||
| /// <param name="buffer">The byte array containing data to write.</param> | ||
| /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes.</param> | ||
| /// <param name="count">The number of bytes to write.</param> | ||
| /// <param name="cancellationToken">Optional cancellation token.</param> | ||
| /// <returns>A task representing the asynchronous operation.</returns> | ||
| /// <exception cref="InvalidOperationException">Thrown if the stream is already completed or an error has been reported.</exception> | ||
| public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default) | ||
| { | ||
| await _responseStream.WriteAsync(buffer, offset, count, cancellationToken); | ||
| } | ||
|
|
||
| #region Noop Overrides | ||
|
|
||
| /// <summary>Gets a value indicating whether the stream supports reading. Always <c>false</c>.</summary> | ||
| public override bool CanRead => false; | ||
|
|
||
| /// <summary>Gets a value indicating whether the stream supports seeking. Always <c>false</c>.</summary> | ||
| public override bool CanSeek => false; | ||
|
|
||
| /// <summary>Gets a value indicating whether the stream supports writing. Always <c>true</c>.</summary> | ||
| public override bool CanWrite => true; | ||
|
|
||
| /// <summary> | ||
| /// Gets the total number of bytes written to the stream so far. | ||
| /// Equivalent to <see cref="BytesWritten"/>. | ||
| /// </summary> | ||
| public override long Length => BytesWritten; | ||
|
|
||
| /// <summary> | ||
| /// Getting or setting the position is not supported. | ||
| /// </summary> | ||
| /// <exception cref="NotSupportedException">Always thrown.</exception> | ||
| public override long Position | ||
| { | ||
| get => throw new NotSupportedException("LambdaResponseStream does not support seeking."); | ||
| set => throw new NotSupportedException("LambdaResponseStream does not support seeking."); | ||
| } | ||
|
|
||
| /// <summary>Not supported.</summary> | ||
| /// <exception cref="NotImplementedException">Always thrown.</exception> | ||
| public override long Seek(long offset, SeekOrigin origin) | ||
| => throw new NotImplementedException("LambdaResponseStream does not support seeking."); | ||
|
|
||
| /// <summary>Not supported.</summary> | ||
| /// <exception cref="NotImplementedException">Always thrown.</exception> | ||
| public override int Read(byte[] buffer, int offset, int count) | ||
| => throw new NotImplementedException("LambdaResponseStream does not support reading."); | ||
|
|
||
| /// <summary>Not supported.</summary> | ||
| /// <exception cref="NotImplementedException">Always thrown.</exception> | ||
| public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) | ||
| => throw new NotImplementedException("LambdaResponseStream does not support reading."); | ||
|
|
||
| /// <summary> | ||
| /// Writes a sequence of bytes to the stream. Delegates to the async path synchronously. | ||
| /// Prefer <see cref="WriteAsync(byte[], int, int, CancellationToken)"/> to avoid blocking. | ||
| /// </summary> | ||
| public override void Write(byte[] buffer, int offset, int count) | ||
| => WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); | ||
|
|
||
| /// <summary> | ||
| /// Flush is a no-op; data is sent to the Runtime API immediately on each write. | ||
| /// </summary> | ||
| public override void Flush() { } | ||
|
|
||
| /// <summary>Not supported.</summary> | ||
| /// <exception cref="NotSupportedException">Always thrown.</exception> | ||
| public override void SetLength(long value) | ||
| => throw new NotSupportedException("LambdaResponseStream does not support SetLength."); | ||
| #endregion | ||
| } | ||
| } | ||
| #endif | ||
59 changes: 59 additions & 0 deletions
59
Libraries/src/Amazon.Lambda.Core/ResponseStreaming/LambdaResponseStreamFactory.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
| // SPDX-License-Identifier: Apache-2.0 | ||
| #if NET8_0_OR_GREATER | ||
| using System; | ||
| using System.IO; | ||
| using System.Runtime.Versioning; | ||
|
|
||
| namespace Amazon.Lambda.Core.ResponseStreaming | ||
| { | ||
| /// <summary> | ||
| /// Factory to create Lambda response streams for writing streaming responses in AWS Lambda functions. The created streams are write-only and non-seekable. | ||
| /// </summary> | ||
| [RequiresPreviewFeatures(LambdaResponseStreamFactory.ParameterizedPreviewMessage)] | ||
| public class LambdaResponseStreamFactory | ||
| { | ||
| internal const string ParameterizedPreviewMessage = | ||
| "Response streaming is in preview till a new version of .NET Lambda runtime client that supports response streaming " + | ||
| "has been deployed to the .NET Lambda managed runtime. Till deployment has been made the feature can be used by deploying as an " + | ||
| "executable including the latest version of Amazon.Lambda.RuntimeSupport and setting the \"EnablePreviewFeatures\" in the Lambda " + | ||
| "project file to \"true\""; | ||
|
|
||
| private static Func<byte[], ILambdaResponseStream> _streamFactory; | ||
|
|
||
| internal static void SetLambdaResponseStream(Func<byte[], ILambdaResponseStream> streamFactory) | ||
| { | ||
| _streamFactory = streamFactory ?? throw new ArgumentNullException(nameof(streamFactory)); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Creates a <see cref="Stream"/> that can be used to write streaming responses back to callers of the Lambda function. Once | ||
| /// a Lambda function creates a response stream all output must be returned by writing to the stream; the Lambda function's handler | ||
| /// return value will be ignored. The stream is write-only and non-seekable. | ||
| /// </summary> | ||
| /// <returns></returns> | ||
| public static Stream CreateStream() | ||
| { | ||
| var runtimeResponseStream = _streamFactory(Array.Empty<byte>()); | ||
| return new LambdaResponseStream(runtimeResponseStream); | ||
| } | ||
normj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| /// <summary> | ||
| /// Create a <see cref="Stream"/> for writing streaming responses, with an HTTP response prelude containing status code and headers. This should be used for | ||
| /// Lambda functions using response streaming that are invoked via the Lambda Function URLs or API Gateway HTTP APIs, where the response format is expected to be an HTTP response. | ||
| /// The prelude will be serialized and sent as the first chunk of the response stream, and should contain any necessary HTTP status code and headers. | ||
| /// <para> | ||
| /// Once a Lambda function creates a response stream all output must be returned by writing to the stream; the Lambda function's handler | ||
| /// return value will be ignored. The stream is write-only and non-seekable. | ||
| /// </para> | ||
| /// </summary> | ||
| /// <param name="prelude">The HTTP response prelude including status code and headers.</param> | ||
| /// <returns></returns> | ||
| public static Stream CreateHttpStream(HttpResponseStreamPrelude prelude) | ||
| { | ||
normj marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| var runtimeResponseStream = _streamFactory(prelude.ToByteArray()); | ||
| return new LambdaResponseStream(runtimeResponseStream); | ||
| } | ||
| } | ||
| } | ||
| #endif | ||
Oops, something went wrong.
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.