Skip to content

Commit dd65554

Browse files
authored
Update _X_AMZN_TRACE_ID on every invoke (#269)
1 parent 4a86f66 commit dd65554

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-0
lines changed

lambda/function.go

+2
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ package lambda
55
import (
66
"context"
77
"encoding/json"
8+
"os"
89
"reflect"
910
"time"
1011

@@ -63,6 +64,7 @@ func (fn *Function) Invoke(req *messages.InvokeRequest, response *messages.Invok
6364
invokeContext = lambdacontext.NewContext(invokeContext, lc)
6465

6566
invokeContext = context.WithValue(invokeContext, "x-amzn-trace-id", req.XAmznTraceId)
67+
os.Setenv("_X_AMZN_TRACE_ID", req.XAmznTraceId)
6668

6769
payload, err := fn.handler.Invoke(invokeContext, req.Payload)
6870
if err != nil {

lambda/function_test.go

+64
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,14 @@ import (
77
"encoding/json"
88
"errors"
99
"fmt"
10+
"os"
1011
"testing"
1112
"time"
1213

1314
"github.com/aws/aws-lambda-go/lambda/messages"
1415
"github.com/aws/aws-lambda-go/lambdacontext"
1516
"github.com/stretchr/testify/assert"
17+
"github.com/stretchr/testify/require"
1618
)
1719

1820
type testWrapperHandler func(ctx context.Context, input []byte) (interface{}, error)
@@ -140,3 +142,65 @@ func TestContextPlumbing(t *testing.T) {
140142
`
141143
assert.JSONEq(t, expected, string(response.Payload))
142144
}
145+
146+
func TestXAmznTraceID(t *testing.T) {
147+
type XRayResponse struct {
148+
Env string
149+
Ctx string
150+
}
151+
152+
srv := &Function{handler: testWrapperHandler(
153+
func(ctx context.Context, input []byte) (interface{}, error) {
154+
return &XRayResponse{
155+
Env: os.Getenv("_X_AMZN_TRACE_ID"),
156+
Ctx: ctx.Value("x-amzn-trace-id").(string),
157+
}, nil
158+
},
159+
)}
160+
161+
sequence := []struct {
162+
Input string
163+
Expected string
164+
}{
165+
{
166+
"",
167+
`{"Env": "", "Ctx": ""}`,
168+
},
169+
{
170+
"dummyid",
171+
`{"Env": "dummyid", "Ctx": "dummyid"}`,
172+
},
173+
{
174+
"",
175+
`{"Env": "", "Ctx": ""}`,
176+
},
177+
{
178+
"123dummyid",
179+
`{"Env": "123dummyid", "Ctx": "123dummyid"}`,
180+
},
181+
{
182+
"",
183+
`{"Env": "", "Ctx": ""}`,
184+
},
185+
{
186+
"",
187+
`{"Env": "", "Ctx": ""}`,
188+
},
189+
{
190+
"567",
191+
`{"Env": "567", "Ctx": "567"}`,
192+
},
193+
{
194+
"hihihi",
195+
`{"Env": "hihihi", "Ctx": "hihihi"}`,
196+
},
197+
}
198+
199+
for i, test := range sequence {
200+
var response messages.InvokeResponse
201+
err := srv.Invoke(&messages.InvokeRequest{XAmznTraceId: test.Input}, &response)
202+
require.NoError(t, err, "failed test sequence[%d]", i)
203+
assert.JSONEq(t, test.Expected, string(response.Payload), "failed test sequence[%d]", i)
204+
}
205+
206+
}

0 commit comments

Comments
 (0)