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 (
36+ data ["timestamp" ].replace ("Z" , "+00:00" )
37+ ),
38+ )
39+
40+
41+ class CustomDataSerDes (SerDes [CustomData ]):
42+ """Custom serializer for CustomData that handles datetime conversion."""
43+
44+ def serialize (self , value : Optional [CustomData ], _ : SerDesContext ) -> Optional [str ]:
45+ """Serialize CustomData to JSON string."""
46+ if value is None :
47+ return None
48+ return json .dumps (value .to_dict ())
49+
50+ def deserialize (
51+ self , payload : Optional [str ], _ : SerDesContext
52+ ) -> Optional [CustomData ]:
53+ """Deserialize JSON string to CustomData."""
54+ if payload is None :
55+ return None
56+ data = json .loads (payload )
57+ return CustomData .from_dict (data )
58+
59+
60+ @durable_execution
61+ def handler (_event : Any , context : DurableContext ) -> dict [str , Any ]:
62+ """Handler demonstrating createCallback with custom serdes."""
63+ callback_config = CallbackConfig (
64+ timeout = Duration .from_seconds (30 ),
65+ serdes = CustomDataSerDes (),
66+ )
67+
68+ callback = context .create_callback (
69+ name = "custom-serdes-callback" ,
70+ config = callback_config ,
71+ )
72+
73+ result : CustomData = callback .result ()
74+
75+ return {
76+ "receivedData" : result .to_dict (),
77+ "isDateObject" : isinstance (result .timestamp , datetime ),
78+ }
0 commit comments