Skip to content

Commit 4257761

Browse files
committed
feat(metrics): add DurableContext support in base provider
- Add _unwrap_durable_context() helper in base provider - Update _add_cold_start_metric() to unwrap DurableContext before passing to providers - Add documentation noting DurableContext support in log_metrics decorator Relates to #7763
1 parent 02abede commit 4257761

File tree

1 file changed

+29
-2
lines changed
  • aws_lambda_powertools/metrics/provider

1 file changed

+29
-2
lines changed

aws_lambda_powertools/metrics/provider/base.py

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,26 @@
1414
logger = logging.getLogger(__name__)
1515

1616

17+
def _unwrap_durable_context(context: Any) -> LambdaContext:
18+
"""Unwrap Lambda Context from DurableContext if applicable.
19+
20+
Parameters
21+
----------
22+
context : object
23+
Lambda context object or DurableContext
24+
25+
Returns
26+
-------
27+
LambdaContext
28+
The unwrapped Lambda context
29+
"""
30+
# Check if this is a DurableContext by duck typing
31+
if hasattr(context, "lambda_context") and hasattr(context, "state"):
32+
return context.lambda_context
33+
34+
return context
35+
36+
1737
class BaseProvider(ABC):
1838
"""
1939
Interface to create a metrics provider.
@@ -177,6 +197,11 @@ def handler(event, context):
177197
default_dimensions: dict[str, str], optional
178198
metric dimensions as key=value that will always be present
179199
200+
Notes
201+
-----
202+
Supports both standard Lambda Context and DurableContext from AWS Durable Execution SDK.
203+
When DurableContext is passed, it automatically unwraps the underlying Lambda Context.
204+
180205
Raises
181206
------
182207
e
@@ -221,13 +246,15 @@ def _add_cold_start_metric(self, context: Any) -> None:
221246
Parameters
222247
----------
223248
context : Any
224-
Lambda context
249+
Lambda context or DurableContext
225250
"""
226251
if not cold_start.is_cold_start:
227252
return
228253

229254
logger.debug("Adding cold start metric and function_name dimension")
230-
self.add_cold_start_metric(context=context)
255+
# Unwrap DurableContext if applicable before passing to add_cold_start_metric
256+
lambda_context = _unwrap_durable_context(context)
257+
self.add_cold_start_metric(context=lambda_context)
231258

232259
cold_start.is_cold_start = False
233260

0 commit comments

Comments
 (0)