@@ -49,6 +49,28 @@ def _retrieve_or_set_model_from_cache(model: type[T]) -> TypeAdapter[T]:
4949 return CACHE_TYPE_ADAPTER [id_model ]
5050
5151
52+ def _parse_string_payload (data : str , adapter : TypeAdapter [T ]):
53+ """Validate a string payload as JSON first, then as a plain Python value.
54+
55+ Falls back to Python validation when Pydantic cannot validate the type from JSON
56+ (see https://github.com/aws-powertools/powertools-lambda-python/issues/5303) and when
57+ the string is not JSON at all, e.g. the plain-text Lambda runtime lines that CloudWatch Logs
58+ subscriptions forward (see https://github.com/aws-powertools/powertools-lambda-python/issues/8695).
59+ If the fallback fails too, the original JSON error is raised so callers see the same message.
60+ """
61+ try :
62+ return adapter .validate_json (data )
63+ except NotImplementedError :
64+ # See: https://github.com/pydantic/pydantic/issues/8890
65+ logger .debug ("Falling back to Python validation due to Pydantic implementation." )
66+ return adapter .validate_python (json .loads (data ))
67+ except ValidationError as exc :
68+ try :
69+ return adapter .validate_python (data )
70+ except ValidationError :
71+ raise exc from None
72+
73+
5274def _parse_and_validate_event (data : dict [str , Any ] | Any , adapter : TypeAdapter [T ]):
5375 """
5476 Parse and validate the event data using the provided adapter.
@@ -70,26 +92,7 @@ def _parse_and_validate_event(data: dict[str, Any] | Any, adapter: TypeAdapter[T
7092
7193 if isinstance (data , str ):
7294 logger .debug ("Parsing event as string" )
73- try :
74- return adapter .validate_json (data )
75- except NotImplementedError :
76- # See: https://github.com/aws-powertools/powertools-lambda-python/issues/5303
77- # See: https://github.com/pydantic/pydantic/issues/8890
78- logger .debug (
79- "Falling back to Python validation due to Pydantic implementation."
80- "See issue: https://github.com/aws-powertools/powertools-lambda-python/issues/5303" ,
81- )
82- data = json .loads (data )
83- except ValidationError as exc :
84- # CloudWatch Logs subscriptions forward plain-text Lambda runtime messages
85- # (START/END/REPORT) that are not valid JSON. Fall back to Python validation
86- # so string-compatible models still receive the raw payload; otherwise surface
87- # the original error.
88- # See: https://github.com/aws-powertools/powertools-lambda-python/issues/8695
89- try :
90- return adapter .validate_python (data )
91- except ValidationError :
92- raise exc from None
95+ return _parse_string_payload (data , adapter )
9396
9497 return adapter .validate_python (data )
9598
0 commit comments