|
| 1 | +"""Demonstrates createCallback with custom serialization/deserialization for Date objects.""" |
| 2 | + |
| 3 | +import json |
| 4 | +from datetime import datetime, timezone |
| 5 | +from typing import Any, Optional |
| 6 | + |
| 7 | +from aws_durable_execution_sdk_python.config import CallbackConfig, Duration |
| 8 | +from aws_durable_execution_sdk_python.context import DurableContext |
| 9 | +from aws_durable_execution_sdk_python.execution import durable_execution |
| 10 | +from aws_durable_execution_sdk_python.serdes import SerDes, SerDesContext |
| 11 | + |
| 12 | + |
| 13 | +class CustomData: |
| 14 | + """Data structure with datetime.""" |
| 15 | + |
| 16 | + def __init__(self, id: int, message: str, timestamp: datetime): |
| 17 | + self.id = id |
| 18 | + self.message = message |
| 19 | + self.timestamp = timestamp |
| 20 | + |
| 21 | + def to_dict(self) -> dict[str, Any]: |
| 22 | + """Convert to dictionary.""" |
| 23 | + return { |
| 24 | + "id": self.id, |
| 25 | + "message": self.message, |
| 26 | + "timestamp": self.timestamp.isoformat(), |
| 27 | + } |
| 28 | + |
| 29 | + @staticmethod |
| 30 | + def from_dict(data: dict[str, Any]) -> "CustomData": |
| 31 | + """Create from dictionary.""" |
| 32 | + return CustomData( |
| 33 | + id=data["id"], |
| 34 | + message=data["message"], |
| 35 | + timestamp=datetime.fromisoformat(data["timestamp"].replace("Z", "+00:00")), |
| 36 | + ) |
| 37 | + |
| 38 | + |
| 39 | +class CustomDataSerDes(SerDes[CustomData]): |
| 40 | + """Custom serializer for CustomData that handles datetime conversion.""" |
| 41 | + |
| 42 | + def serialize(self, value: Optional[CustomData], _: SerDesContext) -> Optional[str]: |
| 43 | + """Serialize CustomData to JSON string.""" |
| 44 | + if value is None: |
| 45 | + return None |
| 46 | + return json.dumps(value.to_dict()) |
| 47 | + |
| 48 | + def deserialize( |
| 49 | + self, payload: Optional[str], _: SerDesContext |
| 50 | + ) -> Optional[CustomData]: |
| 51 | + """Deserialize JSON string to CustomData.""" |
| 52 | + if payload is None: |
| 53 | + return None |
| 54 | + data = json.loads(payload) |
| 55 | + return CustomData.from_dict(data) |
| 56 | + |
| 57 | + |
| 58 | +@durable_execution |
| 59 | +def handler(_event: Any, context: DurableContext) -> dict[str, Any]: |
| 60 | + """Handler demonstrating createCallback with custom serdes.""" |
| 61 | + callback_config = CallbackConfig( |
| 62 | + timeout=Duration.from_seconds(30), |
| 63 | + serdes=CustomDataSerDes(), |
| 64 | + ) |
| 65 | + |
| 66 | + callback = context.create_callback( |
| 67 | + name="custom-serdes-callback", |
| 68 | + config=callback_config, |
| 69 | + ) |
| 70 | + |
| 71 | + result: CustomData = callback.result() |
| 72 | + |
| 73 | + return { |
| 74 | + "receivedData": result.to_dict(), |
| 75 | + "isDateObject": isinstance(result.timestamp, datetime), |
| 76 | + } |
0 commit comments