Debian Codegraph @

instrumentation/github.com/aws/aws-lambda-go/otellambda/lambdatest_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otellambda_test
5
6 import (
7 "context"
8 "encoding/json"
9 "fmt"
10 "log"
11 "reflect"
12 "strconv"
13 "strings"
14 "sync"
15 "testing"
16 "time"
17
18 "github.com/aws/aws-lambda-go/lambda"
19 "github.com/aws/aws-lambda-go/lambdacontext"
20 "github.com/stretchr/testify/assert"
21 "go.opentelemetry.io/otel/attribute"
22 "go.opentelemetry.io/otel/propagation"
23 "go.opentelemetry.io/otel/sdk/instrumentation"
24 "go.opentelemetry.io/otel/sdk/resource"
25 sdktrace "go.opentelemetry.io/otel/sdk/trace"
26 "go.opentelemetry.io/otel/sdk/trace/tracetest"
27 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
28 "go.opentelemetry.io/otel/trace"
29
30 lambdadetector "go.opentelemetry.io/contrib/detectors/aws/lambda"
31 "go.opentelemetry.io/contrib/instrumentation/github.com/aws/aws-lambda-go/otellambda"
32 "go.opentelemetry.io/contrib/propagators/aws/xray"
33 )
34
35 const miB = 1 << 20
36
37 var errorLogger = log.New(log.Writer(), "OTel Lambda Test Error: ", 0)
38
39 type mockIDGenerator struct {
40 sync.Mutex
41 traceCount int
42 spanCount int
43 }
44
45 func (m *mockIDGenerator) NewIDs(context.Context) (trace.TraceID, trace.SpanID) {
46 m.Lock()
47 defer m.Unlock()
48 m.traceCount++
49 m.spanCount++
50 return [16]byte{byte(m.traceCount)}, [8]byte{byte(m.spanCount)}
51 }
52
53 func (m *mockIDGenerator) NewSpanID(context.Context, trace.TraceID) trace.SpanID {
54 m.Lock()
55 defer m.Unlock()
56 m.spanCount++
57 return [8]byte{byte(m.spanCount)}
58 }
59
60 var _ sdktrace.IDGenerator = &mockIDGenerator{}
61
62 type emptyHandler struct{}
63
64 func (emptyHandler) Invoke(context.Context, []byte) ([]byte, error) {
65 return nil, nil
66 }
67
68 var _ lambda.Handler = emptyHandler{}
69
70 func initMockTracerProvider() (*sdktrace.TracerProvider, *tracetest.InMemoryExporter) {
71 ctx := context.Background()
72
73 exp := tracetest.NewInMemoryExporter()
74
75 detector := lambdadetector.NewResourceDetector()
76 res, err := detector.Detect(ctx)
77 if err != nil {
78 errorLogger.Printf("failed to detect lambda resources: %v\n", err)
79 return nil, nil
80 }
81
82 tp := sdktrace.NewTracerProvider(
83 sdktrace.WithSyncer(exp),
84 sdktrace.WithIDGenerator(&mockIDGenerator{}),
85 sdktrace.WithResource(res),
86 )
87
88 return tp, exp
89 }
90
91 func setEnvVars(t *testing.T) {
92 t.Setenv("AWS_LAMBDA_FUNCTION_NAME", "testFunction")
93 t.Setenv("AWS_REGION", "us-texas-1")
94 t.Setenv("AWS_LAMBDA_FUNCTION_VERSION", "$LATEST")
95 t.Setenv("AWS_LAMBDA_LOG_STREAM_NAME", "2023/01/01/[$LATEST]5d1edb9e525d486696cf01a3503487bc")
96 t.Setenv("AWS_LAMBDA_FUNCTION_MEMORY_SIZE", "128")
97 t.Setenv("_X_AMZN_TRACE_ID", "Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1")
98 }
99
100 // Vars for Tracing and TracingWithFlusher Tests.
101 var (
102 mockLambdaContext = lambdacontext.LambdaContext{
103 AwsRequestID: "123",
104 InvokedFunctionArn: "arn:partition:service:region:account-id:resource-type:resource-id",
105 Identity: lambdacontext.CognitoIdentity{
106 CognitoIdentityID: "someId",
107 CognitoIdentityPoolID: "somePoolId",
108 },
109 ClientContext: lambdacontext.ClientContext{},
110 }
111 mockContext = xray.Propagator{}.Extract(lambdacontext.NewContext(context.TODO(), &mockLambdaContext),
112 propagation.HeaderCarrier{
113 "X-Amzn-Trace-Id": []string{"Root=1-5759e988-bd862e3fe1be46a994272793;Parent=53995c3f42cd8ad8;Sampled=1"},
114 })
115 expectedTraceID, _ = trace.TraceIDFromHex("5759e988bd862e3fe1be46a994272793")
116 expectedSpanStub = tracetest.SpanStub{
117 Name: "testFunction",
118 SpanContext: trace.NewSpanContext(trace.SpanContextConfig{
119 TraceID: expectedTraceID,
120 SpanID: trace.SpanID{1},
121 TraceFlags: 1,
122 TraceState: trace.TraceState{},
123 Remote: false,
124 }),
125 Parent: trace.SpanContextFromContext(mockContext),
126 SpanKind: trace.SpanKindServer,
127 StartTime: time.Time{},
128 EndTime: time.Time{},
129 Attributes: []attribute.KeyValue{
130 attribute.String("faas.invocation_id", "123"),
131 attribute.String("aws.lambda.invoked_arn", "arn:partition:service:region:account-id:resource-type:resource-id"),
132 attribute.String("cloud.account.id", "account-id"),
133 },
134 Events: nil,
135 Links: nil,
136 Status: sdktrace.Status{},
137 DroppedAttributes: 0,
138 DroppedEvents: 0,
139 DroppedLinks: 0,
140 ChildSpanCount: 0,
141 Resource: resource.NewWithAttributes(semconv.SchemaURL,
142 attribute.String("cloud.provider", "aws"),
143 attribute.String("cloud.region", "us-texas-1"),
144 attribute.String("faas.name", "testFunction"),
145 attribute.String("faas.version", "$LATEST"),
146 attribute.String("faas.instance", "2023/01/01/[$LATEST]5d1edb9e525d486696cf01a3503487bc"),
147 attribute.Int("faas.max_memory", 128*miB)),
148 InstrumentationScope: instrumentation.Scope{
149 Name: "go.opentelemetry.io/contrib/instrumentation/github.com/aws/aws-lambda-go/otellambda",
150 Version: otellambda.Version,
151 },
152 }
153 )
154
155 func assertStubEqualsIgnoreTime(t *testing.T, expected, actual tracetest.SpanStub) {
156 assert.Equal(t, expected.Name, actual.Name)
157 assert.Equal(t, expected.SpanContext, actual.SpanContext)
158 assert.Equal(t, expected.Parent, actual.Parent)
159 assert.Equal(t, expected.SpanKind, actual.SpanKind)
160 assert.Equal(t, expected.Attributes, actual.Attributes)
161 assert.Equal(t, expected.Events, actual.Events)
162 assert.Equal(t, expected.Links, actual.Links)
163 assert.Equal(t, expected.Status, actual.Status)
164 assert.Equal(t, expected.DroppedAttributes, actual.DroppedAttributes)
165 assert.Equal(t, expected.DroppedEvents, actual.DroppedEvents)
166 assert.Equal(t, expected.DroppedLinks, actual.DroppedLinks)
167 assert.Equal(t, expected.ChildSpanCount, actual.ChildSpanCount)
168 assert.Equal(t, expected.Resource, actual.Resource)
169 assert.Equal(t, expected.InstrumentationScope, actual.InstrumentationScope)
170 }
171
172 func TestInstrumentHandlerTracing(t *testing.T) {
173 setEnvVars(t)
174 tp, memExporter := initMockTracerProvider()
175
176 customerHandler := func() (string, error) {
177 return "hello world", nil
178 }
179
180 // No flusher needed as SimpleSpanProcessor is synchronous
181 wrapped := otellambda.InstrumentHandler(customerHandler, otellambda.WithTracerProvider(tp))
182 wrappedCallable := reflect.ValueOf(wrapped)
183 resp := wrappedCallable.Call([]reflect.Value{reflect.ValueOf(mockContext)})
184 assert.Len(t, resp, 2)
185 assert.Equal(t, "hello world", resp[0].Interface())
186 assert.Nil(t, resp[1].Interface())
187
188 assert.Len(t, memExporter.GetSpans(), 1)
189 stub := memExporter.GetSpans()[0]
190 assertStubEqualsIgnoreTime(t, expectedSpanStub, stub)
191 }
192
193 func TestWrapHandlerTracing(t *testing.T) {
194 setEnvVars(t)
195 tp, memExporter := initMockTracerProvider()
196
197 // No flusher needed as SimpleSpanProcessor is synchronous
198 wrapped := otellambda.WrapHandler(emptyHandler{}, otellambda.WithTracerProvider(tp))
199 _, err := wrapped.Invoke(mockContext, []byte{})
200 assert.NoError(t, err)
201
202 assert.Len(t, memExporter.GetSpans(), 1)
203 stub := memExporter.GetSpans()[0]
204 assertStubEqualsIgnoreTime(t, expectedSpanStub, stub)
205 }
206
207 type mockFlusher struct {
208 flushCount int
209 }
210
211 func (mf *mockFlusher) ForceFlush(context.Context) error {
212 mf.flushCount++
213 return nil
214 }
215
216 var _ otellambda.Flusher = &mockFlusher{}
217
218 func TestInstrumentHandlerTracingWithFlusher(t *testing.T) {
219 setEnvVars(t)
220 tp, memExporter := initMockTracerProvider()
221
222 customerHandler := func() (string, error) {
223 return "hello world", nil
224 }
225
226 flusher := mockFlusher{}
227 wrapped := otellambda.InstrumentHandler(customerHandler, otellambda.WithTracerProvider(tp), otellambda.WithFlusher(&flusher))
228 wrappedCallable := reflect.ValueOf(wrapped)
229 resp := wrappedCallable.Call([]reflect.Value{reflect.ValueOf(mockContext)})
230 assert.Len(t, resp, 2)
231 assert.Equal(t, "hello world", resp[0].Interface())
232 assert.Nil(t, resp[1].Interface())
233
234 assert.Len(t, memExporter.GetSpans(), 1)
235 stub := memExporter.GetSpans()[0]
236 assertStubEqualsIgnoreTime(t, expectedSpanStub, stub)
237
238 assert.Equal(t, 1, flusher.flushCount)
239 }
240
241 func TestWrapHandlerTracingWithFlusher(t *testing.T) {
242 setEnvVars(t)
243 tp, memExporter := initMockTracerProvider()
244
245 flusher := mockFlusher{}
246 wrapped := otellambda.WrapHandler(emptyHandler{}, otellambda.WithTracerProvider(tp), otellambda.WithFlusher(&flusher))
247 _, err := wrapped.Invoke(mockContext, []byte{})
248 assert.NoError(t, err)
249
250 assert.Len(t, memExporter.GetSpans(), 1)
251 stub := memExporter.GetSpans()[0]
252 assertStubEqualsIgnoreTime(t, expectedSpanStub, stub)
253
254 assert.Equal(t, 1, flusher.flushCount)
255 }
256
257 const mockPropagatorKey = "Mockkey"
258
259 type mockPropagator struct{}
260
261 func (mockPropagator) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {
262 // extract tracing information
263 if header := carrier.Get(mockPropagatorKey); header != "" {
264 scc := trace.SpanContextConfig{}
265 splitHeaderVal := strings.Split(header, ":")
266 var err error
267 scc.TraceID, err = trace.TraceIDFromHex(splitHeaderVal[0])
268 if err != nil {
269 errorLogger.Println("Failed to create trace id from hex: ", err)
270 }
271 scc.SpanID, err = trace.SpanIDFromHex(splitHeaderVal[1])
272 if err != nil {
273 errorLogger.Println("Failed to create span id from hex: ", err)
274 }
275 isTraced, err := strconv.Atoi(splitHeaderVal[1])
276 if err != nil {
277 errorLogger.Println("Failed to convert trace flag to int: ", err)
278 }
279 scc.TraceFlags = scc.TraceFlags.WithSampled(isTraced != 0)
280 sc := trace.NewSpanContext(scc)
281 return trace.ContextWithRemoteSpanContext(ctx, sc)
282 }
283 return ctx
284 }
285
286 func (mockPropagator) Inject(context.Context, propagation.TextMapCarrier) {
287 // not needed other than to satisfy interface
288 }
289
290 func (mockPropagator) Fields() []string {
291 // not needed other than to satisfy interface
292 return []string{}
293 }
294
295 type mockRequest struct {
296 Headers map[string]string
297 }
298
299 // Vars for mockPropagator Tests.
300 var (
301 mockPropagatorTestsTraceIDHex = "12345678901234567890123456789012"
302 mockPropagatorTestsSpanIDHex = "1234567890123456"
303 mockPropagatorTestsSampled = "1"
304 mockPropagatorTestsHeader = mockPropagatorTestsTraceIDHex + ":" + mockPropagatorTestsSpanIDHex + ":" + mockPropagatorTestsSampled
305 mockPropagatorTestsEvent = mockRequest{Headers: map[string]string{mockPropagatorKey: mockPropagatorTestsHeader}}
306
307 mockPropagatorTestsContext = mockPropagator{}.Extract(lambdacontext.NewContext(context.TODO(), &mockLambdaContext),
308 propagation.HeaderCarrier{mockPropagatorKey: []string{mockPropagatorTestsHeader}})
309
310 mockPropagatorTestsExpectedTraceID, _ = trace.TraceIDFromHex(mockPropagatorTestsTraceIDHex)
311 mockPropagatorTestsExpectedSpanStub = tracetest.SpanStub{
312 Name: "testFunction",
313 SpanContext: trace.NewSpanContext(trace.SpanContextConfig{
314 TraceID: mockPropagatorTestsExpectedTraceID,
315 SpanID: trace.SpanID{1},
316 TraceFlags: 1,
317 TraceState: trace.TraceState{},
318 Remote: false,
319 }),
320 Parent: trace.SpanContextFromContext(mockPropagatorTestsContext),
321 SpanKind: trace.SpanKindServer,
322 StartTime: time.Time{},
323 EndTime: time.Time{},
324 Attributes: []attribute.KeyValue{
325 attribute.String("faas.invocation_id", "123"),
326 attribute.String("aws.lambda.invoked_arn", "arn:partition:service:region:account-id:resource-type:resource-id"),
327 attribute.String("cloud.account.id", "account-id"),
328 },
329 Events: nil,
330 Links: nil,
331 Status: sdktrace.Status{},
332 DroppedAttributes: 0,
333 DroppedEvents: 0,
334 DroppedLinks: 0,
335 ChildSpanCount: 0,
336 Resource: resource.NewWithAttributes(semconv.SchemaURL,
337 attribute.String("cloud.provider", "aws"),
338 attribute.String("cloud.region", "us-texas-1"),
339 attribute.String("faas.name", "testFunction"),
340 attribute.String("faas.version", "$LATEST"),
341 attribute.String("faas.instance", "2023/01/01/[$LATEST]5d1edb9e525d486696cf01a3503487bc"),
342 attribute.Int("faas.max_memory", 128*miB)),
343 InstrumentationScope: instrumentation.Scope{
344 Name: "go.opentelemetry.io/contrib/instrumentation/github.com/aws/aws-lambda-go/otellambda",
345 Version: otellambda.Version,
346 },
347 }
348 )
349
350 func mockRequestCarrier(eventJSON []byte) propagation.TextMapCarrier {
351 var event mockRequest
352 err := json.Unmarshal(eventJSON, &event)
353 if err != nil {
354 fmt.Println("event type: ", reflect.TypeFor[mockRequest]())
355 panic("mockRequestCarrier only supports events of type mockRequest")
356 }
357 return propagation.HeaderCarrier{mockPropagatorKey: []string{event.Headers[mockPropagatorKey]}}
358 }
359
360 func mockTraceAttributeFn(eventJSON []byte) []attribute.KeyValue {
361 var event mockRequest
362 err := json.Unmarshal(eventJSON, &event)
363 if err != nil {
364 fmt.Println("event type: ", reflect.TypeFor[mockRequest]())
365 panic("mockRequestCarrier only supports events of type mockRequest")
366 }
367 return []attribute.KeyValue{attribute.String("mock.request.type", reflect.TypeFor[mockRequest]().String())}
368 }
369
370 func TestInstrumentHandlerTracingWithMockPropagator(t *testing.T) {
371 setEnvVars(t)
372 tp, memExporter := initMockTracerProvider()
373
374 customerHandler := func(mockRequest) (string, error) {
375 return "hello world", nil
376 }
377
378 // No flusher needed as SimpleSpanProcessor is synchronous
379 wrapped := otellambda.InstrumentHandler(customerHandler,
380 otellambda.WithTracerProvider(tp),
381 otellambda.WithPropagator(mockPropagator{}),
382 otellambda.WithEventToCarrier(mockRequestCarrier))
383
384 wrappedCallable := reflect.ValueOf(wrapped)
385 resp := wrappedCallable.Call([]reflect.Value{reflect.ValueOf(mockPropagatorTestsContext), reflect.ValueOf(mockPropagatorTestsEvent)})
386 assert.Len(t, resp, 2)
387 assert.Equal(t, "hello world", resp[0].Interface())
388 assert.Nil(t, resp[1].Interface())
389
390 assert.Len(t, memExporter.GetSpans(), 1)
391 stub := memExporter.GetSpans()[0]
392 assertStubEqualsIgnoreTime(t, mockPropagatorTestsExpectedSpanStub, stub)
393 }
394
395 func TestWrapHandlerTracingWithMockPropagator(t *testing.T) {
396 setEnvVars(t)
397 tp, memExporter := initMockTracerProvider()
398
399 // No flusher needed as SimpleSpanProcessor is synchronous
400 wrapped := otellambda.WrapHandler(emptyHandler{},
401 otellambda.WithTracerProvider(tp),
402 otellambda.WithPropagator(mockPropagator{}),
403 otellambda.WithEventToCarrier(mockRequestCarrier))
404
405 payload, _ := json.Marshal(mockPropagatorTestsEvent)
406 _, err := wrapped.Invoke(mockPropagatorTestsContext, payload)
407 assert.NoError(t, err)
408
409 assert.Len(t, memExporter.GetSpans(), 1)
410 stub := memExporter.GetSpans()[0]
411 assertStubEqualsIgnoreTime(t, mockPropagatorTestsExpectedSpanStub, stub)
412 }
413
414 func TestWrapHandlerTracingWithTraceAttributeFn(t *testing.T) {
415 setEnvVars(t)
416 tp, memExporter := initMockTracerProvider()
417
418 // No flusher needed as SimpleSpanProcessor is synchronous
419 wrapped := otellambda.WrapHandler(emptyHandler{},
420 otellambda.WithTracerProvider(tp),
421 otellambda.WithTraceAttributeFn(mockTraceAttributeFn),
422 )
423
424 payload, _ := json.Marshal(mockPropagatorTestsEvent)
425 _, err := wrapped.Invoke(mockPropagatorTestsContext, payload)
426 assert.NoError(t, err)
427
428 assert.Len(t, memExporter.GetSpans(), 1)
429 stub := memExporter.GetSpans()[0]
430 expectedAttr := attribute.KeyValue{Key: "mock.request.type", Value: attribute.StringValue(reflect.TypeFor[mockRequest]().String())}
431 assert.Contains(t, stub.Attributes, expectedAttr, "custom attribute 'mock.request.type' with value 'otellambda_test.mockRequest' not found")
432 }