From 6027ce3595589a14be5bcfe598c7584fa3719aab Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 1 Aug 2022 06:09:19 +0000 Subject: [PATCH] Build(deps): Bump github.com/aws/aws-lambda-go from 1.32.1 to 1.34.1 Bumps [github.com/aws/aws-lambda-go](https://github.com/aws/aws-lambda-go) from 1.32.1 to 1.34.1. - [Release notes](https://github.com/aws/aws-lambda-go/releases) - [Commits](https://github.com/aws/aws-lambda-go/compare/v1.32.1...v1.34.1) --- updated-dependencies: - dependency-name: github.com/aws/aws-lambda-go dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] --- go.mod | 2 +- go.sum | 4 +- .../aws/aws-lambda-go/events/alb.go | 4 +- .../aws/aws-lambda-go/events/apigw.go | 33 ++--- .../aws/aws-lambda-go/events/appsync.go | 8 +- .../aws-lambda-go/events/attributevalue.go | 11 +- .../aws/aws-lambda-go/lambda/entry.go | 12 +- .../lambda/extensions_api_client.go | 90 +++++++++++++ .../aws/aws-lambda-go/lambda/handler.go | 25 ++++ .../aws/aws-lambda-go/lambda/invoke_loop.go | 119 ++++++++++++------ .../aws/aws-lambda-go/lambda/rpc.go | 33 ----- .../lambda/{function.go => rpc_function.go} | 33 +++++ .../aws/aws-lambda-go/lambda/sigterm.go | 53 ++++++++ vendor/modules.txt | 2 +- 14 files changed, 317 insertions(+), 112 deletions(-) create mode 100644 vendor/github.com/aws/aws-lambda-go/lambda/extensions_api_client.go delete mode 100644 vendor/github.com/aws/aws-lambda-go/lambda/rpc.go rename vendor/github.com/aws/aws-lambda-go/lambda/{function.go => rpc_function.go} (68%) create mode 100644 vendor/github.com/aws/aws-lambda-go/lambda/sigterm.go diff --git a/go.mod b/go.mod index 29866082..e331d604 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,7 @@ go 1.17 require ( github.com/BurntSushi/toml v1.1.0 - github.com/aws/aws-lambda-go v1.32.1 + github.com/aws/aws-lambda-go v1.34.1 github.com/cppforlife/cobrautil v0.0.0-20200514214827-bb86e6965d72 github.com/cppforlife/go-cli-ui v0.0.0-20200505234325-512793797f05 github.com/google/gofuzz v1.2.0 diff --git a/go.sum b/go.sum index ca639894..66761119 100644 --- a/go.sum +++ b/go.sum @@ -1,7 +1,7 @@ github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I= github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ= -github.com/aws/aws-lambda-go v1.32.1 h1:ls0FU8Mt7ayJszb945zFkUfzxhkQTli8mpJstVcDtCY= -github.com/aws/aws-lambda-go v1.32.1/go.mod h1:jwFe2KmMsHmffA1X2R09hH6lFzJQxzI8qK17ewzbQMM= +github.com/aws/aws-lambda-go v1.34.1 h1:M3a/uFYBjii+tDcOJ0wL/WyFi2550FHoECdPf27zvOs= +github.com/aws/aws-lambda-go v1.34.1/go.mod h1:jwFe2KmMsHmffA1X2R09hH6lFzJQxzI8qK17ewzbQMM= github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI= github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5PlCu98SY8svDHJxuZscDgtXS6KTTbou5AhLI= github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= diff --git a/vendor/github.com/aws/aws-lambda-go/events/alb.go b/vendor/github.com/aws/aws-lambda-go/events/alb.go index 7da6547c..ec5ee282 100644 --- a/vendor/github.com/aws/aws-lambda-go/events/alb.go +++ b/vendor/github.com/aws/aws-lambda-go/events/alb.go @@ -10,7 +10,7 @@ type ALBTargetGroupRequest struct { MultiValueHeaders map[string][]string `json:"multiValueHeaders,omitempty"` RequestContext ALBTargetGroupRequestContext `json:"requestContext"` IsBase64Encoded bool `json:"isBase64Encoded"` - Body string `json:"body,omitempty"` + Body string `json:"body"` } // ALBTargetGroupRequestContext contains the information to identify the load balancer invoking the lambda @@ -29,6 +29,6 @@ type ALBTargetGroupResponse struct { StatusDescription string `json:"statusDescription"` Headers map[string]string `json:"headers"` MultiValueHeaders map[string][]string `json:"multiValueHeaders"` - Body string `json:"body"` + Body string `json:"body,omitempty"` IsBase64Encoded bool `json:"isBase64Encoded"` } diff --git a/vendor/github.com/aws/aws-lambda-go/events/apigw.go b/vendor/github.com/aws/aws-lambda-go/events/apigw.go index 47c4db4e..04ac73f6 100644 --- a/vendor/github.com/aws/aws-lambda-go/events/apigw.go +++ b/vendor/github.com/aws/aws-lambda-go/events/apigw.go @@ -30,22 +30,23 @@ type APIGatewayProxyResponse struct { // APIGatewayProxyRequestContext contains the information to identify the AWS account and resources invoking the // Lambda function. It also includes Cognito identity information for the caller. type APIGatewayProxyRequestContext struct { - AccountID string `json:"accountId"` - ResourceID string `json:"resourceId"` - OperationName string `json:"operationName,omitempty"` - Stage string `json:"stage"` - DomainName string `json:"domainName"` - DomainPrefix string `json:"domainPrefix"` - RequestID string `json:"requestId"` - Protocol string `json:"protocol"` - Identity APIGatewayRequestIdentity `json:"identity"` - ResourcePath string `json:"resourcePath"` - Path string `json:"path"` - Authorizer map[string]interface{} `json:"authorizer"` - HTTPMethod string `json:"httpMethod"` - RequestTime string `json:"requestTime"` - RequestTimeEpoch int64 `json:"requestTimeEpoch"` - APIID string `json:"apiId"` // The API Gateway rest API Id + AccountID string `json:"accountId"` + ResourceID string `json:"resourceId"` + OperationName string `json:"operationName,omitempty"` + Stage string `json:"stage"` + DomainName string `json:"domainName"` + DomainPrefix string `json:"domainPrefix"` + RequestID string `json:"requestId"` + ExtendedRequestID string `json:"extendedRequestId"` + Protocol string `json:"protocol"` + Identity APIGatewayRequestIdentity `json:"identity"` + ResourcePath string `json:"resourcePath"` + Path string `json:"path"` + Authorizer map[string]interface{} `json:"authorizer"` + HTTPMethod string `json:"httpMethod"` + RequestTime string `json:"requestTime"` + RequestTimeEpoch int64 `json:"requestTimeEpoch"` + APIID string `json:"apiId"` // The API Gateway rest API Id } // APIGatewayV2HTTPRequest contains data coming from the new HTTP API Gateway diff --git a/vendor/github.com/aws/aws-lambda-go/events/appsync.go b/vendor/github.com/aws/aws-lambda-go/events/appsync.go index 662fbc71..37682b9e 100644 --- a/vendor/github.com/aws/aws-lambda-go/events/appsync.go +++ b/vendor/github.com/aws/aws-lambda-go/events/appsync.go @@ -2,7 +2,7 @@ package events import "encoding/json" -// AppSyncResolverTemplate represents the requests from AppSync to Lambda +// Deprecated: AppSyncResolverTemplate does not represent resolver events sent by AppSync. Instead directly model your input schema, or use map[string]string, json.RawMessage, interface{}, etc.. type AppSyncResolverTemplate struct { Version string `json:"version"` Operation AppSyncOperation `json:"operation"` @@ -31,13 +31,13 @@ type AppSyncCognitoIdentity struct { DefaultAuthStrategy string `json:"defaultAuthStrategy"` } -// AppSyncOperation specifies the operation type supported by Lambda operations +// Deprecated: not used by any event schema type AppSyncOperation string const ( - // OperationInvoke lets AWS AppSync know to call your Lambda function for every GraphQL field resolver + // Deprecated: not used by any event schema OperationInvoke AppSyncOperation = "Invoke" - // OperationBatchInvoke instructs AWS AppSync to batch requests for the current GraphQL field + // Deprecated: not used by any event schema OperationBatchInvoke AppSyncOperation = "BatchInvoke" ) diff --git a/vendor/github.com/aws/aws-lambda-go/events/attributevalue.go b/vendor/github.com/aws/aws-lambda-go/events/attributevalue.go index d702e9b1..f582d30f 100644 --- a/vendor/github.com/aws/aws-lambda-go/events/attributevalue.go +++ b/vendor/github.com/aws/aws-lambda-go/events/attributevalue.go @@ -68,6 +68,15 @@ func (av DynamoDBAttributeValue) Number() string { return av.value.(string) } +// Int64 provides access to an attribute of type Number. +// DynamoDB sends the values as strings. For convenience this method +// provides conversion to int. +// Method panics if the attribute is not of type Number. +func (av DynamoDBAttributeValue) Int64() (int64, error) { + number := av.Number() + return strconv.ParseInt(number, 10, 64) +} + // Integer provides access to an attribute of type Number. // DynamoDB sends the values as strings. For convenience this method // provides conversion to int. If the value cannot be represented by @@ -76,7 +85,7 @@ func (av DynamoDBAttributeValue) Number() string { // Method panics if the attribute is not of type Number. func (av DynamoDBAttributeValue) Integer() (int64, error) { number := av.Number() - value, err := strconv.ParseInt(number, 10, 64) + value, err := av.Int64() if err == nil { return value, nil } diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/entry.go b/vendor/github.com/aws/aws-lambda-go/lambda/entry.go index f71ac455..c935e236 100644 --- a/vendor/github.com/aws/aws-lambda-go/lambda/entry.go +++ b/vendor/github.com/aws/aws-lambda-go/lambda/entry.go @@ -4,7 +4,6 @@ package lambda import ( "context" - "errors" "log" "os" ) @@ -70,20 +69,11 @@ type startFunction struct { } var ( - // This allows users to save a little bit of coldstart time in the download, by the dependencies brought in for RPC support. - // The tradeoff is dropping compatibility with the go1.x runtime, functions must be "Custom Runtime" instead. - // To drop the rpc dependencies, compile with `-tags lambda.norpc` - rpcStartFunction = &startFunction{ - env: "_LAMBDA_SERVER_PORT", - f: func(_ string, _ Handler) error { - return errors.New("_LAMBDA_SERVER_PORT was present but the function was compiled without RPC support") - }, - } runtimeAPIStartFunction = &startFunction{ env: "AWS_LAMBDA_RUNTIME_API", f: startRuntimeAPILoop, } - startFunctions = []*startFunction{rpcStartFunction, runtimeAPIStartFunction} + startFunctions = []*startFunction{runtimeAPIStartFunction} // This allows end to end testing of the Start functions, by tests overwriting this function to keep the program alive logFatalf = log.Fatalf diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/extensions_api_client.go b/vendor/github.com/aws/aws-lambda-go/lambda/extensions_api_client.go new file mode 100644 index 00000000..e17292b3 --- /dev/null +++ b/vendor/github.com/aws/aws-lambda-go/lambda/extensions_api_client.go @@ -0,0 +1,90 @@ +package lambda + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "io/ioutil" + "net/http" +) + +const ( + headerExtensionName = "Lambda-Extension-Name" + headerExtensionIdentifier = "Lambda-Extension-Identifier" + extensionAPIVersion = "2020-01-01" +) + +type extensionAPIEventType string + +const ( + extensionInvokeEvent extensionAPIEventType = "INVOKE" //nolint:deadcode,unused,varcheck + extensionShutdownEvent extensionAPIEventType = "SHUTDOWN" //nolint:deadcode,unused,varcheck +) + +type extensionAPIClient struct { + baseURL string + httpClient *http.Client +} + +func newExtensionAPIClient(address string) *extensionAPIClient { + client := &http.Client{ + Timeout: 0, // connections to the extensions API are never expected to time out + } + endpoint := "http://" + address + "/" + extensionAPIVersion + "/extension/" + return &extensionAPIClient{ + baseURL: endpoint, + httpClient: client, + } +} + +func (c *extensionAPIClient) register(name string, events ...extensionAPIEventType) (string, error) { + url := c.baseURL + "register" + body, _ := json.Marshal(struct { + Events []extensionAPIEventType `json:"events"` + }{ + Events: events, + }) + + req, _ := http.NewRequest(http.MethodPost, url, bytes.NewReader(body)) + req.Header.Add(headerExtensionName, name) + res, err := c.httpClient.Do(req) + if err != nil { + return "", fmt.Errorf("failed to register extension: %v", err) + } + defer res.Body.Close() + _, _ = io.Copy(ioutil.Discard, res.Body) + + if res.StatusCode != http.StatusOK { + return "", fmt.Errorf("failed to register extension, got response status: %d %s", res.StatusCode, http.StatusText(res.StatusCode)) + } + + return res.Header.Get(headerExtensionIdentifier), nil +} + +type extensionEventResponse struct { + EventType extensionAPIEventType + // ... the rest not implemented +} + +func (c *extensionAPIClient) next(id string) (response extensionEventResponse, err error) { + url := c.baseURL + "event/next" + + req, _ := http.NewRequest(http.MethodGet, url, nil) + req.Header.Add(headerExtensionIdentifier, id) + res, err := c.httpClient.Do(req) + if err != nil { + err = fmt.Errorf("failed to get extension event: %v", err) + return + } + defer res.Body.Close() + _, _ = io.Copy(ioutil.Discard, res.Body) + + if res.StatusCode != http.StatusOK { + err = fmt.Errorf("failed to register extension, got response status: %d %s", res.StatusCode, http.StatusText(res.StatusCode)) + return + } + + err = json.NewDecoder(res.Body).Decode(&response) + return +} diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/handler.go b/vendor/github.com/aws/aws-lambda-go/lambda/handler.go index 354459b1..d23a789b 100644 --- a/vendor/github.com/aws/aws-lambda-go/lambda/handler.go +++ b/vendor/github.com/aws/aws-lambda-go/lambda/handler.go @@ -23,6 +23,8 @@ type handlerOptions struct { jsonResponseEscapeHTML bool jsonResponseIndentPrefix string jsonResponseIndentValue string + enableSIGTERM bool + sigtermCallbacks []func() } type Option func(*handlerOptions) @@ -73,6 +75,26 @@ func WithSetIndent(prefix, indent string) Option { }) } +// WithEnableSIGTERM enables SIGTERM behavior within the Lambda platform on container spindown. +// SIGKILL will occur ~500ms after SIGTERM. +// Optionally, an array of callback functions to run on SIGTERM may be provided. +// +// Usage: +// lambda.StartWithOptions( +// func (event any) (any, error) { +// return event, nil +// }, +// lambda.WithEnableSIGTERM(func() { +// log.Print("function container shutting down...") +// }) +// ) +func WithEnableSIGTERM(callbacks ...func()) Option { + return Option(func(h *handlerOptions) { + h.sigtermCallbacks = append(h.sigtermCallbacks, callbacks...) + h.enableSIGTERM = true + }) +} + func validateArguments(handler reflect.Type) (bool, error) { handlerTakesContext := false if handler.NumIn() > 2 { @@ -139,6 +161,9 @@ func newHandler(handlerFunc interface{}, options ...Option) *handlerOptions { for _, option := range options { option(h) } + if h.enableSIGTERM { + enableSIGTERM(h.sigtermCallbacks) + } h.Handler = reflectHandler(handlerFunc, h) return h } diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/invoke_loop.go b/vendor/github.com/aws/aws-lambda-go/lambda/invoke_loop.go index dca2bf68..f73689ba 100644 --- a/vendor/github.com/aws/aws-lambda-go/lambda/invoke_loop.go +++ b/vendor/github.com/aws/aws-lambda-go/lambda/invoke_loop.go @@ -3,13 +3,16 @@ package lambda import ( + "context" "encoding/json" "fmt" "log" + "os" "strconv" "time" "github.com/aws/aws-lambda-go/lambda/messages" + "github.com/aws/aws-lambda-go/lambdacontext" ) const ( @@ -17,87 +20,121 @@ const ( nsPerMS = int64(time.Millisecond / time.Nanosecond) ) +// TODO: replace with time.UnixMillis after dropping version <1.17 from CI workflows +func unixMS(ms int64) time.Time { + return time.Unix(ms/msPerS, (ms%msPerS)*nsPerMS) +} + // startRuntimeAPILoop will return an error if handling a particular invoke resulted in a non-recoverable error func startRuntimeAPILoop(api string, handler Handler) error { client := newRuntimeAPIClient(api) - function := NewFunction(handler) + h := newHandler(handler) for { invoke, err := client.next() if err != nil { return err } - - err = handleInvoke(invoke, function) - if err != nil { + if err = handleInvoke(invoke, h); err != nil { return err } } } // handleInvoke returns an error if the function panics, or some other non-recoverable error occurred -func handleInvoke(invoke *invoke, function *Function) error { - functionRequest, err := convertInvokeRequest(invoke) +func handleInvoke(invoke *invoke, handler *handlerOptions) error { + // set the deadline + deadline, err := parseDeadline(invoke) if err != nil { - return fmt.Errorf("unexpected error occurred when parsing the invoke: %v", err) + return reportFailure(invoke, lambdaErrorResponse(err)) } + ctx, cancel := context.WithDeadline(handler.baseContext, deadline) + defer cancel() - functionResponse := &messages.InvokeResponse{} - if err := function.Invoke(functionRequest, functionResponse); err != nil { - return fmt.Errorf("unexpected error occurred when invoking the handler: %v", err) + // set the invoke metadata values + lc := lambdacontext.LambdaContext{ + AwsRequestID: invoke.id, + InvokedFunctionArn: invoke.headers.Get(headerInvokedFunctionARN), } - - if functionResponse.Error != nil { - errorPayload := safeMarshal(functionResponse.Error) - log.Printf("%s", errorPayload) - if err := invoke.failure(errorPayload, contentTypeJSON); err != nil { - return fmt.Errorf("unexpected error occurred when sending the function error to the API: %v", err) + if err := parseClientContext(invoke, &lc.ClientContext); err != nil { + return reportFailure(invoke, lambdaErrorResponse(err)) + } + if err := parseCognitoIdentity(invoke, &lc.Identity); err != nil { + return reportFailure(invoke, lambdaErrorResponse(err)) + } + ctx = lambdacontext.NewContext(ctx, &lc) + + // set the trace id + traceID := invoke.headers.Get(headerTraceID) + os.Setenv("_X_AMZN_TRACE_ID", traceID) + // nolint:staticcheck + ctx = context.WithValue(ctx, "x-amzn-trace-id", traceID) + + // call the handler, marshal any returned error + response, invokeErr := callBytesHandlerFunc(ctx, invoke.payload, handler.Handler.Invoke) + if invokeErr != nil { + if err := reportFailure(invoke, invokeErr); err != nil { + return err } - if functionResponse.Error.ShouldExit { + if invokeErr.ShouldExit { return fmt.Errorf("calling the handler function resulted in a panic, the process should exit") } return nil } - - if err := invoke.success(functionResponse.Payload, contentTypeJSON); err != nil { + if err := invoke.success(response, contentTypeJSON); err != nil { return fmt.Errorf("unexpected error occurred when sending the function functionResponse to the API: %v", err) } return nil } -// convertInvokeRequest converts an invoke from the Runtime API, and unpacks it to be compatible with the shape of a `lambda.Function` InvokeRequest. -func convertInvokeRequest(invoke *invoke) (*messages.InvokeRequest, error) { - deadlineEpochMS, err := strconv.ParseInt(invoke.headers.Get(headerDeadlineMS), 10, 64) - if err != nil { - return nil, fmt.Errorf("failed to parse contents of header: %s", headerDeadlineMS) +func reportFailure(invoke *invoke, invokeErr *messages.InvokeResponse_Error) error { + errorPayload := safeMarshal(invokeErr) + log.Printf("%s", errorPayload) + if err := invoke.failure(errorPayload, contentTypeJSON); err != nil { + return fmt.Errorf("unexpected error occurred when sending the function error to the API: %v", err) } - deadlineS := deadlineEpochMS / msPerS - deadlineNS := (deadlineEpochMS % msPerS) * nsPerMS + return nil +} - res := &messages.InvokeRequest{ - InvokedFunctionArn: invoke.headers.Get(headerInvokedFunctionARN), - XAmznTraceId: invoke.headers.Get(headerTraceID), - RequestId: invoke.id, - Deadline: messages.InvokeRequest_Timestamp{ - Seconds: deadlineS, - Nanos: deadlineNS, - }, - Payload: invoke.payload, +func callBytesHandlerFunc(ctx context.Context, payload []byte, handler bytesHandlerFunc) (response []byte, invokeErr *messages.InvokeResponse_Error) { + defer func() { + if err := recover(); err != nil { + invokeErr = lambdaPanicResponse(err) + } + }() + response, err := handler(ctx, payload) + if err != nil { + return nil, lambdaErrorResponse(err) } + return response, nil +} - clientContextJSON := invoke.headers.Get(headerClientContext) - if clientContextJSON != "" { - res.ClientContext = []byte(clientContextJSON) +func parseDeadline(invoke *invoke) (time.Time, error) { + deadlineEpochMS, err := strconv.ParseInt(invoke.headers.Get(headerDeadlineMS), 10, 64) + if err != nil { + return time.Time{}, fmt.Errorf("failed to parse deadline: %v", err) } + return unixMS(deadlineEpochMS), nil +} +func parseCognitoIdentity(invoke *invoke, out *lambdacontext.CognitoIdentity) error { cognitoIdentityJSON := invoke.headers.Get(headerCognitoIdentity) if cognitoIdentityJSON != "" { - if err := json.Unmarshal([]byte(invoke.headers.Get(headerCognitoIdentity)), res); err != nil { - return nil, fmt.Errorf("failed to unmarshal cognito identity json: %v", err) + if err := json.Unmarshal([]byte(cognitoIdentityJSON), out); err != nil { + return fmt.Errorf("failed to unmarshal cognito identity json: %v", err) } } + return nil +} - return res, nil +func parseClientContext(invoke *invoke, out *lambdacontext.ClientContext) error { + clientContextJSON := invoke.headers.Get(headerClientContext) + if clientContextJSON != "" { + if err := json.Unmarshal([]byte(clientContextJSON), out); err != nil { + return fmt.Errorf("failed to unmarshal client context json: %v", err) + } + } + return nil } func safeMarshal(v interface{}) []byte { diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/rpc.go b/vendor/github.com/aws/aws-lambda-go/lambda/rpc.go deleted file mode 100644 index 8c232a98..00000000 --- a/vendor/github.com/aws/aws-lambda-go/lambda/rpc.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved - -//go:build !lambda.norpc -// +build !lambda.norpc - -package lambda - -import ( - "errors" - "log" - "net" - "net/rpc" -) - -func init() { - // Register `startFunctionRPC` to be run if the _LAMBDA_SERVER_PORT environment variable is set. - // This happens when the runtime for the function is configured as `go1.x`. - // The value of the environment variable will be passed as the first argument to `startFunctionRPC`. - rpcStartFunction.f = startFunctionRPC -} - -func startFunctionRPC(port string, handler Handler) error { - lis, err := net.Listen("tcp", "localhost:"+port) - if err != nil { - log.Fatal(err) - } - err = rpc.Register(NewFunction(handler)) - if err != nil { - log.Fatal("failed to register handler function") - } - rpc.Accept(lis) - return errors.New("accept should not have returned") -} diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/function.go b/vendor/github.com/aws/aws-lambda-go/lambda/rpc_function.go similarity index 68% rename from vendor/github.com/aws/aws-lambda-go/lambda/function.go rename to vendor/github.com/aws/aws-lambda-go/lambda/rpc_function.go index e6fe464f..0c8e798e 100644 --- a/vendor/github.com/aws/aws-lambda-go/lambda/function.go +++ b/vendor/github.com/aws/aws-lambda-go/lambda/rpc_function.go @@ -1,10 +1,17 @@ // Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. +//go:build !lambda.norpc +// +build !lambda.norpc + package lambda import ( "context" "encoding/json" + "errors" + "log" + "net" + "net/rpc" "os" "time" @@ -12,6 +19,32 @@ import ( "github.com/aws/aws-lambda-go/lambdacontext" ) +func init() { + // Register `startFunctionRPC` to be run if the _LAMBDA_SERVER_PORT environment variable is set. + // This happens when the runtime for the function is configured as `go1.x`. + // The value of the environment variable will be passed as the first argument to `startFunctionRPC`. + // This allows users to save a little bit of coldstart time in the download, by the dependencies brought in for RPC support. + // The tradeoff is dropping compatibility with the RPC mode of the go1.x runtime. + // To drop the rpc dependencies, compile with `-tags lambda.norpc` + startFunctions = append([]*startFunction{{ + env: "_LAMBDA_SERVER_PORT", + f: startFunctionRPC, + }}, startFunctions...) +} + +func startFunctionRPC(port string, handler Handler) error { + lis, err := net.Listen("tcp", "localhost:"+port) + if err != nil { + log.Fatal(err) + } + err = rpc.Register(NewFunction(handler)) + if err != nil { + log.Fatal("failed to register handler function") + } + rpc.Accept(lis) + return errors.New("accept should not have returned") +} + // Function struct which wrap the Handler // // Deprecated: The Function type is public for the go1.x runtime internal use of the net/rpc package diff --git a/vendor/github.com/aws/aws-lambda-go/lambda/sigterm.go b/vendor/github.com/aws/aws-lambda-go/lambda/sigterm.go new file mode 100644 index 00000000..b742e911 --- /dev/null +++ b/vendor/github.com/aws/aws-lambda-go/lambda/sigterm.go @@ -0,0 +1,53 @@ +// Copyright 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. + +package lambda + +import ( + "log" + "os" + "os/signal" + "syscall" +) + +// enableSIGTERM configures an optional list of sigtermHandlers to run on process shutdown. +// This non-default behavior is enabled within Lambda using the extensions API. +func enableSIGTERM(sigtermHandlers []func()) { + // for fun, we'll also optionally register SIGTERM handlers + if len(sigtermHandlers) > 0 { + signaled := make(chan os.Signal, 1) + signal.Notify(signaled, syscall.SIGTERM) + go func() { + <-signaled + for _, f := range sigtermHandlers { + f() + } + }() + } + + // detect if we're actually running within Lambda + endpoint := os.Getenv("AWS_LAMBDA_RUNTIME_API") + if endpoint == "" { + log.Print("WARNING! AWS_LAMBDA_RUNTIME_API environment variable not found. Skipping attempt to register internal extension...") + return + } + + // Now to do the AWS Lambda specific stuff. + // The default Lambda behavior is for functions to get SIGKILL at the end of lifetime, or after a timeout. + // Any use of the Lambda extension register API enables SIGTERM to be sent to the function process before the SIGKILL. + // We'll register an extension that does not listen for any lifecycle events named "GoLangEnableSIGTERM". + // The API will respond with an ID we need to pass in future requests. + client := newExtensionAPIClient(endpoint) + id, err := client.register("GoLangEnableSIGTERM") + if err != nil { + log.Printf("WARNING! Failed to register internal extension! SIGTERM events may not be enabled! err: %v", err) + return + } + + // We didn't actually register for any events, but we need to call /next anyways to let the API know we're done initalizing. + // Because we didn't register for any events, /next will never return, so we'll do this in a go routine that is doomed to stay blocked. + go func() { + _, err := client.next(id) + log.Printf("WARNING! Reached expected unreachable code! Extension /next call expected to block forever! err: %v", err) + }() + +} diff --git a/vendor/modules.txt b/vendor/modules.txt index 50102dde..876a8cf0 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -2,7 +2,7 @@ ## explicit; go 1.16 github.com/BurntSushi/toml github.com/BurntSushi/toml/internal -# github.com/aws/aws-lambda-go v1.32.1 +# github.com/aws/aws-lambda-go v1.34.1 ## explicit; go 1.18 github.com/aws/aws-lambda-go/events github.com/aws/aws-lambda-go/lambda