-
Notifications
You must be signed in to change notification settings - Fork 997
Enhance apigw-lambda-sns pattern with production-ready improvements #2777
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
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -10,11 +10,18 @@ Resources: | |
Type: AWS::Serverless::Api | ||
Properties: | ||
StageName: s1 | ||
DefinitionBody: # an OpenApi definition | ||
'Fn::Transform': | ||
Name: 'AWS::Include' | ||
TracingEnabled: true | ||
MethodSettings: | ||
- ResourcePath: '/*' | ||
HttpMethod: '*' | ||
MetricsEnabled: true | ||
DataTraceEnabled: true | ||
LoggingLevel: INFO | ||
DefinitionBody: | ||
Fn::Transform: | ||
Name: AWS::Include | ||
Parameters: | ||
Location: './api.yaml' | ||
Location: ./api.yaml | ||
OpenApiVersion: 3.0.3 | ||
EndpointConfiguration: | ||
Type: REGIONAL | ||
|
@@ -28,22 +35,13 @@ Resources: | |
Handler: code.lambda_handler | ||
MemorySize: 128 | ||
Timeout: 3 | ||
Runtime: python3.8 | ||
Runtime: python3.13 | ||
Tracing: Active | ||
Environment: | ||
Variables: | ||
TOPIC_ARN: !Ref MySnsTopic | ||
AssumeRolePolicyDocument: | ||
Version: 2012-10-17 | ||
Statement: | ||
- Action: | ||
- sts:AssumeRole | ||
Effect: Allow | ||
Principal: | ||
Service: | ||
- lambda.amazonaws.com | ||
API_URL: !Sub 'https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/s1' | ||
Policies: | ||
- S3FullAccessPolicy: | ||
BucketName: severlesspatternlambda | ||
- SNSPublishMessagePolicy: | ||
TopicName: !GetAtt MySnsTopic.TopicName | ||
Events: | ||
|
@@ -53,6 +51,172 @@ Resources: | |
Path: / | ||
Method: GET | ||
RestApiId: !Ref RestApi | ||
|
||
# CloudWatch Alarm for API Gateway 5XX Errors | ||
ApiGateway5XXErrorAlarm: | ||
Type: AWS::CloudWatch::Alarm | ||
Properties: | ||
AlarmName: !Sub '${AWS::StackName}-API-Gateway-5XX-Error' | ||
AlarmDescription: Monitor API Gateway 5XX errors | ||
MetricName: 5XXError | ||
Namespace: AWS/ApiGateway | ||
Dimensions: | ||
- Name: ApiName | ||
Value: RestApi | ||
- Name: Stage | ||
Value: s1 | ||
Statistic: Sum | ||
Period: 300 | ||
EvaluationPeriods: 1 | ||
Threshold: 3 | ||
ComparisonOperator: GreaterThanThreshold | ||
TreatMissingData: notBreaching | ||
|
||
# S3 Bucket for Synthetics Canary Artifacts | ||
SyntheticsArtifactsBucket: | ||
Type: AWS::S3::Bucket | ||
DeletionPolicy: Retain | ||
Properties: | ||
PublicAccessBlockConfiguration: | ||
BlockPublicAcls: true | ||
BlockPublicPolicy: true | ||
IgnorePublicAcls: true | ||
RestrictPublicBuckets: true | ||
|
||
# IAM Role for Synthetics Canary | ||
SyntheticsCanaryRole: | ||
Type: AWS::IAM::Role | ||
Properties: | ||
AssumeRolePolicyDocument: | ||
Version: '2012-10-17' | ||
Statement: | ||
- Effect: Allow | ||
Principal: | ||
Service: | ||
- synthetics.amazonaws.com | ||
- lambda.amazonaws.com | ||
Action: sts:AssumeRole | ||
Policies: | ||
- PolicyName: SyntheticsPolicy | ||
PolicyDocument: | ||
Version: '2012-10-17' | ||
Statement: | ||
- Effect: Allow | ||
Action: | ||
- s3:PutObject | ||
- s3:GetObject | ||
- s3:ListBucket | ||
- s3:ListAllMyBuckets | ||
- s3:GetBucketLocation | ||
Resource: | ||
- !Sub '${SyntheticsArtifactsBucket.Arn}/*' | ||
- !GetAtt SyntheticsArtifactsBucket.Arn | ||
- Effect: Allow | ||
Action: | ||
- logs:CreateLogGroup | ||
- logs:CreateLogStream | ||
- logs:PutLogEvents | ||
- cloudwatch:PutMetricData | ||
- synthetics:* | ||
Resource: '*' | ||
|
||
# Synthetics Canary | ||
ApiGatewayCanary: | ||
Type: AWS::Synthetics::Canary | ||
Properties: | ||
Name: !Sub '${AWS::StackName}-api-gw-canary' | ||
RuntimeVersion: syn-nodejs-puppeteer-9.0 | ||
ExecutionRoleArn: !GetAtt SyntheticsCanaryRole.Arn | ||
ArtifactS3Location: !Sub 's3://${SyntheticsArtifactsBucket}/' | ||
Schedule: | ||
Expression: 'rate(1 minute)' | ||
DurationInSeconds: 0 | ||
RunConfig: | ||
TimeoutInSeconds: 60 | ||
MemoryInMB: 960 | ||
FailureRetentionPeriod: 30 | ||
SuccessRetentionPeriod: 30 | ||
StartCanaryAfterCreation: true | ||
Code: | ||
Handler: canary.handler | ||
Script: !Sub | | ||
const { URL } = require('url'); | ||
const synthetics = require('Synthetics'); | ||
const log = require('SyntheticsLogger'); | ||
const syntheticsConfiguration = synthetics.getConfiguration(); | ||
const syntheticsLogHelper = require('SyntheticsLogHelper'); | ||
|
||
const loadBlueprint = async function () { | ||
const urls = ['https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/s1']; | ||
const takeScreenshot = true; | ||
|
||
syntheticsConfiguration.disableStepScreenshots(); | ||
syntheticsConfiguration.setConfig({ | ||
continueOnStepFailure: true, | ||
includeRequestHeaders: true, | ||
includeResponseHeaders: true, | ||
restrictedHeaders: [], | ||
restrictedUrlParameters: [] | ||
}); | ||
|
||
let page = await synthetics.getPage(); | ||
|
||
for (const url of urls) { | ||
await loadUrl(page, url, takeScreenshot); | ||
} | ||
}; | ||
|
||
const resetPage = async function(page) { | ||
try { | ||
await page.goto('about:blank',{waitUntil: ['load', 'networkidle0'], timeout: 30000} ); | ||
} catch (e) { | ||
synthetics.addExecutionError('Unable to open a blank page. ', e); | ||
} | ||
} | ||
|
||
const loadUrl = async function (page, url, takeScreenshot) { | ||
let stepName = null; | ||
let domcontentloaded = false; | ||
|
||
try { | ||
stepName = new URL(url).hostname; | ||
} catch (e) { | ||
const errorString = 'Error parsing url: ' + url + '. ' + e; | ||
log.error(errorString); | ||
throw e; | ||
} | ||
|
||
await synthetics.executeStep(stepName, async function () { | ||
const sanitizedUrl = syntheticsLogHelper.getSanitizedUrl(url); | ||
const response = await page.goto(url, { waitUntil: ['domcontentloaded'], timeout: 30000}); | ||
|
||
if (response) { | ||
domcontentloaded = true; | ||
const status = response.status(); | ||
const statusText = response.statusText(); | ||
|
||
if (response.status() < 200 || response.status() > 299) { | ||
throw new Error('Failed to load url: ' + sanitizedUrl + ' ' + response.status() + ' ' + response.statusText()); | ||
} | ||
} else { | ||
const logNoResponseString = 'No response returned for url: ' + sanitizedUrl; | ||
log.error(logNoResponseString); | ||
throw new Error(logNoResponseString); | ||
} | ||
}); | ||
|
||
if (domcontentloaded && takeScreenshot) { | ||
await new Promise(r => setTimeout(r, 15000)); | ||
await synthetics.takeScreenshot(stepName, 'loaded'); | ||
} | ||
|
||
await resetPage(page); | ||
}; | ||
|
||
exports.handler = async () => { | ||
return await loadBlueprint(); | ||
}; | ||
Comment on lines
+142
to
+218
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As the original pattern is in Python. (refer |
||
|
||
Outputs: | ||
lambdaArn: | ||
Value: !GetAtt lambdaFunction.Arn | ||
|
@@ -62,4 +226,16 @@ Outputs: | |
Value: !Ref MySnsTopic | ||
|
||
apiGatewayInvokeURL: | ||
Value: !Sub https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/s1 | ||
Value: !Sub https://${RestApi}.execute-api.${AWS::Region}.amazonaws.com/s1 | ||
|
||
CloudWatchAlarmName: | ||
Description: Name of the API Gateway 5XX Error Alarm | ||
Value: !Ref ApiGateway5XXErrorAlarm | ||
|
||
SyntheticsCanaryName: | ||
Description: Name of the Synthetics Canary | ||
Value: !Ref ApiGatewayCanary | ||
|
||
SyntheticsArtifactsBucket: | ||
Description: S3 Bucket for Synthetics artifacts (delete manually after stack deletion) | ||
Value: !Ref SyntheticsArtifactsBucket |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Can you please use a reference for stage name instead of hardcoded 's1'?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Updated