forked from imjerrybao/apex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
function.go
227 lines (188 loc) · 5.02 KB
/
function.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
// Package function implements higher-level functionality for dealing with Lambda functions.
package function
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/apex/apex/runtime"
"github.com/apex/apex/shim"
"github.com/apex/apex/utils"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/service/lambda"
"github.com/aws/aws-sdk-go/service/lambda/lambdaiface"
"github.com/jpillora/archive"
)
// Errors.
var (
ErrUnchanged = errors.New("function: unchanged")
)
// InvokeError records an error from an invocation.
type InvokeError struct {
Message string `json:"errorMessage"`
Type string `json:"errorType"`
Stack []string `json:"stackTrace"`
Handled bool
}
// Error message.
func (e *InvokeError) Error() string {
return e.Message
}
// Config for a Lambda function.
type Config struct {
Name string `json:"name"`
Description string `json:"description"`
Runtime string `json:"runtime"`
Memory int64 `json:"memory"`
Timeout int64 `json:"timeout"`
Role string `json:"role"`
}
// Function represents a Lambda function, with configuration loaded
// from the "package.json" file on disk. Operations are performed
// against the function directory as the CWD, so os.Chdir() first.
type Function struct {
Config
Path string
Service lambdaiface.LambdaAPI
runtime runtime.Runtime
}
// Open the package.json file and prime the config.
func (f *Function) Open() error {
p, err := os.Open(filepath.Join(f.Path, "package.json"))
if err != nil {
return err
}
if err := json.NewDecoder(p).Decode(&f.Config); err != nil {
return err
}
r, err := runtime.ByName(f.Runtime)
if err != nil {
return err
}
f.runtime = r
return nil
}
// Deploy generates a zip and creates or updates the function.
func (f *Function) Deploy() error {
zip, err := f.ZipBytes()
if err != nil {
return err
}
info, err := f.Info()
if e, ok := err.(awserr.Error); ok {
if e.Code() == "ResourceNotFoundException" {
return f.Create(zip)
}
}
if err != nil {
return err
}
remoteHash := *info.Configuration.CodeSha256
localHash := utils.Sha256(zip)
if localHash == remoteHash {
return ErrUnchanged
}
return f.Update(zip)
}
// Info returns the function information.
func (f *Function) Info() (*lambda.GetFunctionOutput, error) {
return f.Service.GetFunction(&lambda.GetFunctionInput{
FunctionName: &f.Name,
})
}
// Update the function with the given `zip`.
func (f *Function) Update(zip []byte) error {
_, err := f.Service.UpdateFunctionCode(&lambda.UpdateFunctionCodeInput{
FunctionName: &f.Name,
Publish: aws.Bool(true),
ZipFile: zip,
})
return err
}
// Create the function with the given `zip`.
func (f *Function) Create(zip []byte) error {
_, err := f.Service.CreateFunction(&lambda.CreateFunctionInput{
FunctionName: &f.Name,
Description: &f.Description,
MemorySize: &f.Memory,
Timeout: &f.Timeout,
Runtime: aws.String(f.runtime.Name()),
Handler: aws.String(f.runtime.Handler()),
Role: aws.String(f.Role),
Publish: aws.Bool(true),
Code: &lambda.FunctionCode{
ZipFile: zip,
},
})
return err
}
// Request invokes the remote Lambda function, returning the response and logs.
func (f *Function) Request(event, context interface{}) (reply, logs io.Reader, err error) {
eventBytes, err := json.Marshal(event)
if err != nil {
return nil, nil, err
}
contextBytes, err := json.Marshal(context)
if err != nil {
return nil, nil, err
}
res, err := f.Service.Invoke(&lambda.InvokeInput{
ClientContext: aws.String(base64.StdEncoding.EncodeToString(contextBytes)),
FunctionName: aws.String(f.Name),
InvocationType: aws.String("RequestResponse"),
LogType: aws.String("Tail"),
Qualifier: aws.String("$LATEST"),
Payload: eventBytes,
})
if err != nil {
return nil, nil, err
}
if res.FunctionError != nil {
e := &InvokeError{
Handled: *res.FunctionError == "Handled",
}
if err := json.Unmarshal(res.Payload, e); err != nil {
return nil, nil, err
}
return nil, nil, e
}
logs = base64.NewDecoder(base64.StdEncoding, strings.NewReader(*res.LogResult))
reply = bytes.NewReader(res.Payload)
return reply, logs, nil
}
// Zip returns the zipped contents of the function.
func (f *Function) Zip() (io.Reader, error) {
buf := new(bytes.Buffer)
zip := archive.NewZipWriter(buf)
if r, ok := f.runtime.(runtime.CompiledRuntime); ok {
if err := r.Compile(); err != nil {
return nil, fmt.Errorf("compiling: %s", err)
}
}
if f.runtime.Shimmed() {
zip.AddBytes("index.js", shim.MustAsset("index.js"))
zip.AddBytes("byline.js", shim.MustAsset("byline.js"))
}
if err := zip.AddDir(f.Path); err != nil {
return nil, err
}
if err := zip.Close(); err != nil {
return nil, err
}
return buf, nil
}
// ZipBytes returns the generated zip as bytes.
func (f *Function) ZipBytes() ([]byte, error) {
r, err := f.Zip()
if err != nil {
return nil, err
}
return ioutil.ReadAll(r)
}