Skip to content

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

small AWS CDK + LocalStack project for validating/storing fleetbase data

This project is implemented with AWS CDK and deploys the resulting cloudformation template to localstack:

  • EventBridge + bus with associated rules
  • Lambda function that validates and saves data to MongoDB, as well as reports metrics based on validation success/failure. Written in typescript. Note: The deployment of lambda (and hence the entire stack) is reliant upon an existing S3 bucket to use for uploading the zipped lambda handler artifact.
  • Role for the lambda function. Is kept narrow and only grants permissions for logging and metrics.
  • Cloudwatch anomaly detection alarm for lambda invocations.
  • SQS DLQ for failed EventBridge target invocations
  • MongoDB as a Docker container

The solution provides a simple flow for receiving messages from EventBridge, processing them with a lambda and storing them to mongoDB: EventBridge -> Lambda -> MongoDB. Added Cloudwatch anomaly detection alarm for lambda invocations since a low message volume is expected.

All of the resources are grouped into one stack since the scope is quite small, but if the project grows, the resources can be split into multiple stacks for better maintainability.

Prerequisites

  • Linux/Unix environment (built on WSL2 (Ubuntu)) with the standard tools installed:
    • grep
    • mkdir
    • rm
  • Docker + Compose (ensure docker is available in the WSL environment if that is used):
    • docker --version
    • docker compose version
  • Node.js 20+
  • npm
  • zip (for building lambda)
  • AWS CLI (Tested with v1, v2 should work as well)

Building the project

Several bash scripts are provided under "/scripts/". They streamline the build/deployment process. The following steps are required to build the project`(Assume commands are run from project root unless stated otherwise):

  1. Install dependencies via npm install and npm run build
  2. Package artifact into a zip file zip -r <FILE_NAME>.zip dist. When deploying using localstack/cloudformation,
  3. the template assumes the zip file is named "lambda.zip" and is located in the "artifacts" directory.

These steps are automated via the provided "build-lambda.sh" script. It is also possible to run this script by running npm run package:lambda.

Testing the project

To run unit tests, execute npm run test.

Running the project/Deploying the stack

The project is configured to run using docker and localstack. Perform the following steps to run the project:

  1. Start localstack services and MongoDB container via docker compose up
  2. Synthesize cloudformation template using AWS CDK via npm run cdk:synth
  3. Deploy the synthesized template to localstack

steps 2 and 3 are automated via scripts/deploy-local-simple.sh. Before running it is imperative to ensure the necessary docker containers are running. It is also possible to run this script by running npm run deploy:local.

Note: You can also build the lambda artifact and deploy the stack in one go by running npm run deploy:all. Ensure the docker containers are running beforehand.

Lambda handler

Written in typescript since it was a learning experience and I wanted to refresh my knowledge of the language. The handler validates the incoming event using class-validator. A converter class (FleetBaseDataConverter) is used to convert the incoming event (FleetBaseDataEventModel) to a DB entry (FleetbaseDataDocumentModel. The handler then saves the model to mongoDB. The handler also sends custom metrics to CloudWatch. The following custom metrics are sent:

  • validation.success: Counts the number of successful validation attempts.
  • validation.failure: Counts the number of failed validation attempts. Splitting the handler into multiple classes (FleetBaseDataConverter, MetricsSender etc.) was done to increase readability and maintainability.

Sending test events

Scripts are provided to send test events to the even bridge. This is to help testing the solution. The following scripts are provided:

  • send-test-event.sh: sends a test event to the event bridge. The script expects a path to a .json file containing an event bridge message.
  • check-mongo-entries.sh: lists all documents in the mongoDB database. Used for verifying that events end up in mongoDB.
  • purge-mongo-database.sh: purges all documents in the mongoDB database. Can be used to clean the database bewteen tests.

Under scripts/samples/ you can find a sample events in the form of json files. The following samples are provided:

  • happy-sample.json: sample event that should pass validation and end up in mongoDB.
  • happy-sample-null-fields.json: sample event that should pass validation and end up in mongoDB. The message contains null fields that are not supposed to be required.
  • invalid-sample.json: sample event that should fail validation (erroneous fleetIdentifier) and end up in the dead-letter queue. The message is not saved in mongoDB.

Useful information

Ports

The project uses the following ports when started via docker compose up:

  • 4566: Used to access localstack services, most notably in the script to inject messages on AWS EventBridge.
  • 27017: MongoDB default port. Used to access MongoDB via the Lambda function that validates and saves data.

AI usage

AI/Google aided in the creation of this project as a learning buddy in the following ways:

  • To generate a tiny scaffold CDK structure since I was not familiar with it.
  • To learn how to use the CDK and compare it to a plain yaml CloudFormation template.
  • Aided in setup of the mongo DB related scripts (send-test-event.sh, check-mongo-entries.sh, purge-mongo-database.sh)
  • To refresh my knowledge of TypeScript and JavaScript.
  • Aid in understanding the EventBridge message format.
  • Aid in understanding of how to mock stuff in unit tests.

Considerations/Additional thoughts

  • Note that I added validation that was not specified in the assignment: if present, numberOfVehicles must be an integer >= 0. This is not part of the assignment, but I figured it made sense and wanted to highlight that I would want to discuss this with the stakeholders.
  • if it is desired to send multiple types of events on the same event bridge, it would be possible to add further filtering in the event bus lambda rule on e.g. detail-type and add additional lambdas to handle the different types.
  • Since JS/TS is not my main programming language, I had to look up how to use the CDK and compare it to a plain yaml CloudFormation template. I also had to refresh my memory/learn some new concepts as I went along, so the lambda handler might not be as optimized as it could be and migh not adhere to best practices, so before going to production with this I would definitely like to have this reviewed by someone more knowledgeable in JS/TS.
  • In production, it would be a good idea to store failed events (S3-bucket, another mongoDB collection, dynamo etc) in order to be able to trace the source of the failure. Right now there is only a dead-letter queue (SQS).
  • Since we don't expect a heavy load on the system, I added a cloudwatch anomalies alarm to monitor the number of lambda invocations (fleet-data-handler-lambda-invocations-anomaly-alarm). Depending on expected traffic, this alarm would have to be tuned accordingly.
  • In production, it would be a good idea to add more alarms to monitor lambda health, number of messages processed etc.
  • In production, several measures should be taken in order to increase security. Some examples are:
    • Storing secrets/parameters in AWS Secrets Manager/parameter store instead of hardcoding them in the code (MongoDB connection details comes to mind).
    • Restricting network accesses to the lambda function.
    • Enforcing tighter MongoDB authentication.
    • Limiting who can publish to the EventBridge. This can be sone by setting up appropriate IAM policies.
    • Avoiding logging of sensitive payload fields or connection details to CloudWatch logs.
    • Adding more alarms looking at suspicious traffic patterns, such as high number of failed invocations, high number of failed validations, etc.
    • Have tighter control over input. Maybe add tighter validations on malformed data, input size etc.

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages