Skip to content

Commit

Permalink
Add basic lambda for creating a case (#3)
Browse files Browse the repository at this point in the history
- Accepts a request, performs some basic validation, and saves it to DDB
- Includes shared module for things multiple lambdas will need
- Includes a mock API Gateway so that you can interact with standard curl requests
- Switches to dockerised AWS CLI to create DDB tables
- Includes a basic GitHub Actions test script

To test:
```
make build up test-api
```

For VEGA-1941 #minor
  • Loading branch information
gregtyler authored Aug 29, 2023
1 parent 9dd7f85 commit 6ea60f5
Show file tree
Hide file tree
Showing 17 changed files with 451 additions and 8 deletions.
27 changes: 27 additions & 0 deletions .github/workflows/build.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Test & Build

on:
pull_request:
branches:
- main
push:
branches:
- main
workflow_dispatch:

defaults:
run:
shell: bash

jobs:
build:
name: Build
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: "0"
- name: Build Images
run: make build
- name: Test API
run: make up test-api
18 changes: 11 additions & 7 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,28 @@ export AWS_ACCESS_KEY_ID ?= X
export AWS_SECRET_ACCESS_KEY ?= X

build:
# Nothing to build yet
docker compose build --parallel lambda-create apigw

up:
docker-compose up -d
docker compose up -d apigw
make create-tables

down:
docker-compose down
docker compose down

test-api:
curl -XPOST localhost:9000/create -d '{"uid":"test","version":"1"}' -i

create-tables:
aws --endpoint-url http://localhost:8030 dynamodb create-table \
--no-cli-pager \
docker compose run --rm aws dynamodb describe-table --table-name deeds || \
docker compose run --rm aws dynamodb create-table \
--table-name deeds \
--attribute-definitions AttributeName=uid,AttributeType=S \
--key-schema AttributeName=uid,KeyType=HASH \
--billing-mode PAY_PER_REQUEST

aws --endpoint-url http://localhost:8030 dynamodb create-table \
--no-cli-pager \
docker compose run --rm aws dynamodb describe-table --table-name events || \
docker compose run --rm aws dynamodb create-table \
--table-name events \
--attribute-definitions AttributeName=uid,AttributeType=S AttributeName=created,AttributeType=S \
--key-schema AttributeName=uid,KeyType=HASH AttributeName=created,KeyType=RANGE \
Expand Down
32 changes: 31 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,35 @@ version: "3.6"
services:
ddb:
image: amazon/dynamodb-local:latest

lambda-create:
depends_on: [ddb]
build:
context: .
dockerfile: ./lambda/Dockerfile
args:
- DIR=create
environment:
AWS_REGION: eu-west-1
AWS_DYNAMODB_ENDPOINT: http://ddb:8000
AWS_ACCESS_KEY_ID: X
AWS_SECRET_ACCESS_KEY: X
volumes:
- "./lambda/.aws-lambda-rie:/aws-lambda"
entrypoint: /aws-lambda/aws-lambda-rie /var/task/main

apigw:
depends_on: [lambda-create]
build: ./mock-apigw
ports:
- 8030:8000
- 9000:8080

aws:
depends_on: [ddb]
image: amazon/aws-cli:latest
environment:
AWS_ENDPOINT_URL: http://ddb:8000/
AWS_REGION: eu-west-1
AWS_ACCESS_KEY_ID: X
AWS_SECRET_ACCESS_KEY: X
AWS_PAGER: ""
7 changes: 7 additions & 0 deletions go.work
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
go 1.21.0

use (
./lambda/create
./lambda/shared
./mock-apigw
)
13 changes: 13 additions & 0 deletions go.work.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/stretchr/objx v0.1.0 h1:4G4v2dO3VZwixGIRoQ5Lfboy6nUhCyYzaqnIAPPhYs4=
github.com/yuin/goldmark v1.4.13 h1:fVcFKWvrslecOb/tg+Cc05dkeYx540o0FuFt3nUVDoE=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4 h1:6zppjxzCulZykYSLyVDYbneBfbaBIQPYMevg0bEwv2s=
golang.org/x/net v0.1.0 h1:hZ/3BUoy5aId7sCpA/Tc5lt8DkFgdVS2onTpJsZ/fl0=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4 h1:uVc8UZUe6tr40fFVnUP5Oj+veunVezqYl9z7DYw9xzw=
golang.org/x/sys v0.1.0 h1:kunALQeHf1/185U1i0GOB/fy1IPRDDpuoOOqRReG57U=
golang.org/x/term v0.1.0 h1:g6Z6vPFA9dYBAF7DWcH6sCcOntplXsDKcliusYijMlw=
golang.org/x/text v0.4.0 h1:BrVqGRd7+k1DiOgtnFvAkoQEWQvBc25ouMJM6429SFg=
golang.org/x/tools v0.1.12 h1:VveCTK38A2rkS8ZqFY25HIDFscX5X9OoEhJd3quQmXU=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7 h1:9zdDQZ7Thm29KFXgAX/+yaf3eVbP7djjWp/dXAppNCc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
Binary file added lambda/.aws-lambda-rie/aws-lambda-rie
Binary file not shown.
17 changes: 17 additions & 0 deletions lambda/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
FROM golang:1.21.0 AS build-env

ARG DIR
WORKDIR /app

COPY go.work .
COPY go.work.sum .

COPY . .

RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -installsuffix cgo -o /go/bin/main ./lambda/$DIR

FROM alpine:3

COPY --from=build-env /go/bin/main /var/task/main

ENTRYPOINT [ "/var/task/main" ]
11 changes: 11 additions & 0 deletions lambda/create/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module github.com/ministryofjustice/opg-data-lpa-deed/lambda/create

go 1.21

require (
github.com/aws/aws-lambda-go v1.41.0
github.com/aws/aws-sdk-go v1.44.330
github.com/ministryofjustice/opg-go-common v0.0.0-20220816144329-763497f29f90
)

require github.com/jmespath/go-jmespath v0.4.0 // indirect
51 changes: 51 additions & 0 deletions lambda/create/go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
github.com/aws/aws-lambda-go v1.41.0 h1:l/5fyVb6Ud9uYd411xdHZzSf2n86TakxzpvIoz7l+3Y=
github.com/aws/aws-lambda-go v1.41.0/go.mod h1:jwFe2KmMsHmffA1X2R09hH6lFzJQxzI8qK17ewzbQMM=
github.com/aws/aws-sdk-go v1.44.330 h1:kO41s8I4hRYtWSIuMc/O053wmEGfMTT8D4KtPSojUkA=
github.com/aws/aws-sdk-go v1.44.330/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/jmespath/go-jmespath v0.4.0 h1:BEgLn5cpjn8UN1mAw4NjwDrS35OdebyEtFe+9YPoQUg=
github.com/jmespath/go-jmespath v0.4.0/go.mod h1:T8mJZnbsbmF+m6zOOFylbeCJqk5+pHWvzYPziyZiYoo=
github.com/jmespath/go-jmespath/internal/testify v1.5.1 h1:shLQSRRSCCPj3f2gpwzGwWFoC7ycTf1rcQZHOlsJ6N8=
github.com/jmespath/go-jmespath/internal/testify v1.5.1/go.mod h1:L3OGu8Wl2/fWfCI6z80xFu9LTZmf1ZRjMHUOPmWr69U=
github.com/ministryofjustice/opg-go-common v0.0.0-20220816144329-763497f29f90 h1:mxTHIeCYV7LDZPN7C44wwLlBTUsgQ0G8FQprsrsKXaA=
github.com/ministryofjustice/opg-go-common v0.0.0-20220816144329-763497f29f90/go.mod h1:1RmCNi6dkAv8umAgNHp8RkuBoSKLlxp1UtfsGYH7ufc=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.7.2 h1:4jaiDzPyXQvSd7D0EjG45355tLlV3VOECpq10pLC+8s=
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.8 h1:obN1ZagJSUGI0Ek/LBmuj4SNLPfIny3KsKFopxRdj10=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
102 changes: 102 additions & 0 deletions lambda/create/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
package main

import (
"encoding/json"
"log"
"os"
"time"

"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
"github.com/ministryofjustice/opg-data-lpa-deed/lambda/shared"
"github.com/ministryofjustice/opg-go-common/logging"
)

type Response struct {
}

type Logger interface {
Print(...interface{})
}

type Lambda struct {
ddb dynamodbiface.DynamoDBAPI
tableName string
logger Logger
}

func (l *Lambda) HandleEvent(event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
var data shared.Case
log.Print(event)
response := events.APIGatewayProxyResponse{
StatusCode: 500,
Body: "{\"code\":\"INTERNAL_SERVER_ERROR\",\"detail\":\"Internal server error\"}",
}

err := json.Unmarshal([]byte(event.Body), &data)
if err != nil {
l.logger.Print(err)
return shared.ProblemInternalServerError.Respond()
}

if data.Version == "" {
problem := shared.ProblemInvalidRequest
problem.Errors = []shared.FieldError{
{Source: "/version", Detail: "must supply a valid version"},
}

return problem.Respond()
}

data.UpdatedAt = time.Now()

// save to dynamodb
item, err := dynamodbattribute.MarshalMap(data)
if err != nil {
l.logger.Print(err)
return shared.ProblemInternalServerError.Respond()
}

_, err = l.ddb.PutItem(&dynamodb.PutItemInput{
TableName: aws.String(l.tableName),
Item: item,
})

if err != nil {
l.logger.Print(err)
return shared.ProblemInternalServerError.Respond()
}

// respond
body, err := json.Marshal(Response{})

if err != nil {
l.logger.Print(err)
return shared.ProblemInternalServerError.Respond()
}

response.StatusCode = 201
response.Body = string(body)

return response, nil
}

func main() {
sess := session.Must(session.NewSession())

endpoint := os.Getenv("AWS_DYNAMODB_ENDPOINT")
sess.Config.Endpoint = &endpoint

l := &Lambda{
ddb: dynamodb.New(sess),
tableName: "deeds",
logger: logging.New(os.Stdout, "opg-data-lpa-deed"),
}

lambda.Start(l.HandleEvent)
}
9 changes: 9 additions & 0 deletions lambda/shared/case.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package shared

import "time"

type Case struct {
Uid string `json:"uid" dynamodbav:"uid"`
Version string `json:"version" dynamodbav:"version"`
UpdatedAt time.Time `json:"-" dynamodbav:"updatedAt"`
}
3 changes: 3 additions & 0 deletions lambda/shared/go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module github.com/ministryofjustice/opg-data-lpa-deed/lambda/shared

go 1.21.0
71 changes: 71 additions & 0 deletions lambda/shared/problem.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package shared

import (
"encoding/json"
"fmt"
"os"
"strings"
"time"

"github.com/aws/aws-lambda-go/events"
)

type FieldError struct {
Source string `json:"source"`
Detail string `json:"detail"`
}

type Problem struct {
StatusCode int `json:"-"`
Code string `json:"code"`
Detail string `json:"detail"`
Errors []FieldError `json:"errors,omitempty"`
}

type LogEvent struct {
ServiceName string `json:"service_name"`
Timestamp time.Time `json:"timestamp"`
Status int `json:"status"`
Problem Problem `json:"problem"`
ErrorString string `json:"error_string,omitempty"`
}

var ProblemInternalServerError Problem = Problem{
StatusCode: 500,
Code: "INTERNAL_SERVER_ERROR",
Detail: "Internal server error",
}

var ProblemInvalidRequest Problem = Problem{
StatusCode: 400,
Code: "INVALID_REQUEST",
Detail: "Invalid request",
}

func (problem Problem) Respond() (events.APIGatewayProxyResponse, error) {
var errorString = ""
for _, ve := range problem.Errors {
errorString += fmt.Sprintf("%s %s, ", ve.Source, ve.Detail)
}

_ = json.NewEncoder(os.Stdout).Encode(LogEvent{
ServiceName: "opg-data-lpa-deed",
Timestamp: time.Now(),
Status: problem.StatusCode,
Problem: problem,
ErrorString: strings.TrimRight(errorString, ", "),
})

code := problem.StatusCode
body, err := json.Marshal(problem)

if err != nil {
code = 500
body = []byte("{\"code\":\"INTERNAL_SERVER_ERROR\",\"detail\":\"Internal server error\"}")
}

return events.APIGatewayProxyResponse{
StatusCode: code,
Body: string(body),
}, nil
}
Loading

0 comments on commit 6ea60f5

Please sign in to comment.