-
Notifications
You must be signed in to change notification settings - Fork 494
Expand file tree
/
Copy pathGeneratedMethodModelBuilder.cs
More file actions
355 lines (324 loc) · 16.4 KB
/
GeneratedMethodModelBuilder.cs
File metadata and controls
355 lines (324 loc) · 16.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
using System;
using System.Collections.Generic;
using System.Linq;
using Amazon.Lambda.Annotations.APIGateway;
using Amazon.Lambda.Annotations.SourceGenerator.Extensions;
using Microsoft.CodeAnalysis;
namespace Amazon.Lambda.Annotations.SourceGenerator.Models
{
/// <summary>
/// <see cref="GeneratedMethodModel"/> builder.
/// </summary>
public static class GeneratedMethodModelBuilder
{
public static GeneratedMethodModel Build(IMethodSymbol lambdaMethodSymbol,
IMethodSymbol configureMethodSymbol,
LambdaMethodModel lambdaMethodModel,
GeneratorExecutionContext context)
{
var model = new GeneratedMethodModel
{
Usings = BuildUsings(lambdaMethodModel, lambdaMethodSymbol, configureMethodSymbol, context),
Parameters = BuildParameters(lambdaMethodSymbol, lambdaMethodModel, context),
ReturnType = BuildResponseType(lambdaMethodSymbol, lambdaMethodModel, context),
ContainingType = BuildContainingType(lambdaMethodSymbol),
};
return model;
}
private static IList<string> BuildUsings(LambdaMethodModel lambdaMethodModel,
IMethodSymbol lambdaMethodSymbol,
IMethodSymbol configureMethodSymbol,
GeneratorExecutionContext context)
{
var namespaces = new List<string>
{
"System",
"System.Linq",
"System.Collections.Generic",
"System.Text",
"System.Threading.Tasks",
"System.IO"
};
if (configureMethodSymbol != null)
{
namespaces.Add("Microsoft.Extensions.DependencyInjection");
if (lambdaMethodModel.UsingHostBuilderForDependencyInjection)
{
namespaces.Add("Microsoft.Extensions.Hosting");
}
}
namespaces.Add("Amazon.Lambda.Core");
if(lambdaMethodModel.ReturnsIHttpResults || lambdaMethodModel.ReturnsIAuthorizerResult)
{
namespaces.Add("Amazon.Lambda.Annotations.APIGateway");
}
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);
}
// For authorizer functions returning IAuthorizerResult, the generated handler returns Stream
// (the IAuthorizerResult.Serialize method produces the JSON stream)
if (lambdaMethodModel.ReturnsIAuthorizerResult)
{
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);
}
// For authorizer functions that return raw API Gateway types (backwards compatibility),
// pass through the return type as-is
if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.HttpApiAuthorizerAttribute) ||
lambdaMethodSymbol.HasAttribute(context, TypeFullNames.RestApiAuthorizerAttribute))
{
return lambdaMethodModel.ReturnType;
}
if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.RestApiAttribute))
{
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)
{
case HttpApiVersion.V1:
{
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();
}
}
else if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.ALBApiAttribute))
{
// ALB functions return ApplicationLoadBalancerResponse
// If the user already returns ApplicationLoadBalancerResponse, pass through the return type.
// Otherwise, wrap in ApplicationLoadBalancerResponse.
if (lambdaMethodModel.ReturnsApplicationLoadBalancerResponse)
{
return lambdaMethodModel.ReturnType;
}
var symbol = lambdaMethodModel.ReturnsVoidOrGenericTask ?
task.Construct(context.Compilation.GetTypeByMetadataName(TypeFullNames.ApplicationLoadBalancerResponse)):
context.Compilation.GetTypeByMetadataName(TypeFullNames.ApplicationLoadBalancerResponse);
return TypeModelBuilder.Build(symbol, context);
}
else
{
return lambdaMethodModel.ReturnType;
}
}
private static HttpApiVersion GetHttpApiVersion(IMethodSymbol lambdaMethodSymbol, GeneratorExecutionContext context)
{
var httpApiAttribute = lambdaMethodSymbol.GetAttributeData(context, TypeFullNames.HttpApiAttribute);
if (httpApiAttribute.ConstructorArguments.IsDefaultOrEmpty)
{
throw new InvalidOperationException($"{TypeFullNames.HttpApiAttribute} must have a constructor with parameter.");
}
var versionArgument = httpApiAttribute.NamedArguments.FirstOrDefault(arg => arg.Key == "Version").Value;
if (versionArgument.Type == null)
{
return HttpApiVersion.V2;
}
if (!versionArgument.Type.Equals(context.Compilation.GetTypeByMetadataName(TypeFullNames.HttpApiVersion), SymbolEqualityComparer.Default))
{
throw new InvalidOperationException($"Constructor parameter must be of type {TypeFullNames.HttpApiVersion}.");
}
if (versionArgument.Value == null)
{
throw new InvalidOperationException($"{versionArgument.Type} value cannot be null for {TypeFullNames.HttpApiAttribute}.");
}
return (HttpApiVersion)versionArgument.Value;
}
private static AuthorizerPayloadFormatVersion GetAuthorizerPayloadFormatVersion(AttributeData authorizerAttribute)
{
var versionArg = authorizerAttribute.NamedArguments
.FirstOrDefault(arg => arg.Key == "AuthorizerPayloadFormatVersion").Value;
if (versionArg.Type == null || versionArg.Value == null)
{
// Default is V2
return AuthorizerPayloadFormatVersion.V2;
}
return (AuthorizerPayloadFormatVersion)(int)versionArg.Value;
}
private static IList<ParameterModel> BuildParameters(IMethodSymbol lambdaMethodSymbol,
LambdaMethodModel lambdaMethodModel, GeneratorExecutionContext context)
{
var parameters = new List<ParameterModel>();
var contextParameter = new ParameterModel
{
Name = "__context__",
Type = new TypeModel
{
FullName = TypeFullNames.ILambdaContext
},
Documentation = "The ILambdaContext that provides methods for logging and describing the Lambda environment."
};
if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.HttpApiAuthorizerAttribute))
{
// For HTTP API authorizer functions, the generated handler accepts the authorizer request type
var authorizerAttribute = lambdaMethodSymbol.GetAttributeData(context, TypeFullNames.HttpApiAuthorizerAttribute);
var payloadVersion = GetAuthorizerPayloadFormatVersion(authorizerAttribute);
string requestTypeName;
if (payloadVersion == AuthorizerPayloadFormatVersion.V2)
{
requestTypeName = TypeFullNames.APIGatewayCustomAuthorizerV2Request;
}
else
{
requestTypeName = TypeFullNames.APIGatewayCustomAuthorizerRequest;
}
var symbol = context.Compilation.GetTypeByMetadataName(requestTypeName);
var type = TypeModelBuilder.Build(symbol, context);
var requestParameter = new ParameterModel
{
Name = "__request__",
Type = type,
Documentation = "The API Gateway authorizer request object that will be processed by the Lambda function handler."
};
parameters.Add(requestParameter);
parameters.Add(contextParameter);
}
else if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.RestApiAuthorizerAttribute))
{
// For REST API authorizer functions, always use APIGatewayCustomAuthorizerRequest
var symbol = context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayCustomAuthorizerRequest);
var type = TypeModelBuilder.Build(symbol, context);
var requestParameter = new ParameterModel
{
Name = "__request__",
Type = type,
Documentation = "The API Gateway authorizer request object that will be processed by the Lambda function handler."
};
parameters.Add(requestParameter);
parameters.Add(contextParameter);
}
else if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.RestApiAttribute))
{
var symbol = context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyRequest);
var type = TypeModelBuilder.Build(symbol, context);
var requestParameter = new ParameterModel
{
Name = "__request__",
Type = type,
Documentation = "The API Gateway request object that will be processed by the Lambda function handler."
};
parameters.Add(requestParameter);
parameters.Add(contextParameter);
}
else if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.HttpApiAttribute))
{
var version = GetHttpApiVersion(lambdaMethodSymbol, context);
TypeModel type;
switch (version)
{
case HttpApiVersion.V1:
{
var symbol = context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayProxyRequest);
type = TypeModelBuilder.Build(symbol, context);
break;
}
case HttpApiVersion.V2:
{
var symbol = context.Compilation.GetTypeByMetadataName(TypeFullNames.APIGatewayHttpApiV2ProxyRequest);
type = TypeModelBuilder.Build(symbol, context);
break;
}
default:
throw new ArgumentOutOfRangeException();
}
var requestParameter = new ParameterModel
{
Name = "__request__",
Type = type,
Documentation = "The API Gateway request object that will be processed by the Lambda function handler."
};
parameters.Add(requestParameter);
parameters.Add(contextParameter);
}
else if (lambdaMethodSymbol.HasAttribute(context, TypeFullNames.ALBApiAttribute))
{
var symbol = context.Compilation.GetTypeByMetadataName(TypeFullNames.ApplicationLoadBalancerRequest);
var type = TypeModelBuilder.Build(symbol, context);
var requestParameter = new ParameterModel
{
Name = "__request__",
Type = type,
Documentation = "The ALB request object that will be processed by the Lambda function handler."
};
parameters.Add(requestParameter);
parameters.Add(contextParameter);
}
else
{
// Lambda method with no event attribute are plain lambda functions, therefore, generated method will have
// same parameter as original method except DI injected parameters
foreach (var param in lambdaMethodModel.Parameters)
{
if (param.Attributes.Any(att => att.Type.FullName == TypeFullNames.FromServiceAttribute))
{
continue;
}
// If the Lambda function is taking in the ILambdaContext object make sure in the generated wrapper code we
// use the same system name for the ILambdaContext variable as all of the other places use.
else if(param.Type.FullName == TypeFullNames.ILambdaContext)
{
param.Name = "__context__";
param.Documentation = "The ILambdaContext that provides methods for logging and describing the Lambda environment.";
}
else
{
// Somehow, Roslyn doesn't include @ character when using with reserved keyword. Add a check just in case Roslyn fix is implemented in later versions.
if (!param.Name.StartsWith("@"))
{
param.Name = "__" + param.Name + "__";
}
param.Documentation = "The request object that will be processed by the Lambda function handler.";
}
parameters.Add(param);
}
}
return parameters;
}
private static TypeModel BuildContainingType(IMethodSymbol lambdaMethodSymbol)
{
var name = $"{lambdaMethodSymbol.ContainingType.Name}_{lambdaMethodSymbol.Name}_Generated";
var fullName = $"{lambdaMethodSymbol.ContainingNamespace}.{name}";
var model = new TypeModel
{
Name = name,
FullName = fullName,
IsValueType = false
};
return model;
}
}
}