Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
from __future__ import annotations

from dataclasses import asdict, is_dataclass
from typing import Any
import datetime as dt
from dataclasses import fields, is_dataclass
from decimal import Decimal, InvalidOperation
from enum import Enum
from types import UnionType
from typing import Any, Union, get_args, get_origin, get_type_hints
from uuid import UUID

from aws_lambda_powertools.utilities.idempotency.exceptions import (
IdempotencyModelTypeError,
Expand All @@ -16,6 +21,97 @@
DataClass = Any


def _to_json_compatible(value: Any) -> Any:
"""Convert a dataclass result into values the idempotency JSON encoder can store."""
if is_dataclass(value) and not isinstance(value, type):
return {f.name: _to_json_compatible(getattr(value, f.name)) for f in fields(value)}
if isinstance(value, Enum):
return _to_json_compatible(value.value)
if isinstance(value, dict):
return {k: _to_json_compatible(v) for k, v in value.items()}
if isinstance(value, (list, tuple, set, frozenset)):
return [_to_json_compatible(v) for v in value]
if isinstance(value, (dt.datetime, dt.date, dt.time)):
return value.isoformat()
return str(value) if isinstance(value, UUID) else value


def _convert_union(value: Any, type_hint: Any) -> Any:
for arg in get_args(type_hint):
if arg is type(None):
continue
converted = _from_json_compatible(value, arg)
if converted is not value:
return converted
return value


def _convert_sequence(value: list, origin: type, type_hint: Any) -> Any:
args = get_args(type_hint)
if origin is tuple and args and not (len(args) == 2 and args[1] is Ellipsis):
items = [_from_json_compatible(v, a) for v, a in zip(value, args, strict=False)]
items.extend(value[len(items) :])
else:
item_type = args[0] if args else Any
items = [_from_json_compatible(v, item_type) for v in value]
return items if origin is list else origin(items)


def _convert_scalar(value: Any, type_hint: type) -> Any:
if issubclass(type_hint, Enum):
return type_hint(value)
if not isinstance(value, str):
return value
if issubclass(type_hint, (dt.datetime, dt.date, dt.time)):
return type_hint.fromisoformat(value)
if issubclass(type_hint, (UUID, Decimal)):
return type_hint(value)
return value


def _from_json_compatible(value: Any, type_hint: Any) -> Any:
"""Rebuild a stored value into the type declared on the dataclass field.

Values that don't match the declared type are returned untouched, so records
stored before this conversion existed keep being replayed as they were.
"""
origin = get_origin(type_hint)
result = value

if value is None:
result = None
elif origin is Union or origin is UnionType:
result = _convert_union(value, type_hint)
elif origin in (list, set, frozenset, tuple) and isinstance(value, list):
result = _convert_sequence(value, origin, type_hint)
elif origin is dict and isinstance(value, dict):
args = get_args(type_hint)
value_type = args[1] if len(args) == 2 else Any
result = {k: _from_json_compatible(v, value_type) for k, v in value.items()}
elif isinstance(type_hint, type) and is_dataclass(type_hint) and isinstance(value, dict):
result = _build_dataclass(type_hint, value)
elif isinstance(type_hint, type):
try:
result = _convert_scalar(value, type_hint)
except (ValueError, TypeError, InvalidOperation):
result = value

return result


def _build_dataclass(model: type[DataClass], data: dict) -> DataClass:
try:
hints = get_type_hints(model)
except Exception: # unresolvable forward references: fall back to the raw annotations
hints = {}

converted = {}
for key, value in data.items():
type_hint = hints.get(key)
converted[key] = _from_json_compatible(value, type_hint) if type_hint is not None else value
return model(**converted)


class DataclassSerializer(BaseIdempotencyModelSerializer):
"""
A serializer class for transforming data between dataclass objects and dictionaries.
Expand All @@ -31,10 +127,11 @@ def __init__(self, model: type[DataClass]):
self.__model: type[DataClass] = model

def to_dict(self, data: DataClass) -> dict:
return asdict(data)
# The result is stored as JSON, so dump JSON-compatible values; from_dict rebuilds them from the field types.
return _to_json_compatible(data)

def from_dict(self, data: dict) -> DataClass:
return self.__model(**data)
return _build_dataclass(self.__model, data)

@classmethod
def instantiate(cls, model_type: Any) -> BaseIdempotencySerializer:
Expand Down
2 changes: 2 additions & 0 deletions docs/utilities/idempotency.md
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,8 @@ The output serializer supports any JSON serializable data, **Python Dataclasses*

Use `DataclassSerializer` to automatically serialize what's retrieved from the persistent storage based on the return type annotated.

Fields holding `datetime`, `date`, `time`, `UUID`, `Enum` and `Decimal` values, and nested dataclasses (also inside lists and dictionaries), are saved as JSON and rebuilt from the field type annotations when the result is replayed.

=== "Inferring via the return type"

```python hl_lines="1 11 32 40 43 53"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
"""DataclassSerializer must save results with non-JSON-native fields and rebuild them on replay."""

from __future__ import annotations

import dataclasses
import uuid
from datetime import date, datetime, timezone
from decimal import Decimal
from enum import Enum

from aws_lambda_powertools.utilities.idempotency import IdempotencyConfig, idempotent_function
from aws_lambda_powertools.utilities.idempotency.exceptions import IdempotencyItemAlreadyExistsError
from aws_lambda_powertools.utilities.idempotency.persistence.base import BasePersistenceLayer, DataRecord
from aws_lambda_powertools.utilities.idempotency.serialization.dataclass import DataclassSerializer


class InMemoryPersistenceLayer(BasePersistenceLayer):
"""Stores the serialized record the way a real table would, so replay reads back what was saved."""

def __init__(self):
super().__init__()
self.records: dict[str, DataRecord] = {}

def _put_record(self, data_record: DataRecord) -> None:
if data_record.idempotency_key in self.records:
raise IdempotencyItemAlreadyExistsError
self.records[data_record.idempotency_key] = data_record

def _update_record(self, data_record: DataRecord) -> None:
self.records[data_record.idempotency_key] = data_record

def _get_record(self, idempotency_key) -> DataRecord:
return self.records[idempotency_key]

def _delete_record(self, data_record: DataRecord) -> None:
self.records.pop(data_record.idempotency_key, None)


class FakeLambdaContext:
def get_remaining_time_in_millis(self) -> int:
return 1000


class Color(Enum):
RED = "red"


@dataclasses.dataclass
class Item:
sku: str
shipped_on: date


@dataclasses.dataclass
class Order:
id: uuid.UUID
created: datetime
item: Item
items: list[Item]
color: Color
total: Decimal
coupon: Item | None = None
by_name: dict[str, Item] = dataclasses.field(default_factory=dict)


@dataclasses.dataclass
class Receipt:
number: str
note: str | None = None


def _build_order() -> Order:
return Order(
id=uuid.UUID("12345678-1234-5678-1234-567812345678"),
created=datetime(2026, 1, 1, 10, 30, tzinfo=timezone.utc),
item=Item(sku="a", shipped_on=date(2026, 1, 2)),
items=[Item(sku="b", shipped_on=date(2026, 1, 3))],
color=Color.RED,
total=Decimal("19.90"),
coupon=Item(sku="c", shipped_on=date(2026, 1, 4)),
by_name={"k": Item(sku="d", shipped_on=date(2026, 1, 5))},
)


def _decorate(function, persistence_layer):
config = IdempotencyConfig(use_local_cache=False)
config.register_lambda_context(FakeLambdaContext())
return idempotent_function(
function,
data_keyword_argument="order",
persistence_store=persistence_layer,
config=config,
output_serializer=DataclassSerializer,
)


def test_dataclass_serializer_saves_and_replays_non_json_native_fields():
# GIVEN a function returning a dataclass with UUID, datetime, date, Enum, Decimal and nested dataclasses
calls = []

def process(order: dict) -> Order:
calls.append(order)
return _build_order()

persistence_layer = InMemoryPersistenceLayer()
decorated = _decorate(process, persistence_layer)

# WHEN the same payload is sent twice
first = decorated(order={"id": 1})
second = decorated(order={"id": 1})

# THEN the first result is saved as COMPLETED instead of raising
assert [record.status for record in persistence_layer.records.values()] == ["COMPLETED"]

# AND the second call replays the stored result without running the function again
assert len(calls) == 1

# AND the replayed value equals the original, nested dataclasses included
assert first == _build_order()
assert second == first
assert isinstance(second.item, Item)
assert isinstance(second.items[0], Item)
assert isinstance(second.coupon, Item)
assert isinstance(second.by_name["k"], Item)


def test_dataclass_serializer_replays_plain_string_fields_unchanged():
# GIVEN a dataclass with only plain fields, as before this change
def process(order: dict) -> Receipt:
return Receipt(number="42", note="2026-01-01")

decorated = _decorate(process, InMemoryPersistenceLayer())

# WHEN it is replayed
first = decorated(order={"id": 1})
second = decorated(order={"id": 1})

# THEN string values that merely look like dates are not converted
assert first == second == Receipt(number="42", note="2026-01-01")