Skip to content
Draft
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 @@ -242,5 +242,12 @@ public static class DiagnosticDescriptors
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);

public static readonly DiagnosticDescriptor InvalidDynamoDBEventAttribute = new DiagnosticDescriptor(id: "AWSLambda0132",
title: "Invalid DynamoDBEventAttribute",
messageFormat: "Invalid DynamoDBEventAttribute encountered: {0}",
category: "AWSLambdaCSharpGenerator",
DiagnosticSeverity.Error,
isEnabledByDefault: true);
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.Annotations.DynamoDB;
using Amazon.Lambda.Annotations.SQS;
using Microsoft.CodeAnalysis;

Expand Down Expand Up @@ -90,6 +91,15 @@ public static AttributeModel Build(AttributeData att, GeneratorExecutionContext
Type = TypeModelBuilder.Build(att.AttributeClass, context)
};
}
else if (att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.DynamoDBEventAttribute), SymbolEqualityComparer.Default))
{
var data = DynamoDBEventAttributeBuilder.Build(att);
model = new AttributeModel<DynamoDBEventAttribute>
{
Data = data,
Type = TypeModelBuilder.Build(att.AttributeClass, context)
};
}
else if (att.AttributeClass.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.HttpApiAuthorizerAttribute), SymbolEqualityComparer.Default))
{
var data = HttpApiAuthorizerAttributeBuilder.Build(att);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
using Amazon.Lambda.Annotations.DynamoDB;
using Microsoft.CodeAnalysis;
using System;

namespace Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes
{
/// <summary>
/// Builder for <see cref="DynamoDBEventAttribute"/>.
/// </summary>
public class DynamoDBEventAttributeBuilder
{
public static DynamoDBEventAttribute Build(AttributeData att)
{
if (att.ConstructorArguments.Length != 1)
{
throw new NotSupportedException($"{TypeFullNames.DynamoDBEventAttribute} must have constructor with 1 argument.");
}
var stream = att.ConstructorArguments[0].Value as string;
var data = new DynamoDBEventAttribute(stream);

foreach (var pair in att.NamedArguments)
{
if (pair.Key == nameof(data.ResourceName) && pair.Value.Value is string resourceName)
{
data.ResourceName = resourceName;
}
if (pair.Key == nameof(data.BatchSize) && pair.Value.Value is uint batchSize)
{
data.BatchSize = batchSize;
}
else if (pair.Key == nameof(data.StartingPosition) && pair.Value.Value is string startingPosition)
{
data.StartingPosition = startingPosition;
}
else if (pair.Key == nameof(data.Enabled) && pair.Value.Value is bool enabled)
{
data.Enabled = enabled;
}
else if (pair.Key == nameof(data.MaximumBatchingWindowInSeconds) && pair.Value.Value is uint maximumBatchingWindowInSeconds)
{
data.MaximumBatchingWindowInSeconds = maximumBatchingWindowInSeconds;
}
else if (pair.Key == nameof(data.Filters) && pair.Value.Value is string filters)
{
data.Filters = filters;
}
}

return data;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,10 @@ public static HashSet<EventType> Build(IMethodSymbol lambdaMethodSymbol,
{
events.Add(EventType.SQS);
}
else if (attribute.AttributeClass.ToDisplayString() == TypeFullNames.DynamoDBEventAttribute)
{
events.Add(EventType.DynamoDB);
}
else if (attribute.AttributeClass.ToDisplayString() == TypeFullNames.HttpApiAuthorizerAttribute
|| attribute.AttributeClass.ToDisplayString() == TypeFullNames.RestApiAuthorizerAttribute)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ internal class SyntaxReceiver : ISyntaxContextReceiver
{ "RestApiAuthorizerAttribute", "RestApiAuthorizer" },
{ "HttpApiAttribute", "HttpApi" },
{ "RestApiAttribute", "RestApi" },
{ "SQSEventAttribute", "SQSEvent" }
{ "SQSEventAttribute", "SQSEvent" },
{ "DynamoDBEventAttribute", "DynamoDBEvent" }
};

public List<MethodDeclarationSyntax> LambdaMethods { get; } = new List<MethodDeclarationSyntax>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ public static class TypeFullNames
public const string SQSBatchResponse = "Amazon.Lambda.SQSEvents.SQSBatchResponse";
public const string SQSEventAttribute = "Amazon.Lambda.Annotations.SQS.SQSEventAttribute";

public const string DynamoDBEvent = "Amazon.Lambda.DynamoDBEvents.DynamoDBEvent";
public const string DynamoDBEventAttribute = "Amazon.Lambda.Annotations.DynamoDB.DynamoDBEventAttribute";

public const string LambdaSerializerAttribute = "Amazon.Lambda.Core.LambdaSerializerAttribute";
public const string DefaultLambdaSerializer = "Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer";

Expand All @@ -67,7 +70,8 @@ public static class TypeFullNames
{
RestApiAttribute,
HttpApiAttribute,
SQSEventAttribute
SQSEventAttribute,
DynamoDBEventAttribute
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using Amazon.Lambda.Annotations.SourceGenerator.Models;
using Amazon.Lambda.Annotations.SourceGenerator.Models.Attributes;
using Amazon.Lambda.Annotations.DynamoDB;
using Amazon.Lambda.Annotations.SQS;
using Microsoft.CodeAnalysis;
using System.Collections.Generic;
Expand Down Expand Up @@ -59,6 +60,7 @@ internal static bool ValidateFunction(GeneratorExecutionContext context, IMethod
// Validate Events
ValidateApiGatewayEvents(lambdaFunctionModel, methodLocation, diagnostics);
ValidateSqsEvents(lambdaFunctionModel, methodLocation, diagnostics);
ValidateDynamoDBEvents(lambdaFunctionModel, methodLocation, diagnostics);

return ReportDiagnostics(diagnosticReporter, diagnostics);
}
Expand Down Expand Up @@ -86,6 +88,16 @@ internal static bool ValidateDependencies(GeneratorExecutionContext context, IMe
}
}

// Check for references to "Amazon.Lambda.DynamoDBEvents" if the Lambda method is annotated with DynamoDBEvent attribute.
if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.DynamoDBEventAttribute))
{
if (context.Compilation.ReferencedAssemblyNames.FirstOrDefault(x => x.Name == "Amazon.Lambda.DynamoDBEvents") == null)
{
diagnosticReporter.Report(Diagnostic.Create(DiagnosticDescriptors.MissingDependencies, methodLocation, "Amazon.Lambda.DynamoDBEvents"));
return false;
}
}

return true;
}

Expand Down Expand Up @@ -268,6 +280,45 @@ private static void ValidateSqsEvents(LambdaFunctionModel lambdaFunctionModel, L
}
}

private static void ValidateDynamoDBEvents(LambdaFunctionModel lambdaFunctionModel, Location methodLocation, List<Diagnostic> diagnostics)
{
if (!lambdaFunctionModel.LambdaMethod.Events.Contains(EventType.DynamoDB))
{
return;
}

// Validate DynamoDBEventAttributes
foreach (var att in lambdaFunctionModel.Attributes)
{
if (att.Type.FullName != TypeFullNames.DynamoDBEventAttribute)
continue;

var dynamoDBEventAttribute = ((AttributeModel<DynamoDBEventAttribute>)att).Data;
var validationErrors = dynamoDBEventAttribute.Validate();
validationErrors.ForEach(errorMessage => diagnostics.Add(Diagnostic.Create(DiagnosticDescriptors.InvalidDynamoDBEventAttribute, methodLocation, errorMessage)));
}

// Validate method parameters - When using DynamoDBEventAttribute, the method signature must be (DynamoDBEvent evnt) or (DynamoDBEvent evnt, ILambdaContext context)
var parameters = lambdaFunctionModel.LambdaMethod.Parameters;
if (parameters.Count == 0 ||
parameters.Count > 2 ||
(parameters.Count == 1 && parameters[0].Type.FullName != TypeFullNames.DynamoDBEvent) ||
(parameters.Count == 2 && (parameters[0].Type.FullName != TypeFullNames.DynamoDBEvent || parameters[1].Type.FullName != TypeFullNames.ILambdaContext)))
{
var errorMessage = $"When using the {nameof(DynamoDBEventAttribute)}, the Lambda method can accept at most 2 parameters. " +
$"The first parameter is required and must be of type {TypeFullNames.DynamoDBEvent}. " +
$"The second parameter is optional and must be of type {TypeFullNames.ILambdaContext}.";
diagnostics.Add(Diagnostic.Create(DiagnosticDescriptors.InvalidLambdaMethodSignature, methodLocation, errorMessage));
}

// Validate method return type - When using DynamoDBEventAttribute, the return type must be either void or Task
if (!lambdaFunctionModel.LambdaMethod.ReturnsVoid && !lambdaFunctionModel.LambdaMethod.ReturnsVoidTask)
{
var errorMessage = $"When using the {nameof(DynamoDBEventAttribute)}, the Lambda method can return either void or {TypeFullNames.Task}";
diagnostics.Add(Diagnostic.Create(DiagnosticDescriptors.InvalidLambdaMethodSignature, methodLocation, errorMessage));
}
}

private static bool ReportDiagnostics(DiagnosticReporter diagnosticReporter, List<Diagnostic> diagnostics)
{
var isValid = true;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.Annotations.DynamoDB;
using Amazon.Lambda.Annotations.SourceGenerator.Diagnostics;
using Amazon.Lambda.Annotations.SourceGenerator.FileIO;
using Amazon.Lambda.Annotations.SourceGenerator.Models;
Expand Down Expand Up @@ -221,6 +222,10 @@ private void ProcessLambdaFunctionEventAttributes(ILambdaFunctionSerializable la
eventName = ProcessSqsAttribute(lambdaFunction, sqsAttributeModel.Data, currentSyncedEventProperties);
currentSyncedEvents.Add(eventName);
break;
case AttributeModel<DynamoDBEventAttribute> dynamoDBAttributeModel:
eventName = ProcessDynamoDBAttribute(lambdaFunction, dynamoDBAttributeModel.Data, currentSyncedEventProperties);
currentSyncedEvents.Add(eventName);
break;
}
}

Expand Down Expand Up @@ -600,6 +605,68 @@ private string ProcessSqsAttribute(ILambdaFunctionSerializable lambdaFunction, S
/// Writes all properties associated with <see cref="LambdaFunctionRoleAttribute"/> to the serverless template.
/// </summary>

/// <summary>
/// Writes all properties associated with <see cref="DynamoDBEventAttribute"/> to the serverless template.
/// </summary>
private string ProcessDynamoDBAttribute(ILambdaFunctionSerializable lambdaFunction, DynamoDBEventAttribute att, Dictionary<string, List<string>> syncedEventProperties)
{
var eventName = att.ResourceName;
var eventPath = $"Resources.{lambdaFunction.ResourceName}.Properties.Events.{eventName}";

_templateWriter.SetToken($"{eventPath}.Type", "DynamoDB");

// Stream
_templateWriter.RemoveToken($"{eventPath}.Properties.Stream");
if (!att.Stream.StartsWith("@"))
{
SetEventProperty(syncedEventProperties, lambdaFunction.ResourceName, eventName, "Stream", att.Stream);
}
else
{
var resource = att.Stream.Substring(1);
if (_templateWriter.Exists($"{PARAMETERS}.{resource}"))
SetEventProperty(syncedEventProperties, lambdaFunction.ResourceName, eventName, $"Stream.{REF}", resource);
else
SetEventProperty(syncedEventProperties, lambdaFunction.ResourceName, eventName, $"Stream.{GET_ATTRIBUTE}", new List<string> { resource, "StreamArn" }, TokenType.List);
}

// StartingPosition
SetEventProperty(syncedEventProperties, lambdaFunction.ResourceName, eventName, "StartingPosition", att.StartingPosition);

// BatchSize
if (att.IsBatchSizeSet)
{
SetEventProperty(syncedEventProperties, lambdaFunction.ResourceName, eventName, "BatchSize", att.BatchSize);
}

// Enabled
if (att.IsEnabledSet)
{
SetEventProperty(syncedEventProperties, lambdaFunction.ResourceName, eventName, "Enabled", att.Enabled);
}

// MaximumBatchingWindowInSeconds
if (att.IsMaximumBatchingWindowInSecondsSet)
{
SetEventProperty(syncedEventProperties, lambdaFunction.ResourceName, eventName, "MaximumBatchingWindowInSeconds", att.MaximumBatchingWindowInSeconds);
}

// FilterCriteria
if (att.IsFiltersSet)
{
const char SEPERATOR = ';';
var filters = att.Filters.Split(SEPERATOR).Select(x => x.Trim()).ToList();
var filterList = new List<Dictionary<string, string>>();
foreach (var filter in filters)
{
filterList.Add(new Dictionary<string, string> { { "Pattern", filter } });
}
SetEventProperty(syncedEventProperties, lambdaFunction.ResourceName, eventName, "FilterCriteria.Filters", filterList, TokenType.List);
}

return att.ResourceName;
}

/// <summary>
/// Writes the default values for the Lambda function's metadata and properties.
/// </summary>
Expand Down
Loading
Loading