Skip to content

Commit 4213a82

Browse files
sentry-junior[bot]pabloDeputterdingsdax
authored
feat(aws-lambda): Detect Lambda triggers (#8222)
### Description Sets `faas.trigger` on the Lambda span based on the shape of the delivered event: - `http`: API Gateway REST/HTTP, function URLs, ALB, CloudFront, AppSync - `pubsub`: SQS, SNS, Kinesis, Kafka, MQ, SES, EventBridge - `datasource`: S3, DynamoDB Streams, DocumentDB - `timer`: EventBridge schedules - `other`: anything else The trigger is read from the event envelope, never from its payload. `test_trigger` has one case per code path. Other event sources use the same lookup table, so they have no extra cases. This PR doesn't touch `messaging.batch.message_count`. That change is in #8229. This is Pablo's code from `pablo/aws-lambda-trigger`, without his batch counting for the invocation span. It's the second of three stacked PRs (#8221 → this → #8223). #### Issues * resolves: PY-3018 (`faas.trigger` part; the per-source attributes in the issue aren't in this PR) * Part of #8081 <!-- junior-request-attribution:start --> via @dingsdax. <!-- junior-request-attribution:end --> <!-- junior-session-footer:start --> <!-- junior-conversation-id:slack%3AC0C9X9V5NMT%3A1793904671.980379 --> -- [View Session](https://junior-prod.sentry.dev/conversations/slack%3AC0C9X9V5NMT%3A1793904671.980379) [[Sentry]](https://sentry.sentry.io/explore/conversations/slack%3AC0C9X9V5NMT%3A1793904671.980379/?project=4510944073809921) <!-- junior-session-footer:end --> --------- Co-authored-by: Pablo Deputter <pablo.deputter@sentry.io> Co-authored-by: Pablo Deputter <71842639+pabloDeputter@users.noreply.github.com> Co-authored-by: sentry-junior[bot] <264270552+sentry-junior[bot]@users.noreply.github.com> Co-authored-by: Johannes Daxböck <114897+dingsdax@users.noreply.github.com>
1 parent 08ebd25 commit 4213a82

4 files changed

Lines changed: 192 additions & 0 deletions

File tree

‎sentry_sdk/consts.py‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -718,6 +718,12 @@ class SPANDATA:
718718
Example: "my_function"
719719
"""
720720

721+
FAAS_TRIGGER = "faas.trigger"
722+
"""
723+
The type of the trigger on which the function is executed.
724+
Example: "pubsub"
725+
"""
726+
721727
FAAS_VERSION = "faas.version"
722728
"""
723729
The version of the function that was invoked.

‎sentry_sdk/integrations/aws_lambda/_handler.py‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
_get_user_from_event,
1414
_make_request_event_processor,
1515
)
16+
from sentry_sdk.integrations.aws_lambda._trigger import _get_trigger
1617
from sentry_sdk.integrations.aws_lambda.consts import (
1718
CLOUD_PLATFORM,
1819
CLOUD_PROVIDER,
@@ -231,6 +232,9 @@ def sentry_handler(
231232
**additional_attributes,
232233
}
233234

235+
with capture_internal_exceptions():
236+
attributes[SPANDATA.FAAS_TRIGGER] = _get_trigger(aws_event)
237+
234238
with capture_internal_exceptions():
235239
invoked_function_arn = aws_context.invoked_function_arn
236240
function_version = aws_context.function_version
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
from typing import TYPE_CHECKING
2+
3+
if TYPE_CHECKING:
4+
from typing import Any
5+
6+
# `faas.trigger` of each `eventSource` of `Records` or of a top-level `eventSource`.
7+
# https://docs.aws.amazon.com/lambda/latest/dg/lambda-services.html
8+
_TRIGGERS = {
9+
"aws:sqs": "pubsub",
10+
"aws:sns": "pubsub",
11+
"aws:kinesis": "pubsub",
12+
"aws:ses": "pubsub",
13+
"aws:kafka": "pubsub",
14+
"SelfManagedKafka": "pubsub",
15+
# ActiveMQ: the Lambda docs show `aws:mq`, real deliveries use `aws:amq`.
16+
"aws:mq": "pubsub",
17+
"aws:amq": "pubsub",
18+
"aws:rmq": "pubsub",
19+
"aws:s3": "datasource",
20+
"aws:dynamodb": "datasource",
21+
"aws:docdb": "datasource",
22+
}
23+
24+
# https://docs.aws.amazon.com/eventbridge/latest/ref/overiew-event-structure.html
25+
_EVENTBRIDGE_KEYS = frozenset(
26+
(
27+
"version",
28+
"id",
29+
"detail-type",
30+
"source",
31+
"account",
32+
"time",
33+
"region",
34+
"resources",
35+
"detail",
36+
)
37+
)
38+
39+
40+
def _is_appsync_event(aws_event: "Any") -> bool:
41+
# https://docs.aws.amazon.com/appsync/latest/devguide/resolver-context-reference-js.html
42+
return (
43+
isinstance(aws_event, dict)
44+
and "arguments" in aws_event
45+
and "fieldName" in aws_event.get("info", {})
46+
)
47+
48+
49+
def _get_trigger(aws_event: "Any") -> str:
50+
"""`faas.trigger` from the envelope of the delivered event, never from its payload."""
51+
if isinstance(aws_event, list):
52+
# an AppSync batch resolver delivers a list of resolver events.
53+
if aws_event and all(_is_appsync_event(event) for event in aws_event):
54+
return "http"
55+
return "other"
56+
57+
if not isinstance(aws_event, dict):
58+
return "other"
59+
60+
# API Gateway REST APIs and ALB send `httpMethod`, HTTP APIs and function URLs
61+
# `requestContext.http`.
62+
request_context = aws_event.get("requestContext")
63+
if request_context is not None and (
64+
"httpMethod" in aws_event or "http" in request_context
65+
):
66+
return "http"
67+
68+
if _is_appsync_event(aws_event):
69+
return "http"
70+
71+
records = aws_event.get("Records")
72+
if records:
73+
# CloudFront and Lambda@Edge records have no `eventSource`.
74+
if "cf" in records[0]:
75+
return "http"
76+
# SNS spells it `EventSource`.
77+
source = records[0].get("eventSource") or records[0].get("EventSource")
78+
return _TRIGGERS.get(source, "other")
79+
80+
if _EVENTBRIDGE_KEYS <= aws_event.keys():
81+
if (
82+
aws_event["source"] == "aws.events"
83+
and aws_event["detail-type"] == "Scheduled Event"
84+
):
85+
return "timer"
86+
return "pubsub"
87+
88+
return _TRIGGERS.get(aws_event.get("eventSource", ""), "other")

‎tests/integrations/aws_lambda/test_aws_lambda.py‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,32 @@
2525
SAM_TEMPLATE_FILE = "sam.template.yaml"
2626
SAM_SHUTDOWN_TIMEOUT = 10
2727

28+
SQS_RECORD = {
29+
"messageId": "059f36b4-87a3-44ab-83d2-661975830a7d",
30+
"body": "{}",
31+
"eventSource": "aws:sqs",
32+
"eventSourceARN": "arn:aws:sqs:us-east-1:012345678912:orders",
33+
}
34+
SNS_RECORD = {
35+
"EventSource": "aws:sns",
36+
"Sns": {"TopicArn": "arn:aws:sns:us-east-1:012345678912:alerts"},
37+
}
38+
APPSYNC_EVENT = {
39+
"arguments": {"id": "1"},
40+
"info": {"fieldName": "getOrder", "parentTypeName": "Query"},
41+
}
42+
EVENTBRIDGE_EVENT = {
43+
"version": "0",
44+
"id": "53dc4d37-cffa-4f76-80c9-8b7d4a4d2eaa",
45+
"detail-type": "Object Created",
46+
"source": "aws.s3",
47+
"account": "012345678912",
48+
"time": "2026-10-26T12:00:00Z",
49+
"region": "us-east-1",
50+
"resources": [],
51+
"detail": {},
52+
}
53+
2854

2955
@pytest.fixture(scope="session", autouse=True)
3056
def test_environment():
@@ -767,6 +793,7 @@ def test_no_error(lambda_client, test_environment):
767793
assert _get_span_attr(attrs, SPANDATA.AWS_LOG_STREAM_NAMES) == [
768794
LATEST_FUNCTION_VERSION
769795
]
796+
assert _get_span_attr(attrs, SPANDATA.FAAS_TRIGGER) == "other"
770797

771798

772799
def test_error(lambda_client, test_environment):
@@ -820,6 +847,73 @@ def test_error(lambda_client, test_environment):
820847
assert _get_span_attr(attrs, SPANDATA.AWS_LOG_STREAM_NAMES) == [
821848
LATEST_FUNCTION_VERSION
822849
]
850+
assert _get_span_attr(attrs, SPANDATA.FAAS_TRIGGER) == "other"
851+
852+
853+
@pytest.mark.parametrize(
854+
"aws_event,trigger",
855+
[
856+
pytest.param(
857+
{"httpMethod": "GET", "path": "/", "requestContext": {"stage": "prod"}},
858+
"http",
859+
id="api-gateway-rest",
860+
),
861+
pytest.param(
862+
{
863+
"version": "2.0",
864+
"routeKey": "GET /",
865+
"requestContext": {"http": {"method": "GET"}},
866+
},
867+
"http",
868+
id="api-gateway-http",
869+
),
870+
pytest.param(
871+
{"Records": [{"cf": {"request": {"uri": "/"}}}]},
872+
"http",
873+
id="cloudfront",
874+
),
875+
pytest.param(APPSYNC_EVENT, "http", id="appsync"),
876+
pytest.param([APPSYNC_EVENT, APPSYNC_EVENT], "http", id="appsync-batch"),
877+
pytest.param({"Records": [SQS_RECORD, SQS_RECORD]}, "pubsub", id="sqs"),
878+
pytest.param({"Records": [SNS_RECORD]}, "pubsub", id="sns"),
879+
pytest.param(
880+
{"eventSource": "aws:kafka", "records": {"orders-0": [{}]}},
881+
"pubsub",
882+
id="msk",
883+
),
884+
pytest.param(
885+
EVENTBRIDGE_EVENT,
886+
"pubsub",
887+
id="eventbridge",
888+
),
889+
pytest.param(
890+
{
891+
**EVENTBRIDGE_EVENT,
892+
"source": "aws.events",
893+
"detail-type": "Scheduled Event",
894+
},
895+
"timer",
896+
id="eventbridge-schedule",
897+
),
898+
pytest.param({"Records": [{"eventSource": "aws:s3"}]}, "datasource", id="s3"),
899+
pytest.param(
900+
[{"good dog": "Maisey"}, {"good dog": "Charlie"}],
901+
"other",
902+
id="list",
903+
),
904+
],
905+
)
906+
def test_trigger(lambda_client, test_environment, aws_event, trigger):
907+
lambda_client.invoke(
908+
FunctionName="BasicOkSpanStreaming",
909+
Payload=json.dumps(aws_event),
910+
)
911+
912+
(segment_span,) = [
913+
s for s in test_environment["server"].span_items if s["is_segment"]
914+
]
915+
attrs = segment_span["attributes"]
916+
assert _get_span_attr(attrs, SPANDATA.FAAS_TRIGGER) == trigger
823917

824918

825919
def test_trace_continuation(lambda_client, test_environment):

0 commit comments

Comments
 (0)