|
| 1 | +// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | +#if NET8_0_OR_GREATER |
| 4 | +using System; |
| 5 | +using System.IO; |
| 6 | +using System.Runtime.Versioning; |
| 7 | +using System.Threading; |
| 8 | +using System.Threading.Tasks; |
| 9 | + |
| 10 | +namespace Amazon.Lambda.Core |
| 11 | +{ |
| 12 | + /// <summary> |
| 13 | + /// Factory to create Lambda response streams for writing streaming responses in AWS Lambda functions. The created streams are write-only and non-seekable. |
| 14 | + /// </summary> |
| 15 | + [RequiresPreviewFeatures(LambdaResponseStreamFactory.ParameterizedPreviewMessage)] |
| 16 | + public class LambdaResponseStreamFactory |
| 17 | + { |
| 18 | + internal const string ParameterizedPreviewMessage = |
| 19 | + "Response streaming is in preview till a new version of .NET Lambda runtime client that supports response streaming " + |
| 20 | + "has been deployed to the .NET Lambda managed runtime. Till deployment has been made the feature can be used by deploying as an " + |
| 21 | + "executable including the latest version of Amazon.Lambda.RuntimeSupport and setting the \"EnablePreviewFeatures\" in the Lambda " + |
| 22 | + "project file to \"true\""; |
| 23 | + |
| 24 | + private static Func<byte[], ILambdaResponseStream> _streamFactory; |
| 25 | + |
| 26 | + internal static void SetLambdaResponseStream(Func<byte[], ILambdaResponseStream> streamFactory) |
| 27 | + { |
| 28 | + _streamFactory = streamFactory ?? throw new ArgumentNullException(nameof(streamFactory)); |
| 29 | + } |
| 30 | + |
| 31 | + /// <summary> |
| 32 | + /// Creates a <see cref="Stream"/> that can be used to write streaming responses back to callers of the Lambda function. Once |
| 33 | + /// A Lambda function creates a response stream all output must be returned by writing to the stream; the Lambda function's handler |
| 34 | + /// return value will be ignored. The stream is write-only and non-seekable. |
| 35 | + /// </summary> |
| 36 | + /// <returns></returns> |
| 37 | + public static Stream CreateStream() |
| 38 | + { |
| 39 | + var runtimeResponseStream = _streamFactory(Array.Empty<byte>()); |
| 40 | + return new LambdaResponseStream(runtimeResponseStream); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + /// <summary> |
| 45 | + /// Interface for writing streaming responses in AWS Lambda functions. |
| 46 | + /// Obtained by calling <see cref="LambdaResponseStreamFactory.CreateStream"/> within a handler. |
| 47 | + /// </summary> |
| 48 | + internal interface ILambdaResponseStream : IDisposable |
| 49 | + { |
| 50 | + /// <summary> |
| 51 | + /// Asynchronously writes a portion of a byte array to the response stream. |
| 52 | + /// </summary> |
| 53 | + /// <param name="buffer">The byte array containing data to write.</param> |
| 54 | + /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes.</param> |
| 55 | + /// <param name="count">The number of bytes to write.</param> |
| 56 | + /// <param name="cancellationToken">Optional cancellation token.</param> |
| 57 | + /// <returns>A task representing the asynchronous operation.</returns> |
| 58 | + /// <exception cref="InvalidOperationException">Thrown if the stream is already completed or an error has been reported.</exception> |
| 59 | + Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default); |
| 60 | + |
| 61 | + |
| 62 | + /// <summary> |
| 63 | + /// Gets the total number of bytes written to the stream so far. |
| 64 | + /// </summary> |
| 65 | + long BytesWritten { get; } |
| 66 | + |
| 67 | + |
| 68 | + /// <summary> |
| 69 | + /// Gets whether an error has been reported. |
| 70 | + /// </summary> |
| 71 | + bool HasError { get; } |
| 72 | + } |
| 73 | + |
| 74 | + /// <summary> |
| 75 | + /// A write-only, non-seekable <see cref="Stream"/> subclass that streams response data |
| 76 | + /// to the Lambda Runtime API. Returned by <see cref="LambdaResponseStreamFactory.CreateStream"/>. |
| 77 | + /// Integrates with standard .NET stream consumers such as <see cref="System.IO.StreamWriter"/>. |
| 78 | + /// </summary> |
| 79 | + [RequiresPreviewFeatures(LambdaResponseStreamFactory.ParameterizedPreviewMessage)] |
| 80 | + public class LambdaResponseStream : Stream |
| 81 | + { |
| 82 | + private readonly ILambdaResponseStream _responseStream; |
| 83 | + |
| 84 | + internal LambdaResponseStream(ILambdaResponseStream responseStream) |
| 85 | + { |
| 86 | + _responseStream = responseStream; |
| 87 | + } |
| 88 | + |
| 89 | + /// <summary> |
| 90 | + /// The number of bytes written to the Lambda response stream so far. |
| 91 | + /// </summary> |
| 92 | + public long BytesWritten => _responseStream.BytesWritten; |
| 93 | + |
| 94 | + /// <summary> |
| 95 | + /// Asynchronously writes a byte array to the response stream. |
| 96 | + /// </summary> |
| 97 | + /// <param name="buffer">The byte array to write.</param> |
| 98 | + /// <param name="cancellationToken">Optional cancellation token.</param> |
| 99 | + /// <returns>A task representing the asynchronous operation.</returns> |
| 100 | + /// <exception cref="InvalidOperationException">Thrown if the stream is already completed or an error has been reported.</exception> |
| 101 | + public async Task WriteAsync(byte[] buffer, CancellationToken cancellationToken = default) |
| 102 | + { |
| 103 | + if (buffer == null) |
| 104 | + throw new ArgumentNullException(nameof(buffer)); |
| 105 | + |
| 106 | + await WriteAsync(buffer, 0, buffer.Length, cancellationToken); |
| 107 | + } |
| 108 | + |
| 109 | + /// <summary> |
| 110 | + /// Asynchronously writes a portion of a byte array to the response stream. |
| 111 | + /// </summary> |
| 112 | + /// <param name="buffer">The byte array containing data to write.</param> |
| 113 | + /// <param name="offset">The zero-based byte offset in buffer at which to begin copying bytes.</param> |
| 114 | + /// <param name="count">The number of bytes to write.</param> |
| 115 | + /// <param name="cancellationToken">Optional cancellation token.</param> |
| 116 | + /// <returns>A task representing the asynchronous operation.</returns> |
| 117 | + /// <exception cref="InvalidOperationException">Thrown if the stream is already completed or an error has been reported.</exception> |
| 118 | + public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default) |
| 119 | + { |
| 120 | + await _responseStream.WriteAsync(buffer, offset, count, cancellationToken); |
| 121 | + } |
| 122 | + |
| 123 | + #region Noop Overrides |
| 124 | + |
| 125 | + /// <summary>Gets a value indicating whether the stream supports reading. Always <c>false</c>.</summary> |
| 126 | + public override bool CanRead => false; |
| 127 | + |
| 128 | + /// <summary>Gets a value indicating whether the stream supports seeking. Always <c>false</c>.</summary> |
| 129 | + public override bool CanSeek => false; |
| 130 | + |
| 131 | + /// <summary>Gets a value indicating whether the stream supports writing. Always <c>true</c>.</summary> |
| 132 | + public override bool CanWrite => true; |
| 133 | + |
| 134 | + /// <summary> |
| 135 | + /// Gets the total number of bytes written to the stream so far. |
| 136 | + /// Equivalent to <see cref="BytesWritten"/>. |
| 137 | + /// </summary> |
| 138 | + public override long Length => BytesWritten; |
| 139 | + |
| 140 | + /// <summary> |
| 141 | + /// Getting or setting the position is not supported. |
| 142 | + /// </summary> |
| 143 | + /// <exception cref="NotSupportedException">Always thrown.</exception> |
| 144 | + public override long Position |
| 145 | + { |
| 146 | + get => throw new NotSupportedException("LambdaResponseStream does not support seeking."); |
| 147 | + set => throw new NotSupportedException("LambdaResponseStream does not support seeking."); |
| 148 | + } |
| 149 | + |
| 150 | + /// <summary>Not supported.</summary> |
| 151 | + /// <exception cref="NotImplementedException">Always thrown.</exception> |
| 152 | + public override long Seek(long offset, SeekOrigin origin) |
| 153 | + => throw new NotImplementedException("LambdaResponseStream does not support seeking."); |
| 154 | + |
| 155 | + /// <summary>Not supported.</summary> |
| 156 | + /// <exception cref="NotImplementedException">Always thrown.</exception> |
| 157 | + public override int Read(byte[] buffer, int offset, int count) |
| 158 | + => throw new NotImplementedException("LambdaResponseStream does not support reading."); |
| 159 | + |
| 160 | + /// <summary>Not supported.</summary> |
| 161 | + /// <exception cref="NotImplementedException">Always thrown.</exception> |
| 162 | + public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) |
| 163 | + => throw new NotImplementedException("LambdaResponseStream does not support reading."); |
| 164 | + |
| 165 | + /// <summary> |
| 166 | + /// Writes a sequence of bytes to the stream. Delegates to the async path synchronously. |
| 167 | + /// Prefer <see cref="WriteAsync(byte[], int, int, CancellationToken)"/> to avoid blocking. |
| 168 | + /// </summary> |
| 169 | + public override void Write(byte[] buffer, int offset, int count) |
| 170 | + => WriteAsync(buffer, offset, count, CancellationToken.None).GetAwaiter().GetResult(); |
| 171 | + |
| 172 | + /// <summary> |
| 173 | + /// Flush is a no-op; data is sent to the Runtime API immediately on each write. |
| 174 | + /// </summary> |
| 175 | + public override void Flush() { } |
| 176 | + |
| 177 | + /// <summary>Not supported.</summary> |
| 178 | + /// <exception cref="NotSupportedException">Always thrown.</exception> |
| 179 | + public override void SetLength(long value) |
| 180 | + => throw new NotSupportedException("LambdaResponseStream does not support SetLength."); |
| 181 | + #endregion |
| 182 | + } |
| 183 | +} |
| 184 | +#endif |
0 commit comments