-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
86 lines (74 loc) · 2.44 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//go:generate linegen
package main
import (
"encoding/json"
"fmt"
"log"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/kelseyhightower/envconfig"
"github.com/pkg/errors"
"go.uber.org/zap"
"github.com/microfactory/line/line"
)
// Context provides information about Lambda execution environment.
type Context struct {
FunctionName string `json:"function_name"`
FunctionVersion string `json:"function_version"`
InvokedFunctionARN string `json:"invoked_function_arn"`
MemoryLimitInMB int `json:"memory_limit_in_mb,string"`
AWSRequestID string `json:"aws_request_id"`
LogGroupName string `json:"log_group_name"`
LogStreamName string `json:"log_stream_name"`
RemainingTimeInMillis func() int64 `json:"-"`
}
//Handle is the entrypoint to our Lambda core, it "routes" invocations from specific Lambda functions to specific handlers based on a regexp of the function ARN
func Handle(ev json.RawMessage, ctx *Context) (interface{}, error) {
logs, err := zap.NewProduction()
if err != nil {
log.Fatalf("failed to create logger: %+v", err)
}
conf := &line.Conf{}
err = envconfig.Process("LINE", conf)
if err != nil {
logs.Fatal("failed to process env config", zap.Error(err))
}
sess, err := session.NewSession(
&aws.Config{
Region: aws.String(conf.AWSRegion),
Credentials: credentials.NewStaticCredentials(
conf.AWSAccessKeyID,
conf.AWSSecretAccessKey,
"",
),
},
)
if err != nil {
logs.Fatal("failed to setup aws session", zap.Error(err))
}
svc := &line.Services{
SQS: sqs.New(sess),
DB: dynamodb.New(sess),
Logs: logs,
}
//report loaded configuration for debugging purposes
logs.Info("loaded configuration", zap.String("conf", fmt.Sprintf("%+v", conf)), zap.String("ctx", fmt.Sprintf("%+v", ctx)))
//find a handler that has a name that matches the the calling Lambda ARN
var testedExp []string
for exp, handler := range line.Handlers {
if exp.MatchString(ctx.InvokedFunctionARN) {
return handler(
conf,
svc,
ev,
)
}
testedExp = append(testedExp, exp.String())
}
//error not found
return nil, errors.Errorf("none of the tested handlers (%s) matched ARN '%s'", strings.Join(testedExp, ", "), ctx.InvokedFunctionARN)
}