Skip to content
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

WIP: Change response type to Stream when Lambda function uses APIGateway events #1746

Closed
wants to merge 6 commits into from
Closed
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 @@ -48,6 +48,10 @@
<Generator>TextTemplatingFilePreprocessor</Generator>
<LastGenOutput>FieldsAndConstructor.cs</LastGenOutput>
</None>
<None Update="Templates\JsonSerializerContextTemplate.tt">
<Generator>TextTemplatingFilePreprocessor</Generator>
<LastGenOutput>JsonSerializerContextTemplate.cs</LastGenOutput>
</None>
<None Update="Templates\LambdaFunctionTemplate.tt">
<Generator>TextTemplatingFilePreprocessor</Generator>
<LastGenOutput>LambdaFunctionTemplate.cs</LastGenOutput>
Expand Down Expand Up @@ -78,6 +82,11 @@
<AutoGen>True</AutoGen>
<DependentUpon>FieldsAndConstructor.tt</DependentUpon>
</Compile>
<Compile Update="Templates\JsonSerializerContextTemplate.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>JsonSerializerContextTemplate.tt</DependentUpon>
</Compile>
<Compile Update="Templates\LambdaFunctionTemplate.cs">
<DependentUpon>LambdaFunctionTemplate.tt</DependentUpon>
<DesignTime>True</DesignTime>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;

Expand Down Expand Up @@ -50,16 +52,17 @@ public class Generator : ISourceGenerator
public Generator()
{
#if DEBUG
// if (!Debugger.IsAttached)
// {
// Debugger.Launch();
// }
//if (!Debugger.IsAttached)
//{
// Debugger.Launch();
//}
#endif
}

public void Execute(GeneratorExecutionContext context)
{
var diagnosticReporter = new DiagnosticReporter(context);
var sourceGeneratedSerializableTypes = new HashSet<string>();

try
{
Expand Down Expand Up @@ -225,12 +228,18 @@ public void Execute(GeneratorExecutionContext context)
continue;
}


var template = new LambdaFunctionTemplate(model);

string sourceText;
try
{
sourceText = template.TransformText().ToEnvironmentLineEndings();
var filePath = $"C:\\codebase\\V3\\snapshots\\{model.GeneratedMethod.ContainingType.Name}.g.cs";
using (StreamWriter writer = new StreamWriter(filePath))
{
writer.Write(sourceText);
}
Comment on lines +238 to +242
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This was my hack to update the snapshots quickly. Ignore this for now.

context.AddSource($"{model.GeneratedMethod.ContainingType.Name}.g.cs", SourceText.From(sourceText, Encoding.UTF8, SourceHashAlgorithm.Sha256));
}
catch (Exception e) when (e is NotSupportedException || e is InvalidOperationException)
Expand All @@ -242,10 +251,20 @@ public void Execute(GeneratorExecutionContext context)
// report every generated file to build output
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.CodeGeneration, Location.None, $"{model.GeneratedMethod.ContainingType.Name}.g.cs", sourceText));

AddSourceGeneratedSerializableTypes(sourceGeneratedSerializableTypes, model);
lambdaModels.Add(model);
annotationReport.LambdaFunctions.Add(model);
}

if (sourceGeneratedSerializableTypes.Any())
{
var jsonSerializerContextTemplate = new JsonSerializerContextTemplate(context.Compilation.AssemblyName, sourceGeneratedSerializableTypes);
var sourceText = jsonSerializerContextTemplate.TransformText().ToEnvironmentLineEndings();
context.AddSource("ApiGatewayResponseJsonSerializerContext.g.cs", SourceText.From(sourceText, Encoding.UTF8, SourceHashAlgorithm.Sha256));
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.CodeGeneration, Location.None, "ApiGatewayResponseJsonSerializerContext.g.cs", sourceText));
Execute(context);
}

if (isExecutable)
{
var executableAssembly = GenerateExecutableAssemblySource(
Expand Down Expand Up @@ -297,6 +316,25 @@ public void Execute(GeneratorExecutionContext context)
}
}

private static void AddSourceGeneratedSerializableTypes(HashSet<string> sourceGeneratedSerializableTypes, LambdaFunctionModel model)
{
var restApiAttribute = model.LambdaMethod.Attributes.FirstOrDefault(att => att.Type.FullName == TypeFullNames.RestApiAttribute) as AttributeModel<APIGateway.RestApiAttribute>;
var httpApiAttribute = model.LambdaMethod.Attributes.FirstOrDefault(att => att.Type.FullName == TypeFullNames.HttpApiAttribute) as AttributeModel<APIGateway.HttpApiAttribute>;

if (restApiAttribute is null && httpApiAttribute is null)
{
return;
}
if (model.LambdaMethod.ReturnsIHttpResults)
{
return;
}

var useHttpV2Response = httpApiAttribute?.Data.Version == APIGateway.HttpApiVersion.V2;
var apiGatewayResponseType = useHttpV2Response ? TypeFullNames.APIGatewayHttpApiV2ProxyResponse : TypeFullNames.APIGatewayProxyResponse;
sourceGeneratedSerializableTypes.Add(apiGatewayResponseType);
}

private static ExecutableAssembly GenerateExecutableAssemblySource(
GeneratorExecutionContext context,
DiagnosticReporter diagnosticReporter,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,61 +53,44 @@ private static IList<string> BuildUsings(LambdaMethodModel lambdaMethodModel,
{
namespaces.Add("Amazon.Lambda.Annotations.APIGateway");
}
if (lambdaMethodModel.Events.Contains(EventType.API))
{
namespaces.Add("System.Text.Json");
}

return namespaces;
}

private static TypeModel BuildResponseType(IMethodSymbol lambdaMethodSymbol,
LambdaMethodModel lambdaMethodModel, GeneratorExecutionContext context)
{
var task = context.Compilation.GetTypeByMetadataName(TypeFullNames.Task1);

if (lambdaMethodModel.ReturnsIHttpResults)
{
var typeStream = context.Compilation.GetTypeByMetadataName(TypeFullNames.Stream);
if (lambdaMethodModel.ReturnsGenericTask)
{
var genericTask = task.Construct(typeStream);
return TypeModelBuilder.Build(genericTask, context);
}
return TypeModelBuilder.Build(typeStream, context);
}


if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.RestApiAttribute))
if (lambdaMethodModel.Events.Contains(EventType.API))
{
var symbol = lambdaMethodModel.ReturnsVoidOrGenericTask ?
task.Construct(context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyResponse)):
context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyResponse);
return TypeModelBuilder.Build(symbol, context);
}
else if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.HttpApiAttribute))
{
var version = GetHttpApiVersion(lambdaMethodSymbol, context);
switch (version)
if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.HttpApiAttribute))
{
case HttpApiVersion.V1:
var version = GetHttpApiVersion(lambdaMethodSymbol, context);
if (version != HttpApiVersion.V1 && version != HttpApiVersion.V2)
{
var symbol = lambdaMethodModel.ReturnsVoidOrGenericTask ?
task.Construct(context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyResponse)):
context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyResponse);
return TypeModelBuilder.Build(symbol, context);
}
case HttpApiVersion.V2:
{
var symbol = lambdaMethodModel.ReturnsVoidOrGenericTask ?
task.Construct(context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayHttpApiV2ProxyResponse)):
context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayHttpApiV2ProxyResponse);
return TypeModelBuilder.Build(symbol, context);
}
default:
throw new ArgumentOutOfRangeException();
};
}

return CreateStreamTypeModel(context, lambdaMethodModel);
}
else

return lambdaMethodModel.ReturnType;
}

private static TypeModel CreateStreamTypeModel(GeneratorExecutionContext context, LambdaMethodModel lambdaMethodModel)
{
var task = context.Compilation.GetTypeByMetadataName(TypeFullNames.Task1);
var typeStream = context.Compilation.GetTypeByMetadataName(TypeFullNames.Stream);
if (lambdaMethodModel.ReturnsVoidOrGenericTask)
{
return lambdaMethodModel.ReturnType;
var genericTask = task.Construct(typeStream);
return TypeModelBuilder.Build(genericTask, context);
}
return TypeModelBuilder.Build(typeStream, context);
}

private static HttpApiVersion GetHttpApiVersion(IMethodSymbol lambdaMethodSymbol, GeneratorExecutionContext context)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,34 @@ public bool ReturnsIHttpResults
{
return true;
}
if(ReturnsGenericTask && ReturnType.TypeArguments.Count == 1 && ReturnType.TypeArguments[0].FullName == TypeFullNames.IHttpResult)

return ReturnsGenericTask && ReturnType.TypeArguments.Count == 1 && ReturnType.TypeArguments[0].FullName == TypeFullNames.IHttpResult;
}
}

/// <summary>
/// Returns true if the Lambda function returns either of the following types
/// 1. APIGatewayProxyResponse or Task<APIGatewayProxyResponse>
/// 2. APIGatewayHttpApiV2ProxyResponse or Task<APIGatewayHttpApiV2ProxyResponse>
/// </summary>
public bool ReturnsApiGatewayResponse
{
get
{
if(ReturnsVoid)
{
return true;
return false;
}

if(ReturnType.FullName == TypeFullNames.APIGatewayProxyResponse || ReturnType.FullName == TypeFullNames.APIGatewayHttpApiV2ProxyResponse)
{
return true;
}
if(ReturnsGenericTask && ReturnType.TypeArguments.Count == 1)
{
return ReturnType.TypeArguments[0].FullName == TypeFullNames.APIGatewayProxyResponse
|| ReturnType.TypeArguments[0].FullName == TypeFullNames.APIGatewayHttpApiV2ProxyResponse;
}

return false;
}
Expand Down
Loading
Loading