Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support setting an optional base context for functions. #287

Merged
merged 4 commits into from
May 30, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 17 additions & 3 deletions lambda/entry.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
package lambda

import (
"context"
"log"
"net"
"net/rpc"
Expand Down Expand Up @@ -37,8 +38,12 @@ import (
// Where "TIn" and "TOut" are types compatible with the "encoding/json" standard library.
// See https://golang.org/pkg/encoding/json/#Unmarshal for how deserialization behaves
func Start(handler interface{}) {
wrappedHandler := NewHandler(handler)
StartHandler(wrappedHandler)
StartWithContext(context.Background(), handler)
}

// StartWithContext is the same as Start except sets the base context for the function.
func StartWithContext(ctx context.Context, handler interface{}) {
StartHandlerWithContext(ctx, NewHandler(handler))
}

// StartHandler takes in a Handler wrapper interface which can be implemented either by a
Expand All @@ -48,12 +53,21 @@ func Start(handler interface{}) {
//
// func Invoke(context.Context, []byte) ([]byte, error)
func StartHandler(handler Handler) {
StartHandlerWithContext(context.Background(), handler)
}

// StartHandlerWithContext is the same as StartHandler except sets the base context for the function.
//
// Handler implementation requires a single "Invoke()" function:
//
// func Invoke(context.Context, []byte) ([]byte, error)
func StartHandlerWithContext(ctx context.Context, handler Handler) {
port := os.Getenv("_LAMBDA_SERVER_PORT")
lis, err := net.Listen("tcp", "localhost:"+port)
if err != nil {
log.Fatal(err)
}
err = rpc.Register(NewFunction(handler))
err = rpc.Register(NewFunctionWithContext(ctx, handler))
if err != nil {
log.Fatal("failed to register handler function")
}
Expand Down
20 changes: 19 additions & 1 deletion lambda/function.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,31 @@ import (
// Function struct which wrap the Handler
type Function struct {
handler Handler
context context.Context
}

// NewFunction which creates a Function with a given Handler
func NewFunction(handler Handler) *Function {
return &Function{handler: handler}
}

// NewFunctionWithContext which creates a Function with a given Handler and sets the base Context.
func NewFunctionWithContext(ctx context.Context, handler Handler) *Function {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can this be private? NewFunction doesn't really have a reason to be in the public API, so it'd be nice to not increase surface area further.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bmoffatt removed this function. I decided to go for the http.Request.WithContext approach instead, except that WithContext is not exported on the Function. I think that's a little cleaner 👍

return &Function{
context: ctx,
handler: handler,
}
}

// Context returns the base context used for the fn.
func (fn *Function) Context() context.Context {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be private, or moved inside of Invoke. The public visibility of the other Function methods is done only as a requirement of the net/ipc library.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bmoffatt made this un exported 👍

if fn.context == nil {
return context.Background()
}

return fn.context
}

// Ping method which given a PingRequest and a PingResponse parses the PingResponse
func (fn *Function) Ping(req *messages.PingRequest, response *messages.PingResponse) error {
*response = messages.PingResponse{}
Expand All @@ -44,7 +62,7 @@ func (fn *Function) Invoke(req *messages.InvokeRequest, response *messages.Invok
}()

deadline := time.Unix(req.Deadline.Seconds, req.Deadline.Nanos).UTC()
invokeContext, cancel := context.WithDeadline(context.Background(), deadline)
invokeContext, cancel := context.WithDeadline(fn.Context(), deadline)
defer cancel()

lc := &lambdacontext.LambdaContext{
Expand Down
26 changes: 26 additions & 0 deletions lambda/function_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,32 @@ func TestInvoke(t *testing.T) {
assert.Equal(t, deadline.UnixNano(), responseValue)
}

func TestInvokeWithContext(t *testing.T) {
key := struct{}{}
srv := &Function{
handler: testWrapperHandler(
func(ctx context.Context, input []byte) (interface{}, error) {
assert.Equal(t, "dummy", ctx.Value(key))
if deadline, ok := ctx.Deadline(); ok {
return deadline.UnixNano(), nil
}
return nil, errors.New("!?!?!?!?!")
}),
context: context.WithValue(context.Background(), key, "dummy"),
}
deadline := time.Now()
var response messages.InvokeResponse
err := srv.Invoke(&messages.InvokeRequest{
Deadline: messages.InvokeRequest_Timestamp{
Seconds: deadline.Unix(),
Nanos: int64(deadline.Nanosecond()),
}}, &response)
assert.NoError(t, err)
var responseValue int64
assert.NoError(t, json.Unmarshal(response.Payload, &responseValue))
assert.Equal(t, deadline.UnixNano(), responseValue)
}

type CustomError struct{}

func (e CustomError) Error() string { return fmt.Sprintf("Something bad happened!") }
Expand Down