Skip to content

Commit

Permalink
init commit
Browse files Browse the repository at this point in the history
  • Loading branch information
nthienan committed Apr 9, 2023
0 parents commit e5e19a2
Show file tree
Hide file tree
Showing 13 changed files with 813 additions and 0 deletions.
28 changes: 28 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[**/*.md]
trim_trailing_whitespace = false

[**/*.go]
indent_size = 4

[Makefile]
indent_style = tab
indent_size = 4

[Dockerfile]
indent_size = 4

[VERSION]
insert_final_newline = false
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
build
22 changes: 22 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "main",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/main.go"
},
{
"name": "Test",
"type": "go",
"request": "launch",
"mode": "test",
"program": "${fileDirname}"
}
]
}
11 changes: 11 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module github.com/nthienan/aws-dynamodb-cache-lambda-extension

go 1.19

require (
github.com/aws/aws-sdk-go v1.44.239
github.com/gorilla/mux v1.8.0
gopkg.in/yaml.v2 v2.4.0
)

require github.com/jmespath/go-jmespath v0.4.0 // indirect
46 changes: 46 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
github.com/aws/aws-sdk-go v1.44.239 h1:AenB6byCYGSBb30q99CGYqFbqpLpWrTidzm7MzxtuPo=
github.com/aws/aws-sdk-go v1.44.239/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI=
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
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/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/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 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
129 changes: 129 additions & 0 deletions internal/extension/client.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
package extension

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
)

// RegisterResponse is the body of the response for /register
type RegisterResponse struct {
FunctionName string `json:"functionName"`
FunctionVersion string `json:"functionVersion"`
Handler string `json:"handler"`
}

// NextEventResponse is the response for /event/next
type NextEventResponse struct {
EventType EventType `json:"eventType"`
DeadlineMs int64 `json:"deadlineMs"`
RequestID string `json:"requestId"`
InvokedFunctionArn string `json:"invokedFunctionArn"`
Tracing Tracing `json:"tracing"`
}

// Tracing is part of the response for /event/next
type Tracing struct {
Type string `json:"type"`
Value string `json:"value"`
}

// EventType represents the type of events recieved from /event/next
type EventType string

const (
// Invoke is a lambda invoke
Invoke EventType = "INVOKE"

// Shutdown is a shutdown event for the environment
Shutdown EventType = "SHUTDOWN"

extensionNameHeader = "Lambda-Extension-Name"
extensionIdentiferHeader = "Lambda-Extension-Identifier"
)

// Client is a simple client for the Lambda Extensions API
type Client struct {
baseURL string
httpClient *http.Client
extensionID string
}

// NewClient returns a Lambda Extensions API client
func NewClient(awsLambdaRuntimeAPI string) *Client {
baseURL := fmt.Sprintf("http://%s/2020-01-01/extension", awsLambdaRuntimeAPI)
return &Client{
baseURL: baseURL,
httpClient: &http.Client{},
}
}

// Register will register the extension with the Extensions API
func (e *Client) Register(ctx context.Context, filename string) (*RegisterResponse, error) {
const action = "/register"
url := e.baseURL + action

reqBody, err := json.Marshal(map[string]interface{}{
"events": []EventType{Invoke, Shutdown},
})
if err != nil {
return nil, err
}
httpReq, err := http.NewRequestWithContext(ctx, "POST", url, bytes.NewBuffer(reqBody))
if err != nil {
return nil, err
}
httpReq.Header.Set(extensionNameHeader, filename)
httpRes, err := e.httpClient.Do(httpReq)
if err != nil {
return nil, err
}
if httpRes.StatusCode != 200 {
return nil, fmt.Errorf("request failed with status %s", httpRes.Status)
}
defer httpRes.Body.Close()
body, err := io.ReadAll(httpRes.Body)
if err != nil {
return nil, err
}
res := RegisterResponse{}
err = json.Unmarshal(body, &res)
if err != nil {
return nil, err
}
e.extensionID = httpRes.Header.Get(extensionIdentiferHeader)
return &res, nil
}

// NextEvent blocks while long polling for the next lambda invoke or shutdown
func (e *Client) NextEvent(ctx context.Context) (*NextEventResponse, error) {
const action = "/event/next"
url := e.baseURL + action

httpReq, err := http.NewRequestWithContext(ctx, "GET", url, nil)
if err != nil {
return nil, err
}
httpReq.Header.Set(extensionIdentiferHeader, e.extensionID)
httpRes, err := e.httpClient.Do(httpReq)
if err != nil {
return nil, err
}
if httpRes.StatusCode != 200 {
return nil, fmt.Errorf("request failed with status %s", httpRes.Status)
}
defer httpRes.Body.Close()
body, err := io.ReadAll(httpRes.Body)
if err != nil {
return nil, err
}
res := NextEventResponse{}
err = json.Unmarshal(body, &res)
if err != nil {
return nil, err
}
return &res, nil
}
82 changes: 82 additions & 0 deletions internal/extension/entry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
package extension

import (
"log"
"os"
"strconv"

"github.com/nthienan/aws-dynamodb-cache-lambda-extension/internal/plugins"
"gopkg.in/yaml.v2"
)

// Constants definition
const (
Parameters = "parameters"
Dynamodb = "dynamodb"
FileName = "/var/task/config.yaml"
InitializeCacheOnStartup = "CACHE_EXTENSION_INIT_STARTUP"
)

// Struct for storing CacheConfiguration
type CacheConfig struct {
DynamoDb []plugins.DynamoDbConfiguration
}

var cacheConfig = CacheConfig{}

// Initialize cache and start the background process to refresh cache
func InitCacheExtensions() {
// Read the cache config file
data := LoadConfigFile()

// Unmarshal the configuration to struct
err := yaml.Unmarshal([]byte(data), &cacheConfig)
if err != nil {
log.Fatalf(plugins.PrintPrefix, "error: %v", err)
}

// Initialize Cache
println(plugins.PrintPrefix, "Initializing cache ...")
InitCache()
println(plugins.PrintPrefix, "Cache successfully loaded")
}

// Initialize individual cache
func InitCache() {

// Read Lambda env variable
var initCache = os.Getenv(InitializeCacheOnStartup)
var initCacheInBool = false
if initCache != "" {
cacheInBool, err := strconv.ParseBool(initCache)
if err != nil {
panic(plugins.PrintPrefix + "Error while converting CACHE_EXTENSION_INIT_STARTUP env variable " +
initCache)
} else {
initCacheInBool = cacheInBool
}
}

// Initialize map and load data from individual services if "CACHE_EXTENSION_INIT_STARTUP" = true
plugins.InitDynamodb(cacheConfig.DynamoDb, initCacheInBool)
}

// Route request to corresponding cache handlers
func RouteCache(cacheType string, name string) string {
switch cacheType {
case Dynamodb:
return plugins.FetchDynamoDbCache(name)
default:
return ""
}
}

// Load the config file
func LoadConfigFile() string {
data, err := os.ReadFile(FileName)
if err != nil {
panic(err)
}

return string(data)
}
35 changes: 35 additions & 0 deletions internal/ipc/ipc.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package ipc

import (
"github.com/nthienan/aws-dynamodb-cache-lambda-extension/internal/extension"
"github.com/nthienan/aws-dynamodb-cache-lambda-extension/internal/plugins"
"github.com/gorilla/mux"
"net/http"
)

// Start begins running the sidecar
func Start(port string) {
go startHTTPServer(port)
}

// Method that responds back with the cached values
func startHTTPServer(port string) {
router := mux.NewRouter()
router.Path("/{cacheType}").Queries("name", "{name}").HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
value := extension.RouteCache(vars["cacheType"], vars["name"])

if len(value) != 0 {
_, _ = w.Write([]byte(value))
} else {
_, _ = w.Write([]byte("No data found"))
}
})

println(plugins.PrintPrefix, "Starting Httpserver on port ", port)
err := http.ListenAndServe(":"+port, router)
if err != nil {
panic(err)
}
}
Loading

0 comments on commit e5e19a2

Please sign in to comment.