|
| 1 | +"""Example demonstrating multiple steps with retry logic.""" |
| 2 | + |
| 3 | +from random import random |
| 4 | +from typing import Any |
| 5 | + |
| 6 | +from aws_durable_execution_sdk_python.config import StepConfig |
| 7 | +from aws_durable_execution_sdk_python.context import DurableContext |
| 8 | +from aws_durable_execution_sdk_python.execution import durable_handler |
| 9 | +from aws_durable_execution_sdk_python.retries import ( |
| 10 | + RetryStrategyConfig, |
| 11 | + create_retry_strategy, |
| 12 | +) |
| 13 | + |
| 14 | + |
| 15 | +def simulated_get_item(name: str) -> dict[str, Any] | None: |
| 16 | + """Simulate getting an item that may fail randomly.""" |
| 17 | + # Fail 50% of the time |
| 18 | + if random() < 0.5: # noqa: S311 |
| 19 | + msg = "Random failure" |
| 20 | + raise RuntimeError(msg) |
| 21 | + |
| 22 | + # Simulate finding item after some attempts |
| 23 | + if random() > 0.3: # noqa: S311 |
| 24 | + return {"id": name, "data": "item data"} |
| 25 | + |
| 26 | + return None |
| 27 | + |
| 28 | + |
| 29 | +@durable_handler |
| 30 | +def handler(event: Any, context: DurableContext) -> dict[str, Any]: |
| 31 | + """Handler demonstrating polling with retry logic.""" |
| 32 | + name = event.get("name", "test-item") |
| 33 | + |
| 34 | + # Retry configuration for steps |
| 35 | + retry_config = RetryStrategyConfig( |
| 36 | + max_attempts=5, |
| 37 | + retryable_error_types=[RuntimeError], |
| 38 | + ) |
| 39 | + |
| 40 | + step_config = StepConfig(create_retry_strategy(retry_config)) |
| 41 | + |
| 42 | + item = None |
| 43 | + poll_count = 0 |
| 44 | + max_polls = 5 |
| 45 | + |
| 46 | + try: |
| 47 | + while poll_count < max_polls: |
| 48 | + poll_count += 1 |
| 49 | + |
| 50 | + # Try to get the item with retry |
| 51 | + get_response = context.step( |
| 52 | + lambda _, n=name: simulated_get_item(n), |
| 53 | + name=f"get_item_poll_{poll_count}", |
| 54 | + config=step_config, |
| 55 | + ) |
| 56 | + |
| 57 | + # Did we find the item? |
| 58 | + if get_response: |
| 59 | + item = get_response |
| 60 | + break |
| 61 | + |
| 62 | + # Wait 1 second until next poll |
| 63 | + context.wait(seconds=1) |
| 64 | + |
| 65 | + except RuntimeError as e: |
| 66 | + # Retries exhausted |
| 67 | + return {"error": "DDB Retries Exhausted", "message": str(e)} |
| 68 | + |
| 69 | + if not item: |
| 70 | + return {"error": "Item Not Found"} |
| 71 | + |
| 72 | + # We found the item! |
| 73 | + return {"success": True, "item": item, "pollsRequired": poll_count} |
0 commit comments