Skip to content

Build a new service ​

So you wanna build a new service... This guide will explain some of the key files and config you will need to put in place for your service. This guide follows a Node TypeScript Service example.

When building your service, Please make sure you are following our architecture principals

This guide suggests how to structure your service folder for consistency and Luna Engineering best practices

Overview ​

Directory Structure ​

A service needs to live in a folder within the services/ directory. The name of the folder should be the plural name of the service. For example:

engagements - GOOD
engagement - BAD
andi-services - BAD
andis - GOOD

Note the casing should be kebab case. (lowercase and dash delimited)

This is an example directory structure your service should follow as well as some of the files you may require. In this example we will be using the contact service

services/
  | - contacts
    | - build/                   // build folder (is git ignored)
    | - commands/                // lambda source code folder that write, update or delete data
    | - query/                   // lambda source code folder that reads data
    | - subscriber/              // lambda source code folder that handles asyncronous messages
    | - scheduler/               // lambda source code folder that runs on a schedule - CRON
    | - docs/                    // docs folder that holds documentation
    | - utils/                   // common util methods for the service
    | - models/                  // common methods for querying the services databases
    | - lefthook.yml             // git hooks (pre-commit lint, pre-push audit)
    | - .eslintrc.js             // linting
    | - .npmrc                   // enables getting private reg. packages from Gitlab
    | - application.yml          // will hold the cloudformation IAC
    | - build.sh                 // code to build the service
    | - ci.yml                   // will hold the Gitlab CI jobs
    | - jest-dynalite-config.js  // config for jest dynalite
    | - jest.config.js           // test config
    | - package.json             // dependencies 
    | - README.md                // docs about the service
    | - samconfig.toml           // config for deployments to envs
    | - tsconfig.json            // development config for TypeScript
    | - tsconfig.build.json      // build config for TypeScript

Each lambda source code folder will have the following structure:

commands/
  | - __test__                   // mirror of the src folder but with tests
  | - src/
    | - handlers
    | | - createContact.ts       // handler for creating a contact
    | | - deleteContact.ts       // handler for deleting a contact
    | - handler.ts               // entrypoint for the lambda - routes events to respective handlers

Files ​

There are some config files that are required for your service. Lets take a look through each one and explain what it does and what it should contain.

lefthook.yml ​

This file defines the Lefthook git hooks for this service. The root lefthook.yml picks it up. yarn run lint runs on commit when files under this service's folder are staged, and yarn run audit runs on push when the push changes files in this folder. A failed audit blocks the push and shows the /fix-audit command to run. Without this file, lint and audit are only enforced in CI, not locally. root must be the service's path from the repo root, with a trailing slash, and job names must be unique in the repo.

For a service at services/my-service, it should contain the following:

yaml
pre-commit:
  jobs:
    - name: services/my-service lint
      root: services/my-service/
      run: yarn run lint

pre-push:
  jobs:
    - name: services/my-service audit
      root: services/my-service/
      run: yarn run audit
      env:
        AUDIT_REGISTRY_ERROR: warn
      fail_text: 'Fix it before you push: claude "/fix-audit services/my-service", then commit and push again.'

.eslintrc.js ​

This file sets up the eslint configuration for the service.

It should contain the following:

js

const mainEslintConfig = require('../../platform/config/lint/eslint');

module.exports = {
  ...mainEslintConfig,
  ignorePatterns: [
    ...mainEslintConfig.ignorePatterns,
    "build/*"
  ]
}

Note here it extends the main eslint config to prevent repetition of config.

.npmrc ​

This file specifies our private NPM package registry location as well as what auth token to use. This allows the service to install packages from our private Gitlab package registry, for example packages such as @bhag-business-platform/luna-utils

It should contain the following:

@bhag-business-platform:registry=https://gitlab.com/api/v4/projects/71835281/packages/npm/
//gitlab.com/api/v4/projects/71835281/packages/npm/:_authToken=${LUNA_PACKAGE_REGISTRY_PAT}

application.yml ​

This file contains the infrastructure as code for the service. The infrastructure is written for cloudformation - AWS SAM. It will be specific to the service.

If your lambdas require dependencies (node_modules) you will need to include the following LambdaLayer in your Resources: (replacing contacts with your service name)

yml
ContactsModulesLambdaLayer:
  Type: AWS::Serverless::LayerVersion
  Properties:
    LayerName: !Sub ${Environment}-contacts-modules-layer
    ContentUri: build/dependencies
    CompatibleRuntimes:
      - nodejs24.x

Then reference it in your lambdas as follows:

yml
ContactsCommandsFunction:
  Type: AWS::Serverless::Function
  Properties:
    FunctionName: !Sub ${Environment}-contacts-commands-function
    CodeUri: build/commands/src
    Layers:
      - !Ref ContactsModulesLambdaLayer

build.sh ​

This file contains the script to build the service for deployments. It compiles the TypeScript into JavaScript and correctly sets up the build folder structure for SAM to use.

It should contain the following:

sh
#!/bin/sh

rm -fr ./build

tsc -p tsconfig.build.json

yarn install --prod --modules-folder build/dependencies/nodejs/node_modules

You will need to also allow this script to be executed. This can be done with the following command:

$ chmod u+x ./build.sh

Note - If you have some common code and are making use of lambda layers - you will need to update this file. More on this below.

ci.yml ​

This file contains the Gitlab CI configuration for this service. It will use anchors and templates that you can use.

The file may look something like this:

yml
service-contacts:install:
  extends:
    - .luna-node-service-install-template
  variables:
    SERVICE_DIR: contacts

service-contacts:audit:
  extends:
    - .luna-node-service-audit-template
  variables:
    SERVICE_DIR: contacts

service-contacts:build:
  extends: 
    - .luna-node-service-build-template
  variables:
    SERVICE_DIR: contacts

service-contacts:test:
  extends: 
    - .luna-node-service-test-template
  variables:
    SERVICE_DIR: contacts

service-contacts:lint:
  extends: 
    - .luna-node-service-lint-template
  variables:
    SERVICE_DIR: contacts

service-contacts:cfn-lint:
  extends: 
    - .luna-service-cfn-linter-template
  variables:
    SERVICE_DIR: contacts

service-contacts:deploy:lower-environment:
  extends:
    - .luna-service-environment-deploy-template
  environment:
	  name: $CI_COMMIT_REF_SLUG/contacts-service
    url: $DYNAMIC_ENVIRONMENT_URL
  variables:
    SERVICE_DIR: contacts
    ENVIRONMENT: '$CI_COMMIT_REF_NAME'

service-contacts:deploy:staging:
  extends: 
    - .luna-service-staging-deploy-template
  environment:
    name: staging/contacts-service
    url: https://contacts.v2.staging.luna.and.sh
  variables:
    SERVICE_DIR: contacts 

service-contacts:deploy:production:
  extends: 
    - .luna-service-production-deploy-template
  environment:
    name: production/contacts-service
    url: https://contacts.v2.luna.and-digital.com
  variables:
    SERVICE_DIR: contacts

Note it is important to have the environment:name for each deploy step to be environment/serviceName-serivce so that it is unique and grouped to the correct environment. So that outdated deployments can be skipped for production as required.

Note you will find the template definitions of what each job does in platform/ci/services/anchors.yml

Include changes to .gitlab-ci.yml ​

To make sure your CI runs - please include it in main .gitlab-ci.yml file at the root of the repo. Include it in the section that is relevant to services.

yml
...
include: 
  - 'services/emails/ci.yml'
      - 'services/contacts/ci.yml'
...

jest-dynalite-config.js ​

This file specified the jest-dynalite - a mock ddb for jest tests. It uses the DynamoDB resources as defined in appilcation.yml to spin up the mock tables for tests.

The file should look like this:

js
const yaml = require('js-yaml');
const fs = require('fs');
const { CLOUDFORMATION_SCHEMA } = require('cloudformation-js-yaml-schema');

module.exports = {
  tables: () => {
    let cloudformation = yaml.load(fs.readFileSync('./application.yml', 'utf8'), {
      schema: CLOUDFORMATION_SCHEMA,
    });

    const resources = Object.keys(cloudformation.Resources).reduce(
      (acc, curr) => {
        return [
          ...acc,
          {
            ...cloudformation.Resources[curr],
            _ResourceName: curr,
          },
        ];
      },
      [],
    );

    const tables = resources.filter((r) => r.Type === 'AWS::DynamoDB::Table');

    return tables
      .map((r) => {
        let table = r.Properties;
        table.TableName = `Test-${r._ResourceName}`;
        delete table.TimeToLiveSpecification; //errors on dynamo-local
        delete table.PointInTimeRecoverySpecification; //errors on dynamo-local
        delete table.StreamSpecification; //errors on dynamo-local
        delete table.Tags; //errors on dynamo-local
        return table;
      })
      .filter((x) => x);
  },
  basePort: 8003,
};

jest.config.js ​

This file specified the jest testing config.

It should contain the following:

js
const mainJestConfig = require('../../platform/config/test/jest');

const tsconfig = require('./tsconfig.json');
const moduleNameMapper = require('tsconfig-paths-jest')(tsconfig);

module.exports = {
  ...mainJestConfig,
  moduleNameMapper,
  preset: 'jest-dynalite',
};

Note here - this config also extends a base jest config and overrides a few values.

package.json ​

This file contains your scripts, and dependencies that your service needs.

At a minimum this file must contain the following:

json
{
  "name": "contacts-service",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "build": "./build.sh",
    "test": "jest",
    "lint": "eslint .",
    "audit": "../../platform/scripts/run-node-audit.sh",
    "audit:ignore": "yarn audit --json > .yarn-audit.ignore"
  },
  "devDependencies": {
    "@types/jest": "^27.4.1",
    "@typescript-eslint/eslint-plugin": "^5.20.0",
    "@typescript-eslint/parser": "^5.20.0",
    "cloudformation-js-yaml-schema": "^0.4.2",
    "eslint": "^8.13.0",
    "eslint-plugin-security": "^1.5.0",
    "fs": "^0.0.1-security",
    "jest": "^26.6.3",
    "jest-dynalite": "^3.4.4",
    "js-yaml": "^4.1.0",
    "ts-jest": "^26.4.4",
    "tsconfig-paths-jest": "^0.0.1",
    "typescript": "^4.6.3"
  },
  "dependencies": {}
}

You will need to add devDependencies and dependencies as required for your service.

README.md ​

This file contains documentation about the service - it can use images and other files from the docs/ folder. See the Kudos service README.md for a good example of a README for a service

samconfig.toml ​

This file contains the configuration for deploying to different environments.

It will contain parameter definitions for each environment.

At a minimum the file should contain the following:

toml
version = 0.1
[polaris]
[polaris.deploy]
[polaris.deploy.parameters]
stack_name = "polaris-contacts-service"
s3_bucket = "polaris-s3-luna-deployments-and-digital-luna-bucket"
s3_prefix = "polaris/contacts"
region = "eu-west-1"
confirm_changeset = true
capabilities = "CAPABILITY_AUTO_EXPAND CAPABILITY_NAMED_IAM CAPABILITY_IAM"
parameter_overrides = [
  "Environment=\"polaris\""
]

version = 0.1
[sol]
[sol.deploy]
[sol.deploy.parameters]
stack_name = "sol-contacts-service"
s3_bucket = "sol-s3-luna-deployments-and-digital-luna-bucket"
s3_prefix = "sol/contacts"
region = "eu-west-1"
confirm_changeset = true
capabilities = "CAPABILITY_AUTO_EXPAND CAPABILITY_NAMED_IAM CAPABILITY_IAM"
parameter_overrides = [
  "Environment=\"sol\""
]

version = 0.1
[pulsar]
[pulsar.deploy]
[pulsar.deploy.parameters]
stack_name = "pulsar-contacts-service"
s3_bucket = "pulsar-s3-luna-deployments-and-digital-luna-bucket"
s3_prefix = "pulsar/contacts"
region = "eu-west-1"
confirm_changeset = true
capabilities = "CAPABILITY_AUTO_EXPAND CAPABILITY_NAMED_IAM CAPABILITY_IAM"
parameter_overrides = [
  "Environment=\"pulsar\""
]

version = 0.1
[staging]
[staging.deploy]
[staging.deploy.parameters]
stack_name = "staging-contacts-service"
s3_bucket = "staging-s3-luna-deployments-and-digital-luna-bucket"
s3_prefix = "staging/contacts"
region = "eu-west-1"
capabilities = "CAPABILITY_AUTO_EXPAND CAPABILITY_NAMED_IAM CAPABILITY_IAM"
parameter_overrides = [
  "Environment=\"staging\""
]

version = 0.1
[production]
[production.deploy]
[production.deploy.parameters]
stack_name = "production-contacts-service"
s3_bucket = "production-s3-luna-deployments-and-digital-luna-bucket"
s3_prefix = "production/contacts"
region = "eu-west-1"
capabilities = "CAPABILITY_AUTO_EXPAND CAPABILITY_NAMED_IAM CAPABILITY_IAM"
parameter_overrides = [
  "Environment=\"production\""
]

tsconfig.json ​

This file contains the base TypeScript config for this service - which will be used during development and testing.

It should contain the following:

json
{
  "compilerOptions": {
    "baseUrl": ".",
    "target": "es2019",
    "module": "commonjs",
    "allowJs": true,
    "checkJs": true,
    "esModuleInterop": true,
    "outDir": "./build",
  },
  "include": ["commands/**/*", "query/**/*"] // include anything you want to be building
}

tsconfig.build.json ​

This file contains the TypeScript config for building the service. It extends the base but omits tests.

It should contain the following:

json
{
  "extends": "./tsconfig.json",
  "exclude": ["**/__test__/*"]
}

Infrastructure - application.yml ​

When it comes to writting your services infrastructure there are a few conventions and rules you should follow.

Naming ​

Please ensure all resources have a name defined that follows the following format:

ENVIRONMENT-SERVICE-RESOURCE_TYPE
  • ENVIRONMENT - is the environment this is on usually it will be !Sub ${Environment} that will result in it being staging or production or polaris
  • SERVICE - is the plural name of the service - contacts for example
  • RESOURCE_TYPE - is the type of resource you are naming. It should be dash delimited. for example: table when having to specify multiple of the same resource type, e.g. lambdas, make sure the type is the last string (function)

Here are some example:

environment-contacts-commands-function
environment-contacts-scheduler-function
environment-contacts-table
environment-contacts-queue
environment-contacts-deadletter-queue

Some exceptions apply, for example topics or s3 buckets that need to follow a specific convention

API domain ​

All new services on gitlab should use the v2 domain as their api domain.

For example on lower environments they should be:

SERVICE.v2.ENVIRONMENT.dev.luna.and.sh

Stack naming ​

Please ensure your cloudformation stack is named ENVIRONMENT-SERVICE-service

Where ENVIRONMENT is the environment, SERVICE is the name of the service

Shared Code via Lambda Layers. ​

We use the TypeScript compiler to compile TypeScript into JavaScript for our lambdas. Lambda requires all source code for the lambda to be bundled up in one zip.

This presents a problem when shared code and dependencies are required in our lambdas. The way around this is to use Lambda Layers - which allow you to share common code across your lambdas.

If your Lambda uses any dependencies (node_modules) you will be required to create a dependencies lambda layer - and use it in your lambdas. This is already set up in your ./build.sh

However, to get code from a folder outside of the entrypoint of the lambda you will need to create a lambda layer. To do this - follow these steps that follow the example of a "schemas" folder in the contacts service.

Create the Lambda Layer Definition in application.yml ​

Create the following lambda layer resource in your application.yml

yml
Resources:
  ...
  ContactsSchemasLambdaLayer:
    Type: AWS::Serverless::LayerVersion
    Properties:
      LayerName: !Sub ${Environment}-contacts-schemas-layer
      ContentUri: build/layers/schemas
      CompatibleRuntimes:
        - nodejs24.x

Update the ./build.sh script to build the folder correctly ​

Add the following to the ./build.sh script

mkdir -p ./build/layers/schemas/nodejs
mv build/schemas build/layers/schemas/nodejs/schemas

This will ensure correct folder structure for LambdaLayers and Cloudformation to pick up the code and the lambda layer

Update tsconfig.json to understand the correct pathing ​

When the lambda is running it will require the lambda layer from a specific path. When developing locally this can cause some errors - especially when running tests. Therefore we modify the TypeScript config to understand where to look for the files.

json
{
  "compilerOptions": {
    ...
    "paths": {
      "/opt/nodejs/schemas": ["schemas/index"]
    }
  },
  "include": ["commands/**/*", "query/**/*", "schemas/**/*"]
}

This will tell the typescript compiler to also compile the schemas folder as well as map the /opt/nodejs/schemas import to schemas/index - make sure there is an index.js file in that folder.

Update your application code with the correct import ​

Now you can use the schema import as follows:

js
import { createContactSchema } from '/opt/nodejs/schemas';

Troubleshooting - Lambda layer too large ​

AWS enforces a 250MB (unzipped) limit on the total size of a function and its layers. As a service grows - more shared code, more dependencies - the layers can breach this limit and cause deployments to fail.

Until we migrate to AWS SDK v3 (which is modular and dramatically smaller than the bundled v2 SDK), you can reduce the layer size in your ./build.sh as a workaround by stripping the TypeScript declaration files (*.d.ts) that the compiler emits - they aren't needed at runtime. It also helps to print the dependencies layer size at the end of the build so you can keep an eye on how close you are to the limit.

A full ./build.sh with these optimisations, following the schemas/models/utils layer example, looks like this:

sh
#!/bin/sh

rm -fr ./build

tsc -p tsconfig.build.json

yarn install --prod --modules-folder build/dependencies/nodejs/node_modules

mkdir -p ./build/layers/schemas/nodejs
mv build/schemas build/layers/schemas/nodejs/schemas

mkdir -p ./build/layers/models/nodejs
mv build/models build/layers/models/nodejs/models

mkdir -p ./build/layers/utils/nodejs
mv build/utils build/layers/utils/nodejs/utils

echo "Cleaning up build artifacts to reduce Lambda layer size..."

find ./build -name "*.d.ts" -type f -delete

echo "Build complete."

echo "Node modules size (lambda layer limit 250MB):"
du -sh ./build/dependencies/nodejs/node_modules

Made with ❤️ by the Luna team