-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbasic-lambda.yaml
242 lines (208 loc) · 7.97 KB
/
basic-lambda.yaml
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
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
FibonacciFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs22.x
InlineCode: |
exports.handler = async (event) => {
// Get parameters from event
const number = event.number || 0;
const userName = event.userName || 'anonymous';
// Log the incoming event and user
console.log('Event received from user:', userName, 'Event:', JSON.stringify(event));
// Random log message
console.log('Processing Fibonacci calculation at:', new Date().toISOString());
// Validate input
if (number < 0) {
const errorMessage = `User ${userName} requested Fibonacci of negative number: ${number}`;
console.error(errorMessage);
}
// Sleep for 1 second
await new Promise(resolve => setTimeout(resolve, 1000));
// Calculate Fibonacci
const calculateFibonacci = (n) => {
if (n <= 1) return n;
return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);
};
const result = calculateFibonacci(number);
// Log and return the result
console.log('Calculated Fibonacci result:', result);
return {
statusCode: 200,
body: JSON.stringify({
userName,
input: number,
fibonacci: result
})
};
};
Description: A Lambda function that calculates Fibonacci numbers
MemorySize: 128
Timeout: 30
FibonacciPowertoolsFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs22.x
InlineCode: |
const { Logger } = require('@aws-lambda-powertools/logger');
const logger = new Logger({
serviceName: 'fibonacciService',
logLevel: 'INFO'
});
const calculateFibonacci = (n) => {
if (n <= 1) return n;
return calculateFibonacci(n - 1) + calculateFibonacci(n - 2);
};
exports.handler = async (event, context) => {
// Add correlation ids from Lambda context
logger.addContext(context);
// Get parameters from event
const number = event.number || 0;
const userName = event.userName || 'anonymous';
// Structured logging of the event
logger.info('Processing fibonacci request', {
userName,
number,
timestamp: new Date().toISOString(),
});
// Validate input
if (number < 0) {
const errorMessage = 'User requested Fibonacci of negative number';
logger.error(errorMessage, { userName, number });
}
// Sleep for 1 second
logger.debug('Sleeping for 1 second');
await new Promise(resolve => setTimeout(resolve, 1000));
// Calculate fibonacci
logger.debug('Calculating fibonacci', { number });
const result = calculateFibonacci(number);
// Log success with structured data
logger.info('Fibonacci calculation completed', {
userName,
input: number,
result,
});
return {
statusCode: 200,
body: JSON.stringify({
userName,
input: number,
fibonacci: result
})
};
};
Description: A Lambda function that calculates Fibonacci numbers with Powertools logging
MemorySize: 128
Timeout: 30
Environment:
Variables:
POWERTOOLS_SERVICE_NAME: fibonacciService
LOG_LEVEL: INFO
Layers:
- !Sub arn:aws:lambda:${AWS::Region}:094274105915:layer:AWSLambdaPowertoolsTypeScriptV2:17
InvokerFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs22.x
InlineCode: |
const { LambdaClient, InvokeCommand } = require('@aws-sdk/client-lambda');
const lambda = new LambdaClient();
exports.handler = async (event) => {
const results = {
standard: [],
powertools: []
};
const userNames = ['alice', 'bob', 'charlie', 'dave'];
// Invoke both Fibonacci functions 50 times sequentially
for (let i = 0; i < 50; i++) {
const number = Math.floor(Math.random() * 21) - 10; // Random number between -10 and 10
const userName = userNames[Math.floor(Math.random() * userNames.length)];
const payload = Buffer.from(JSON.stringify({
number,
userName
}));
// Standard Fibonacci function invocation
const standardCommand = new InvokeCommand({
FunctionName: process.env.FIBONACCI_FUNCTION_ARN,
InvocationType: 'RequestResponse',
Payload: payload
});
// Powertools Fibonacci function invocation
const powertoolsCommand = new InvokeCommand({
FunctionName: process.env.FIBONACCI_POWERTOOLS_FUNCTION_ARN,
InvocationType: 'RequestResponse',
Payload: payload
});
try {
console.log(`Invoking calculation ${i + 1}/50 for number ${number}`);
// Invoke standard function
const standardResponse = await lambda.send(standardCommand);
const standardPayload = JSON.parse(new TextDecoder().decode(standardResponse.Payload));
results.standard.push({
invocation: i + 1,
number,
userName,
response: standardPayload
});
// Invoke powertools function
const powertoolsResponse = await lambda.send(powertoolsCommand);
const powertoolsPayload = JSON.parse(new TextDecoder().decode(powertoolsResponse.Payload));
results.powertools.push({
invocation: i + 1,
number,
userName,
response: powertoolsPayload
});
} catch (error) {
console.log(`Error in invocation ${i + 1}:`, error);
results.standard.push({
invocation: i + 1,
number,
userName,
error: error.message
});
results.powertools.push({
invocation: i + 1,
number,
userName,
error: error.message
});
}
}
console.log('All invocations completed', JSON.stringify(results));
return {
statusCode: 200,
body: 'Success'
};
};
Description: A Lambda function that invokes the Fibonacci function 50 times
MemorySize: 128
Timeout: 300
Environment:
Variables:
FIBONACCI_FUNCTION_ARN: !GetAtt FibonacciFunction.Arn
FIBONACCI_POWERTOOLS_FUNCTION_ARN: !GetAtt FibonacciPowertoolsFunction.Arn
Policies:
- Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- lambda:InvokeFunction
Resource:
- !GetAtt FibonacciFunction.Arn
- !GetAtt FibonacciPowertoolsFunction.Arn
Outputs:
FibonacciFunction:
Description: Fibonacci Lambda Function ARN
Value: !GetAtt FibonacciFunction.Arn
FibonacciPowertoolsFunction:
Description: Fibonacci Powertools Lambda Function ARN
Value: !GetAtt FibonacciPowertoolsFunction.Arn
InvokerFunction:
Description: Invoker Lambda Function ARN
Value: !GetAtt InvokerFunction.Arn