Skip to content

Commit a6f393e

Browse files
committed
WIP: better refactoring
1 parent 41b9eb2 commit a6f393e

File tree

11 files changed

+439
-291
lines changed

11 files changed

+439
-291
lines changed

cmd/localstack/main.go

Lines changed: 39 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"strconv"
1010
"strings"
1111

12+
"github.com/aws/aws-sdk-go-v2/config"
1213
"github.com/localstack/lambda-runtime-init/internal/aws/xray"
1314
"github.com/localstack/lambda-runtime-init/internal/bootstrap"
1415
"github.com/localstack/lambda-runtime-init/internal/hotreloading"
@@ -24,8 +25,8 @@ import (
2425
func InitLsOpts() *server.LsOpts {
2526
return &server.LsOpts{
2627
// required
27-
RuntimeEndpoint: utils.GetEnvOrDie("LOCALSTACK_RUNTIME_ENDPOINT"),
28-
RuntimeId: utils.GetEnvOrDie("LOCALSTACK_RUNTIME_ID"),
28+
RuntimeEndpoint: utils.MustGetEnv("LOCALSTACK_RUNTIME_ENDPOINT"),
29+
RuntimeId: utils.MustGetEnv("LOCALSTACK_RUNTIME_ID"),
2930
AccountId: utils.GetEnvWithDefault("LOCALSTACK_FUNCTION_ACCOUNT_ID", "000000000000"),
3031
// optional with default
3132
InteropPort: utils.GetEnvWithDefault("LOCALSTACK_INTEROP_PORT", "9563"),
@@ -45,6 +46,19 @@ func InitLsOpts() *server.LsOpts {
4546
}
4647
}
4748

49+
func InitFunctionConfig() server.FunctionConfig {
50+
return server.FunctionConfig{
51+
FunctionName: utils.GetEnvWithDefault("AWS_LAMBDA_FUNCTION_NAME", "test_function"),
52+
FunctionVersion: utils.GetEnvWithDefault("AWS_LAMBDA_FUNCTION_VERSION", "$LATEST"),
53+
FunctionTimeoutSec: utils.GetEnvWithDefault("AWS_LAMBDA_FUNCTION_TIMEOUT", "30"),
54+
InitializationType: utils.GetEnvWithDefault("AWS_LAMBDA_INITIALIZATION_TYPE", "on-demand"),
55+
LogGroupName: utils.GetEnvWithDefault("AWS_LAMBDA_LOG_GROUP_NAME", "/aws/lambda/Functions"),
56+
LogStreamName: utils.GetEnvWithDefault("AWS_LAMBDA_LOG_STREAM_NAME", "$LATEST"),
57+
FunctionMemorySizeMb: utils.GetEnvWithDefault("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", "3008"),
58+
FunctionHandler: utils.GetEnvWithDefault("AWS_LAMBDA_FUNCTION_HANDLER", os.Getenv("_HANDLER")),
59+
}
60+
}
61+
4862
// UnsetLsEnvs unsets environment variables specific to LocalStack to achieve better runtime parity with AWS
4963
func UnsetLsEnvs() {
5064
unsetList := [...]string{
@@ -81,6 +95,9 @@ func main() {
8195

8296
// configuration parsing
8397
lsOpts := InitLsOpts()
98+
functionConf := InitFunctionConfig()
99+
awsEnvConf, _ := config.NewEnvConfig()
100+
84101
UnsetLsEnvs()
85102

86103
// set up logging following the Logrus logging levels: https://github.com/sirupsen/logrus#level-logging
@@ -155,6 +172,7 @@ func main() {
155172
logCollector := logging.NewLogCollector()
156173
localStackLogsEgressApi := logging.NewLocalStackLogsEgressAPI(logCollector)
157174
tracer := tracing.NewLocalStackTracer()
175+
// localSupervisor := supervisor.NewLocalSupervisor()
158176

159177
// build sandbox
160178
sandbox := rapidcore.
@@ -169,6 +187,10 @@ func main() {
169187
SetLogsEgressAPI(localStackLogsEgressApi).
170188
SetTracer(tracer)
171189

190+
// Externally set supervisor for metrics tracking
191+
// sandbox.SetSupervisor(localSupervisor)
192+
// sandbox.SetRuntimeFsRootPath(localSupervisor.RootPath)
193+
172194
// xray daemon
173195
endpoint := "http://" + lsOpts.LocalstackIP + ":" + lsOpts.EdgePort
174196
xrayConfig := xray.NewConfig(endpoint, xRayLogLevel)
@@ -181,9 +203,6 @@ func main() {
181203
})
182204
d.Run() // async
183205

184-
defaultInterop := sandbox.DefaultInteropServer()
185-
interopServer := server.NewCustomInteropServer(lsOpts, defaultInterop, logCollector)
186-
sandbox.SetInteropServer(interopServer)
187206
if len(handler) > 0 {
188207
sandbox.SetHandler(handler)
189208
}
@@ -194,25 +213,27 @@ func main() {
194213

195214
// initialize all flows and start runtime API
196215
sandboxContext, internalStateFn := sandbox.Create()
197-
// Populate our custom interop server
198-
interopServer.SetSandboxContext(sandboxContext)
199-
interopServer.SetInternalStateGetter(internalStateFn)
216+
// Populate our interop server
217+
sandbox.DefaultInteropServer().SetSandboxContext(sandboxContext)
218+
sandbox.DefaultInteropServer().SetInternalStateGetter(internalStateFn)
200219

201-
// get timeout
202-
invokeTimeoutEnv := utils.GetEnvOrDie("AWS_LAMBDA_FUNCTION_TIMEOUT") // TODO: collect all AWS_* env parsing
203-
invokeTimeoutSeconds, err := strconv.Atoi(invokeTimeoutEnv)
204-
if err != nil {
205-
log.Fatalln(err)
206-
}
207-
go hotreloading.RunHotReloadingListener(interopServer, lsOpts.HotReloadingPaths, fileWatcherContext, lsOpts.FileWatcherStrategy)
220+
localStackService := server.NewLocalStackAPI(sandbox.LambdaInvokeAPI(), bootstrap, logCollector, xrayConfig.Endpoint, lsOpts, functionConf, awsEnvConf)
208221

209222
// start runtime init. It is important to start `InitHandler` synchronously because we need to ensure the
210223
// notification channels and status fields are properly initialized before `AwaitInitialized`
211224
log.Debugln("Starting runtime init.")
212-
server.InitHandler(sandbox.LambdaInvokeAPI(), utils.GetEnvOrDie("AWS_LAMBDA_FUNCTION_VERSION"), int64(invokeTimeoutSeconds), bootstrap, lsOpts.AccountId) // TODO: replace this with a custom init
225+
localStackService.Initialize()
226+
227+
invokeServer := server.NewServer(lsOpts.InteropPort, localStackService)
228+
invokeServer.RegisterOnShutdown(localStackService.Close)
229+
230+
defer invokeServer.Shutdown(context.Background())
231+
232+
go invokeServer.ListenAndServe()
233+
go hotreloading.RunHotReloadingListener(sandbox.DefaultInteropServer(), lsOpts.HotReloadingPaths, fileWatcherContext, lsOpts.FileWatcherStrategy)
213234

214235
log.Debugln("Awaiting initialization of runtime init.")
215-
if err := interopServer.AwaitInitialized(); err != nil {
236+
if err := sandbox.DefaultInteropServer().AwaitInitialized(); err != nil {
216237
// Error cases: ErrInitDoneFailed or ErrInitResetReceived
217238
log.Errorln("Runtime init failed to initialize: " + err.Error() + ". Exiting.")
218239
// NOTE: Sending the error status to LocalStack is handled beforehand in the custom_interop.go through the
@@ -221,7 +242,7 @@ func main() {
221242
}
222243

223244
log.Debugln("Completed initialization of runtime init. Sending status ready to LocalStack.")
224-
if err := interopServer.SendStatus(server.Ready, []byte{}); err != nil {
245+
if err := localStackService.SendStatus(server.Ready, []byte{}); err != nil {
225246
log.Fatalln("Failed to send status ready to LocalStack " + err.Error() + ". Exiting.")
226247
}
227248

go.mod

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ go 1.24
44

55
require (
66
github.com/aws/aws-sdk-go v1.44.298
7+
github.com/aws/aws-sdk-go-v2/config v1.29.14
78
github.com/aws/aws-xray-daemon v0.0.0-20250212175715-5defe1b8d61b
89
github.com/cihub/seelog v0.0.0-20170130134532-f561c5e57575
910
github.com/fsnotify/fsnotify v1.6.0
@@ -16,6 +17,18 @@ require (
1617

1718
require (
1819
github.com/StackExchange/wmi v0.0.0-20190523213315-cbe66965904d // indirect
20+
github.com/aws/aws-sdk-go-v2 v1.36.3 // indirect
21+
github.com/aws/aws-sdk-go-v2/credentials v1.17.67 // indirect
22+
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.30 // indirect
23+
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.34 // indirect
24+
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.34 // indirect
25+
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 // indirect
26+
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.3 // indirect
27+
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.15 // indirect
28+
github.com/aws/aws-sdk-go-v2/service/sso v1.25.3 // indirect
29+
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.30.1 // indirect
30+
github.com/aws/aws-sdk-go-v2/service/sts v1.33.19 // indirect
31+
github.com/aws/smithy-go v1.22.2 // indirect
1932
github.com/go-ole/go-ole v1.2.4 // indirect
2033
github.com/google/uuid v1.6.0 // indirect
2134
github.com/jmespath/go-jmespath v0.4.0 // indirect

go.sum

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,34 @@ github.com/aws/aws-lambda-runtime-interface-emulator v0.0.0-20250423173140-3a077
66
github.com/aws/aws-lambda-runtime-interface-emulator v0.0.0-20250423173140-3a0772eae98d/go.mod h1:J6YoZd6buk2amNl7zFx1jMXq/3qh9zqsFkzNvbQLkDY=
77
github.com/aws/aws-sdk-go v1.44.298 h1:5qTxdubgV7PptZJmp/2qDwD2JL187ePL7VOxsSh1i3g=
88
github.com/aws/aws-sdk-go v1.44.298/go.mod h1:aVsgQcEevwlmQ7qHE9I3h+dtQgpqhFB+i8Phjh7fkwI=
9+
github.com/aws/aws-sdk-go-v2 v1.36.3 h1:mJoei2CxPutQVxaATCzDUjcZEjVRdpsiiXi2o38yqWM=
10+
github.com/aws/aws-sdk-go-v2 v1.36.3/go.mod h1:LLXuLpgzEbD766Z5ECcRmi8AzSwfZItDtmABVkRLGzg=
11+
github.com/aws/aws-sdk-go-v2/config v1.29.14 h1:f+eEi/2cKCg9pqKBoAIwRGzVb70MRKqWX4dg1BDcSJM=
12+
github.com/aws/aws-sdk-go-v2/config v1.29.14/go.mod h1:wVPHWcIFv3WO89w0rE10gzf17ZYy+UVS1Geq8Iei34g=
13+
github.com/aws/aws-sdk-go-v2/credentials v1.17.67 h1:9KxtdcIA/5xPNQyZRgUSpYOE6j9Bc4+D7nZua0KGYOM=
14+
github.com/aws/aws-sdk-go-v2/credentials v1.17.67/go.mod h1:p3C44m+cfnbv763s52gCqrjaqyPikj9Sg47kUVaNZQQ=
15+
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.30 h1:x793wxmUWVDhshP8WW2mlnXuFrO4cOd3HLBroh1paFw=
16+
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.30/go.mod h1:Jpne2tDnYiFascUEs2AWHJL9Yp7A5ZVy3TNyxaAjD6M=
17+
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.34 h1:ZK5jHhnrioRkUNOc+hOgQKlUL5JeC3S6JgLxtQ+Rm0Q=
18+
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.34/go.mod h1:p4VfIceZokChbA9FzMbRGz5OV+lekcVtHlPKEO0gSZY=
19+
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.34 h1:SZwFm17ZUNNg5Np0ioo/gq8Mn6u9w19Mri8DnJ15Jf0=
20+
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.34/go.mod h1:dFZsC0BLo346mvKQLWmoJxT+Sjp+qcVR1tRVHQGOH9Q=
21+
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3 h1:bIqFDwgGXXN1Kpp99pDOdKMTTb5d2KyU5X/BZxjOkRo=
22+
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.3/go.mod h1:H5O/EsxDWyU+LP/V8i5sm8cxoZgc2fdNR9bxlOFrQTo=
23+
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.3 h1:eAh2A4b5IzM/lum78bZ590jy36+d/aFLgKF/4Vd1xPE=
24+
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.12.3/go.mod h1:0yKJC/kb8sAnmlYa6Zs3QVYqaC8ug2AbnNChv5Ox3uA=
25+
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.15 h1:dM9/92u2F1JbDaGooxTq18wmmFzbJRfXfVfy96/1CXM=
26+
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.12.15/go.mod h1:SwFBy2vjtA0vZbjjaFtfN045boopadnoVPhu4Fv66vY=
27+
github.com/aws/aws-sdk-go-v2/service/sso v1.25.3 h1:1Gw+9ajCV1jogloEv1RRnvfRFia2cL6c9cuKV2Ps+G8=
28+
github.com/aws/aws-sdk-go-v2/service/sso v1.25.3/go.mod h1:qs4a9T5EMLl/Cajiw2TcbNt2UNo/Hqlyp+GiuG4CFDI=
29+
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.30.1 h1:hXmVKytPfTy5axZ+fYbR5d0cFmC3JvwLm5kM83luako=
30+
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.30.1/go.mod h1:MlYRNmYu/fGPoxBQVvBYr9nyr948aY/WLUvwBMBJubs=
31+
github.com/aws/aws-sdk-go-v2/service/sts v1.33.19 h1:1XuUZ8mYJw9B6lzAkXhqHlJd/XvaX32evhproijJEZY=
32+
github.com/aws/aws-sdk-go-v2/service/sts v1.33.19/go.mod h1:cQnB8CUnxbMU82JvlqjKR2HBOm3fe9pWorWBza6MBJ4=
933
github.com/aws/aws-xray-daemon v0.0.0-20250212175715-5defe1b8d61b h1:hiV1SQDGCUECdYdKRvfBmIZnoCWggTDauTintGTkIFU=
1034
github.com/aws/aws-xray-daemon v0.0.0-20250212175715-5defe1b8d61b/go.mod h1:1tKEa2CqVzCVcMS59532MHzZP5P0hF682qCGpR/Tl1k=
35+
github.com/aws/smithy-go v1.22.2 h1:6D9hW43xKFrRx/tXXfAlIZc4JI+yQe6snnWcQyxSyLQ=
36+
github.com/aws/smithy-go v1.22.2/go.mod h1:irrKGvNn1InZwb2d7fkIRNucdfwR8R+Ts3wxYa/cJHg=
1137
github.com/cihub/seelog v0.0.0-20170130134532-f561c5e57575 h1:kHaBemcxl8o/pQ5VM1c8PVE1PubbNx3mjUr09OqWGCs=
1238
github.com/cihub/seelog v0.0.0-20170130134532-f561c5e57575/go.mod h1:9d6lWj8KzO/fd/NrVaLscBKmPigpZpn5YawRPw+e3Yo=
1339
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=

internal/aws/xray/daemon.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ func NewConfig(endpoint string, logLevel string) *cfg.Config {
8080
xrayConfig.Endpoint = endpoint
8181
xrayConfig.NoVerifySSL = util.Bool(true) // obvious
8282
xrayConfig.LocalMode = util.Bool(true) // skip EC2 metadata check
83-
xrayConfig.Region = utils.GetEnvOrDie("AWS_REGION")
83+
xrayConfig.Region = utils.MustGetEnv("AWS_REGION")
8484
xrayConfig.Logging.LogLevel = logLevel
8585
//xrayConfig.TotalBufferSizeMB
8686
//xrayConfig.RoleARN = roleARN

internal/hotreloading/listener.go

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ import (
88
"github.com/localstack/lambda-runtime-init/internal/filenotify"
99
"github.com/localstack/lambda-runtime-init/internal/utils"
1010
log "github.com/sirupsen/logrus"
11-
"go.amzn.com/lambda/rapidcore/standalone"
1211
)
1312

1413
type ChangeListener struct {
@@ -70,7 +69,7 @@ func (c *ChangeListener) Watch() {
7069
for _, dir := range toBeRemovedDirs {
7170
err := c.watcher.Remove(dir)
7271
if err != nil {
73-
log.Warnln("Error removing path: ", event.Name, err)
72+
log.WithField("event", event.Name).Warnf("Error removing path: %w", err)
7473
}
7574
}
7675
}
@@ -128,7 +127,7 @@ func (c *ChangeListener) Close() error {
128127
return c.watcher.Close()
129128
}
130129

131-
func ResetListener(changeChannel <-chan bool, server standalone.InteropServer) {
130+
func resetListener(changeChannel <-chan bool, server Resetter) {
132131
for {
133132
_, more := <-changeChannel
134133
if !more {

internal/hotreloading/reloader.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,14 @@ import (
55
"time"
66

77
log "github.com/sirupsen/logrus"
8-
"go.amzn.com/lambda/rapidcore/standalone"
8+
"go.amzn.com/lambda/core/statejson"
99
)
1010

11-
func RunHotReloadingListener(server standalone.InteropServer, targetPaths []string, ctx context.Context, fileWatcherStrategy string) {
11+
type Resetter interface {
12+
Reset(reason string, timeoutMs int64) (*statejson.ResetDescription, error)
13+
}
14+
15+
func RunHotReloadingListener(server Resetter, targetPaths []string, ctx context.Context, fileWatcherStrategy string) {
1216
if len(targetPaths) == 1 && targetPaths[0] == "" {
1317
log.Debugln("Hot reloading disabled.")
1418
return
@@ -23,7 +27,7 @@ func RunHotReloadingListener(server standalone.InteropServer, targetPaths []stri
2327
defer changeListener.Close()
2428
go changeListener.Start()
2529
changeListener.AddTargetPaths(targetPaths)
26-
go ResetListener(changeListener.debouncedChannel, server)
30+
go resetListener(changeListener.debouncedChannel, server)
2731

2832
<-ctx.Done()
2933
log.Infoln("Closing down filewatcher.")

internal/server/handler.go

Lines changed: 73 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,58 +1,83 @@
11
package server
22

33
import (
4-
"os"
4+
"encoding/json"
5+
"net/http"
56
"strings"
6-
"time"
77

8-
"github.com/localstack/lambda-runtime-init/internal/utils"
9-
"go.amzn.com/lambda/interop"
10-
"go.amzn.com/lambda/rapidcore"
11-
"go.amzn.com/lambda/rapidcore/env"
8+
"github.com/go-chi/chi"
9+
log "github.com/sirupsen/logrus"
10+
"go.amzn.com/lambda/fatalerror"
11+
"go.amzn.com/lambda/rapi/model"
12+
"go.amzn.com/lambda/rapidcore/standalone"
1213
)
1314

14-
func InitHandler(sandbox rapidcore.LambdaInvokeAPI, functionVersion string, timeout int64, bs interop.Bootstrap, accountId string) (time.Time, time.Time) {
15-
additionalFunctionEnvironmentVariables := map[string]string{}
16-
17-
// Add default Env Vars if they were not defined. This is a required otherwise 1p Python2.7, Python3.6, and
18-
// possibly others pre runtime API runtimes will fail. This will be overwritten if they are defined on the system.
19-
additionalFunctionEnvironmentVariables["AWS_LAMBDA_LOG_GROUP_NAME"] = "/aws/lambda/Functions"
20-
additionalFunctionEnvironmentVariables["AWS_LAMBDA_LOG_STREAM_NAME"] = "$LATEST"
21-
additionalFunctionEnvironmentVariables["AWS_LAMBDA_FUNCTION_VERSION"] = "$LATEST"
22-
additionalFunctionEnvironmentVariables["AWS_LAMBDA_FUNCTION_MEMORY_SIZE"] = "3008"
23-
additionalFunctionEnvironmentVariables["AWS_LAMBDA_FUNCTION_NAME"] = "test_function"
24-
25-
// Forward Env Vars from the running system (container) to what the function can view. Without this, Env Vars will
26-
// not be viewable when the function runs.
27-
for _, env := range os.Environ() {
28-
// Split the env into by the first "=". This will account for if the env var's value has a '=' in it
29-
envVar := strings.SplitN(env, "=", 2)
30-
additionalFunctionEnvironmentVariables[envVar[0]] = envVar[1]
15+
func NewServer(port string, api *LocalStackAPI) *http.Server {
16+
r := chi.NewRouter()
17+
18+
r.Post("/invoke", InvokeHandler(api))
19+
20+
return &http.Server{
21+
Addr: ":" + port,
22+
Handler: r,
23+
}
24+
}
25+
26+
func InvokeHandler(api *LocalStackAPI) http.HandlerFunc {
27+
return func(w http.ResponseWriter, r *http.Request) {
28+
// TODO: We shouldn't be using a custom request body here,
29+
// instead we should be forwarding the entire boto3/AWS request
30+
var req InvokeRequest
31+
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
32+
log.WithError(err).Error("Failed to decode invoke request")
33+
}
34+
35+
proxyReq, err := http.NewRequest(r.Method, r.URL.String(), strings.NewReader(req.Payload))
36+
if err != nil {
37+
log.WithError(err).Error("Failed to create proxy request")
38+
w.WriteHeader(http.StatusInternalServerError)
39+
return
40+
}
41+
42+
// Ensure we always return a response to caller
43+
defer func() {
44+
w.WriteHeader(200)
45+
w.Write([]byte("OK"))
46+
}()
47+
48+
// TODO: Add client context to request or as a header ("X-Amz-Client-Context")
49+
// Copy relevant headers from original request
50+
proxyReq.Header.Set("X-Amzn-Trace-Id", req.TraceId)
51+
proxyReq.Header.Set("X-Amzn-Request-Id", req.InvokeId)
52+
53+
proxyResponseWriter := &standalone.ResponseWriterProxy{}
54+
55+
// Use standalone's Execute which handles all the error cases
56+
standalone.Execute(proxyResponseWriter, proxyReq, api)
57+
58+
if err := api.AfterInvoke(); err != nil {
59+
log.WithError(err).Error("Post-invocation step failed.")
60+
}
61+
62+
api.CollectAndSendLogs(req.InvokeId)
63+
64+
var errorResponse model.ErrorResponse
65+
isValidError := json.Unmarshal(proxyResponseWriter.Body, &errorResponse) == nil
66+
67+
if !proxyResponseWriter.IsError() || !isValidError {
68+
api.SendResponse(req.InvokeId, proxyResponseWriter.Body)
69+
return
70+
}
71+
72+
switch errorResponse.ErrorType {
73+
case string(fatalerror.FunctionOversizedResponse):
74+
// Emulator returns incorrect response
75+
errorResponse.ErrorMessage = "Response payload size exceeded maximum allowed payload size (6291556 bytes)."
76+
if modifiedBody, err := json.Marshal(errorResponse); err == nil {
77+
proxyResponseWriter.Body = modifiedBody
78+
}
79+
}
80+
api.SendError(req.InvokeId, proxyResponseWriter.Body)
3181
}
3282

33-
initStart := time.Now()
34-
// pass to rapid
35-
sandbox.Init(&interop.Init{
36-
Handler: utils.GetEnvWithDefault("AWS_LAMBDA_FUNCTION_HANDLER", os.Getenv("_HANDLER")),
37-
AwsKey: os.Getenv("AWS_ACCESS_KEY_ID"),
38-
AwsSecret: os.Getenv("AWS_SECRET_ACCESS_KEY"),
39-
AwsSession: os.Getenv("AWS_SESSION_TOKEN"),
40-
AccountID: accountId,
41-
XRayDaemonAddress: utils.GetEnvWithDefault("AWS_XRAY_DAEMON_ADDRESS", "127.0.0.1:2000"),
42-
FunctionName: utils.GetEnvWithDefault("AWS_LAMBDA_FUNCTION_NAME", "test_function"),
43-
FunctionVersion: functionVersion,
44-
45-
// TODO: Implement runtime management controls
46-
// https://aws.amazon.com/blogs/compute/introducing-aws-lambda-runtime-management-controls/
47-
RuntimeInfo: interop.RuntimeInfo{
48-
ImageJSON: "{}",
49-
Arn: "",
50-
Version: ""},
51-
CustomerEnvironmentVariables: additionalFunctionEnvironmentVariables,
52-
SandboxType: interop.SandboxClassic,
53-
Bootstrap: bs,
54-
EnvironmentVariables: env.NewEnvironment(),
55-
}, timeout*1000)
56-
initEnd := time.Now()
57-
return initStart, initEnd
5883
}

0 commit comments

Comments
 (0)