Skip to content

Add support for Lambda Response Streaming#2288

Merged
normj merged 54 commits into
feature/response-streamingfrom
normj/response-streaming
Apr 20, 2026
Merged

Add support for Lambda Response Streaming#2288
normj merged 54 commits into
feature/response-streamingfrom
normj/response-streaming

Conversation

@normj
Copy link
Copy Markdown
Member

@normj normj commented Feb 19, 2026

Issue #, if available:
#1635

Description of changes:
Integrate Lambda response streaming support into the Amazon.Lambda.RuntimeSupport.

A hello world example of using response streaming. In this case sense I wrapped the Stream returned from CreateStream in a StreamWriter the writes will be buffered in StreamWriter till the buffer is full. I call the flush method every 10 iterations to force sending data back to the client.

using Amazon.Lambda.Core;
using Amazon.Lambda.Core.ResponseStreaming;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.SystemTextJson;

#pragma warning disable CA2252

// The function handler that will be called for each Lambda event
var handler = async (string input, ILambdaContext context) =>
{
    using var responseStream = LambdaResponseStreamFactory.CreateStream();

    using var writer = new StreamWriter(responseStream);
    for (var i = 1; i <= 100; i++)
    {
        var message = $"Hello {input} - {i}";
        await writer.WriteLineAsync(message);

        if (i % 10 == 0)
        {
            await writer.FlushAsync();
            await Task.Delay(1000);
        }
    }
};

// Build the Lambda runtime client passing in the handler to call for each
// event and the JSON serializer to use for translating Lambda JSON documents
// to .NET types.
await LambdaBootstrapBuilder.Create(handler, new DefaultLambdaJsonSerializer())
        .Build()
        .RunAsync();

For a use with API Gateway or Lambda Function URL you need to create the stream with the CreateHttpStream passing the status code and response headers.

using Amazon.Lambda.APIGatewayEvents;
using Amazon.Lambda.Core;
using Amazon.Lambda.Core.ResponseStreaming;
using Amazon.Lambda.RuntimeSupport;
using Amazon.Lambda.Serialization.SystemTextJson;
using System.Net;

#pragma warning disable CA2252

// The function handler that will be called for each Lambda event
var handler = async (APIGatewayProxyRequest request, ILambdaContext context) =>
{
    var prelude = new HttpResponseStreamPrelude
    {
        StatusCode = HttpStatusCode.OK,
        Headers =
        {
            { "Content-Type", "text/plain" }
        }
    };
   
    using var responseStream = LambdaResponseStreamFactory.CreateHttpStream(prelude);

    using var writer = new StreamWriter(responseStream);
    for (var i = 1; i <= 10000000; i++)
    {
        var message = $"Hello - {i} ({responseStream.Length.ToString("N0")}) (Remaining Time: {context.RemainingTime})";
        await writer.WriteLineAsync(message);

        if (i % 100 == 0)
        {
            await writer.FlushAsync();
        }

        if (context.RemainingTime < TimeSpan.FromSeconds(5))
        {
            await writer.WriteLineAsync("Approaching Lambda timeout, stopping the stream.");
            await writer.FlushAsync();
            break;
        }
    }
};

// Build the Lambda runtime client passing in the handler to call for each
// event and the JSON serializer to use for translating Lambda JSON documents
// to .NET types.
await LambdaBootstrapBuilder.Create(handler, new DefaultLambdaJsonSerializer())
        .Build()
        .RunAsync();

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

@normj normj marked this pull request as draft February 19, 2026 01:50
@normj normj changed the base branch from dev to feature/response-streaming March 10, 2026 23:49
@normj normj marked this pull request as ready for review March 11, 2026 18:25
@normj normj marked this pull request as draft March 11, 2026 18:26
@normj normj force-pushed the normj/response-streaming branch from 2ed63cc to d60bb93 Compare March 11, 2026 20:10
@normj normj force-pushed the normj/response-streaming branch from 96dc138 to 0bd63a9 Compare March 12, 2026 03:03
GarrettBeatty and others added 14 commits April 8, 2026 13:10
* release_2026-04-08

* Update test app CloudFormation templates

* Updated changelog
* Add [S3Event] annotation attribute and source generator support

- S3EventAttribute with Bucket (required), ResourceName, Events, FilterPrefix, FilterSuffix, Enabled
- S3EventAttributeBuilder for Roslyn AttributeData parsing
- TypeFullNames constants and Events hashset registration
- SyntaxReceiver secondary attribute registration
- EventTypeBuilder S3 event type mapping
- AttributeModelBuilder S3 branch
- CloudFormationWriter ProcessS3Attribute (SAM S3 event with Ref, Events list, Filter rules)
- LambdaFunctionValidator ValidateS3Events (params, return type, dependency check)
- DiagnosticDescriptors InvalidS3EventAttribute (AWSLambda0133)

Add S3Event annotation tests

- ValidS3Events.cs.txt test source with 3 test functions
- S3EventsTests.cs CloudFormation writer tests (attribute application + property sync)
- S3Events project references in TestServerlessApp.csproj and test project

IT test

PR comments

change file

fixes

PR comments

* add header
* treat warnings as errors

* Change file
* chore: improve test flakiness

* update changelog
…enerator (#2324)

* Phase 1: Add FunctionUrlAttribute with source generator wiring and CloudFormation FunctionUrlConfig generation

- New FunctionUrlAttribute class with AuthType property (NONE/AWS_IAM)
- New FunctionUrlAuthType enum
- Source generator detects FunctionUrlAttribute and maps to EventType.API
- Generated wrapper uses HttpApi V2 request/response types (same payload format)
- CloudFormationWriter emits FunctionUrlConfig on the function resource
- Dependency validation checks for Amazon.Lambda.APIGatewayEvents
- SyntaxReceiver detects missing [LambdaFunction] on [FunctionUrl] methods
- 6 new unit tests for CloudFormation template generation (JSON + YAML)

Phase 2: Add CORS support to FunctionUrlAttribute

- AllowOrigins, AllowMethods, AllowHeaders, ExposeHeaders, AllowCredentials, MaxAge properties
- FunctionUrlAttributeBuilder parses all CORS properties from AttributeData
- CloudFormationWriter emits Cors block under FunctionUrlConfig only when CORS properties are set
- 4 new unit tests for CORS generation and no-CORS scenarios

Phase 3: FunctionUrlConfig orphan cleanup and attribute switching

- Remove FunctionUrlConfig from template when [FunctionUrl] attribute is removed
- Clean transition when switching from [FunctionUrl] to [HttpApi] or [RestApi]
- 4 new unit tests for orphan cleanup and attribute switching scenarios

Phase 4: End-to-end source generator test for FunctionUrl

- FunctionUrlExample.cs test source with [FunctionUrl] + [FromQuery] + IHttpResult
- Generated wrapper snapshot using HttpApi V2 payload format
- Serverless template snapshot with FunctionUrlConfig
- Full Roslyn source generator verification test

IT tests

Update Libraries/src/Amazon.Lambda.Annotations.SourceGenerator/Models/Attributes/FunctionUrlAttributeBuilder.cs

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>

copilot comments

change file

fix cleanup

add header

PR comments

* fix template

* fix test
* release_2026-04-14

* Update test app CloudFormation templates

* Updated changelog
* Add CODEOWNERS file

* Add [SNSEvent] annotation attribute and source generator support

- SNSEventAttribute with Topic, ResourceName, FilterPolicy, Enabled
- SNSEventAttributeBuilder for Roslyn AttributeData parsing
- Source generator wiring (TypeFullNames, SyntaxReceiver, EventTypeBuilder, AttributeModelBuilder)
- CloudFormationWriter ProcessSNSAttribute (SAM SNS event subscription)
- LambdaFunctionValidator ValidateSNSEvents
- DiagnosticDescriptors InvalidSNSEventAttribute
- SNSEventAttributeTests (attribute unit tests)
- SNSEventsTests (CloudFormation writer tests)
- E2E source generator snapshot tests
- Integration test (SNSEventSubscription)
- Sample function (SnsMessageProcessing)
- .autover change file
- README documentation

pr comments

fix tests

fix tests

fix tests

* add header

---------

Co-authored-by: AlexDaines <55813219+AlexDaines@users.noreply.github.com>
* release_2026-04-16

* Update test app CloudFormation templates

* Updated changelog
@normj normj merged commit f63fec7 into feature/response-streaming Apr 20, 2026
13 of 14 checks passed
@normj normj deleted the normj/response-streaming branch April 20, 2026 22:41
GarrettBeatty pushed a commit that referenced this pull request May 6, 2026
* Task 1

* Task 2

* Task 3

* Add support for Lambda Response Streaming (#2288)

* Remove out of support build targets and fix all compiler warnings.
@normj normj mentioned this pull request May 7, 2026
2 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants