Skip to content

Fix issue with Source generator for Lambda functions that return void #1257

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

Merged
merged 1 commit into from
Aug 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,14 @@ public class LambdaMethodModel
public bool IsAsync { get; set; }

/// <summary>
/// Returns true if original method returns void or <see cref="System.Threading.Tasks.Task"/>
/// Returns true if original method returns void
/// </summary>
public bool ReturnsVoidOrTask { get; set; }
public bool ReturnsVoid { get; set; }

/// <summary>
/// Returns true if original method returns <see cref="System.Threading.Tasks.Task"/>
/// </summary>
public bool ReturnsTask { get; set; }

/// <summary>
/// Gets or sets the return type of the method.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ public static LambdaMethodModel Build(IMethodSymbol lambdaMethodSymbol,
{
IsAsync = lambdaMethodSymbol.IsAsync,
ReturnType = TypeModelBuilder.Build(lambdaMethodSymbol.ReturnType, context),
ReturnsVoidOrTask = lambdaMethodSymbol.ReturnsVoid || lambdaMethodSymbol.ReturnType.Equals(context.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task"), SymbolEqualityComparer.Default),
ReturnsVoid = lambdaMethodSymbol.ReturnsVoid,
ReturnsTask = lambdaMethodSymbol.ReturnType.Equals(context.Compilation.GetTypeByMetadataName("System.Threading.Tasks.Task"), SymbolEqualityComparer.Default),
Parameters = ParameterModelBuilder.Build(lambdaMethodSymbol, context),
Name = lambdaMethodSymbol.Name,
ContainingAssembly = lambdaMethodSymbol.ContainingAssembly.Name,
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -368,10 +368,16 @@ namespace <#= _model.LambdaMethod.ContainingNamespace #>
<#
}

if (_model.LambdaMethod.ReturnsVoidOrTask)
if (_model.LambdaMethod.ReturnsVoid)
{
#>
<#= _model.LambdaMethod.IsAsync ? "await " : "" #><#= _model.LambdaMethod.ContainingType.Name.ToCamelCase() #>.<#= _model.LambdaMethod.Name #>(<#= parameters #>);
<#= _model.LambdaMethod.ContainingType.Name.ToCamelCase() #>.<#= _model.LambdaMethod.Name #>(<#= parameters #>);
<#
}
else if (_model.LambdaMethod.ReturnsTask)
{
#>
await <#= _model.LambdaMethod.ContainingType.Name.ToCamelCase() #>.<#= _model.LambdaMethod.Name #>(<#= parameters #>);
<#
}
else
Expand All @@ -389,7 +395,7 @@ namespace <#= _model.LambdaMethod.ContainingNamespace #>
}
else
{
if (!_model.LambdaMethod.ReturnsVoidOrTask)
if (!_model.LambdaMethod.ReturnsVoid && !_model.LambdaMethod.ReturnsTask)
{
if (_model.LambdaMethod.ReturnType.IsValueType)
{
Expand All @@ -415,7 +421,7 @@ namespace <#= _model.LambdaMethod.ContainingNamespace #>
return new <#= _model.LambdaMethod.IsAsync ? _model.GeneratedMethod.ReturnType.TaskTypeArgument : _model.GeneratedMethod.ReturnType.FullName #>
{
<#
if (!_model.LambdaMethod.ReturnsVoidOrTask)
if (!_model.LambdaMethod.ReturnsVoid && !_model.LambdaMethod.ReturnsTask)
{
#>
Body = <#= _model.LambdaMethod.ReturnType.IsString() ? "response" : "body" #>,
Expand Down Expand Up @@ -455,10 +461,16 @@ namespace <#= _model.LambdaMethod.ContainingNamespace #>
}
}

if (_model.LambdaMethod.ReturnsVoidOrTask)
if (_model.LambdaMethod.ReturnsVoid)
{
#>
return <#= _model.LambdaMethod.IsAsync ? "await " : "" #><#= _model.LambdaMethod.ContainingType.Name.ToCamelCase() #>.<#= _model.LambdaMethod.Name #>(<#= parameters #>);
<#= _model.LambdaMethod.ContainingType.Name.ToCamelCase() #>.<#= _model.LambdaMethod.Name #>(<#= parameters #>);
<#
}
else if (_model.LambdaMethod.ReturnsTask)
{
#>
return await <#= _model.LambdaMethod.ContainingType.Name.ToCamelCase() #>.<#= _model.LambdaMethod.Name #>(<#= parameters #>);
<#
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@

<ItemGroup>
<None Remove="Snapshots\ServerlessTemplates\subnamespace.template" />
<None Remove="Snapshots\ServerlessTemplates\voidexample.template" />
</ItemGroup>

<ItemGroup>
Expand All @@ -73,5 +74,11 @@
<ProjectReference Include="..\..\src\Amazon.Lambda.Serialization.SystemTextJson\Amazon.Lambda.Serialization.SystemTextJson.csproj" />
</ItemGroup>

<ItemGroup>
<Content Update="Snapshots\VoidExample_VoidReturn_Generated.g.cs">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
</ItemGroup>


</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
{
"AWSTemplateFormatVersion": "2010-09-09",
"Transform": "AWS::Serverless-2016-10-31",
"Resources": {
"TestServerlessAppVoidExampleVoidReturnGenerated": {
"Type": "AWS::Serverless::Function",
"Metadata": {
"Tool": "Amazon.Lambda.Annotations"
},
"Properties": {
"MemorySize": 256,
"Timeout": 30,
"Policies": [
"AWSLambdaBasicExecutionRole"
],
"PackageType": "Image",
"ImageUri": ".",
"ImageConfig": {
"Command": [
"TestProject::TestServerlessApp.VoidExample_VoidReturn_Generated::VoidReturn"
]
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Amazon.Lambda.Core;

namespace TestServerlessApp
{
public class VoidExample_VoidReturn_Generated
{
private readonly VoidExample voidExample;

public VoidExample_VoidReturn_Generated()
{
SetExecutionEnvironment();
voidExample = new VoidExample();
}

public void VoidReturn(string text, Amazon.Lambda.Core.ILambdaContext __context__)
{
voidExample.VoidReturn(text, __context__);
}

private static void SetExecutionEnvironment()
{
const string envName = "AWS_EXECUTION_ENV";

var envValue = new StringBuilder();

// If there is an existing execution environment variable add the annotations package as a suffix.
if(!string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)))
{
envValue.Append($"{Environment.GetEnvironmentVariable(envName)}_");
}

envValue.Append("amazon-lambda-annotations_0.5.1.0");

Environment.SetEnvironmentVariable(envName, envValue.ToString());
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -216,5 +216,41 @@ public async Task VerifyFunctionInSubNamespace()
var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}

[Fact]
public async Task VerifyFunctionReturnVoid()
{
var expectedTemplateContent = File.ReadAllText(Path.Combine("Snapshots", "ServerlessTemplates", "voidexample.template")).ToEnvironmentLineEndings();
var expectedSubNamespaceGenerated = File.ReadAllText(Path.Combine("Snapshots", "VoidExample_VoidReturn_Generated.g.cs")).ToEnvironmentLineEndings();

await new VerifyCS.Test
{
TestState =
{
Sources =
{
(Path.Combine("TestServerlessApp", "VoidExample.cs"), File.ReadAllText(Path.Combine("TestServerlessApp", "VoidExample.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaFunctionAttribute.cs"))),
(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"), File.ReadAllText(Path.Combine("Amazon.Lambda.Annotations", "LambdaStartupAttribute.cs"))),
},
GeneratedSources =
{
(
typeof(SourceGenerator.Generator),
"VoidExample_VoidReturn_Generated.g.cs",
SourceText.From(expectedSubNamespaceGenerated, Encoding.UTF8, SourceHashAlgorithm.Sha256)
)
},
ExpectedDiagnostics =
{
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments("VoidExample_VoidReturn_Generated.g.cs", expectedSubNamespaceGenerated),
new DiagnosticResult("AWSLambda0103", DiagnosticSeverity.Info).WithArguments($"TestServerlessApp{Path.DirectorySeparatorChar}serverless.template", expectedTemplateContent)
}
}
}.RunAsync();

var actualTemplateContent = File.ReadAllText(Path.Combine("TestServerlessApp", "serverless.template"));
Assert.Equal(expectedTemplateContent, actualTemplateContent);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ public async Task InitializeAsync()

Assert.Equal(StackStatus.CREATE_COMPLETE, await _cloudFormationHelper.GetStackStatusAsync(_stackName));
Assert.True(await _s3Helper.BucketExistsAsync(_bucketName));
Assert.Equal(12, LambdaFunctions.Count);
Assert.Equal(13, LambdaFunctions.Count);
Assert.False(string.IsNullOrEmpty(RestApiUrlPrefix));
Assert.False(string.IsNullOrEmpty(RestApiUrlPrefix));

Expand Down
14 changes: 14 additions & 0 deletions Libraries/test/TestServerlessApp/VoidExample.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
using Amazon.Lambda.Annotations;
using Amazon.Lambda.Core;

namespace TestServerlessApp
{
public class VoidExample
{
[LambdaFunction(PackageType = LambdaPackageType.Image)]
public void VoidReturn(string text, ILambdaContext context)
{
context.Logger.LogLine(text);
}
}
}
20 changes: 20 additions & 0 deletions Libraries/test/TestServerlessApp/serverless.template
Original file line number Diff line number Diff line change
Expand Up @@ -367,6 +367,26 @@
]
}
}
},
"TestServerlessAppVoidExampleVoidReturnGenerated": {
"Type": "AWS::Serverless::Function",
"Metadata": {
"Tool": "Amazon.Lambda.Annotations"
},
"Properties": {
"MemorySize": 256,
"Timeout": 30,
"Policies": [
"AWSLambdaBasicExecutionRole"
],
"PackageType": "Image",
"ImageUri": ".",
"ImageConfig": {
"Command": [
"TestServerlessApp::TestServerlessApp.VoidExample_VoidReturn_Generated::VoidReturn"
]
}
}
}
},
"Outputs": {
Expand Down