bcgov / bcparks-ar-api

BCParks Attendance and Revenue Backend.
Apache License 2.0
2 stars 11 forks source link
aws dynamodb env nodejs serverless

BC Parks Attendance & Revenue - API

Lifecycle:Maturing Maintainability Rating

Introduction

This repository consists of the back end code for the BC Parks Attendance & Revenue system (A&R) API. A&R helps Park Operators, BC Parks, and the BC Government track important statistical information to help guide budget allowances and any maintenance that needs to be done to parks.

The AWS resources for this project are defined in the template.yaml file. Data models can be found in /docs

Associated repos:

Contribution Guidelines

To contribute to this code, follow the steps through this link: https://bcgov.github.io/bcparks/collaborate

Local Development

Prerequisites

To use the SAM CLI, you need the following tools.

DynamoDB Local

This project makes use of dynamodb-local for local development. You can start an instance of DynamoDB using Docker.

docker run -d -p 8000:8000 --name dynamodb amazon/dynamodb-local -jar DynamoDBLocal.jar -sharedDb

AWS Credentials

The AWS credentials AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY must exist in your environment as environment variables or in the .aws credential file. These values are used by the aws-sdk to instantiate sdk objects.

You can provide any value for them when using dynamodb-local.

Use the SAM CLI to build and test locally

Set the AWS Credentials:

Copy the sample-vars.json file to the root of your local arSam folder and make changes according to your own personal set up.

    "IS_OFFLINE":"true", // set to true if working online
    "DYNAMODB_ENDPOINT_URL":"http://172.17.0.1:8000", // local endpoint of your local dynamodb server
    "AWS_REGION":"local-env", // can be anything if working locally
    "TABLE_NAME":"ParksAr", // local DynamoDB table name
    "NAME_CACHE_TABLE_NAME":"NameCacheAr", // cache table
    "CONFIG_TABLE_NAME":"ConfigAr" // config table

Navigate to the folder containing template.yaml

Build your application with the sam build command.

arSam$ sam build

Use the sam local start-api to run the API locally on port 3000.

arSam$ sam local start-api
arSam$ curl http://localhost:3000/

You can also use yarn build & yarn start-full to build and start the API locally.

Connecting to remote AWS DynamoDB endpoints (for migrations, etc)

DynamoDB functionality is universally inherited from dynamodb which is exported from the baseLayer. By default, the DynamoDB endpoint is dynamodb.<region>.amazonaws.com, unless you have the local environment variable IS_OFFLINE=true. The DYNAMODB_ENDPOINT_URL environment variable determines which endpoint dynamodb will point to.

Local connections

export IS_OFFLINE=true
export DYNAMODB_ENDPOINT_URL="http://172.17.0.1:8000" // local endpoint of your local dynamodb server

Remote connections

unset IS_OFFLINE
export DYNAMODB_ENDPOINT_URL="https://dynamodb.ca-central-1.amazonaws.com" // remote endpoint for all dynamodb connections in ca-central-1

Testing

Test a single function by invoking it directly with a test event. An event is a JSON document that represents the input that the function receives from the event source. Test events are included in the events folder in this project.

Run functions locally and invoke them with the sam local invoke command.

arSam$ sam local invoke HelloWorldFunction --event events/event.json

The SAM CLI reads the application template to determine the API's routes and the functions that they invoke. The Events property on each function's definition includes the route and method for each path.

      Events:
        HelloWorld:
          Type: Api
          Properties:
            Path: /hello
            Method: get

Run the suite of unit tests with yarn test:

arSam$ yarn test

With SAM, Lambda and layer dependencies are stored in their respective nodejs folder upon running sam build, not the common node_modules folder. Since Jest looks for dependencies in the node_modules folder, a symlink is created in the build step so Jest can find layer dependencies outside of a SAM docker container environment.

Because of this, dependency mapping does not exist prior to sam build and therefore sam build is included in the yarn test script.

Additionally, Lambdas with layer dependencies import the layer using require:

const { layerFn } = require(/opt/layer);

The /opt directory is only available at runtime within the SAM docker container after running sam build && sam local start-api. Jest cannot be mapped to the opt directory. To work around this, Jest is configured to look for the respective layer resources using moduleNameMapper.

"jest": {
  ...
  "moduleNameMapper": [
    "^/opt/baseLayer": "<rootDir>/.aws-sam/build/BaseLayer/baseLayer",
    "^/opt/constantsLayer": "<rootDir>/.aws-sam/build/ConstantsLayer/constantsLayer",
    ...,
    "^/opt/subAreaLayer": "<rootDir>/.aws-sam/build/subAreaLayer/subAreaLayer"
  ]
}

The configuration above tells Jest to look for layer resources in the build folder. We tell Jest to look here instead of the /layer folder because all the layer's dependencies are available within the build folder via symlink after running sam build.

Deployment Pipeline

Github Actions

On push to the Main branch, three actions run:

  1. Lint
  2. Unit Tests
  3. Deploy to dev

The deploy to dev orchestrates deployment to AWS dev.

Deploying to test and prod

Test pipeline is triggered by publishing a release that is marked as a pre-release.

Prod pipeline is triggered by removing the pre-release tag from a release.

Deploying to AWS

sam build
sam deploy --guided

The first command will build the source of your application. The second command will package and deploy your application to AWS, with a series of prompts:

You can find your API Gateway Endpoint URL in the output values displayed after deployment.

Fetch, tail, and filter Lambda function logs

To simplify troubleshooting, SAM CLI has a command called sam logs. sam logs lets you fetch logs generated by your deployed Lambda function from the command line. In addition to printing the logs on the terminal, this command has several nifty features to help you quickly find the bug.

NOTE: This command works for all AWS Lambda functions; not just the ones you deploy using SAM.

arSam$ sam logs -n ConfigGet --stack-name ar-api --tail

You can find more information and examples about filtering Lambda function logs in the SAM CLI Documentation.

Resources

See the AWS SAM developer guide for an introduction to SAM specification, the SAM CLI, and serverless application concepts.