-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmodels.py
More file actions
263 lines (217 loc) · 8.55 KB
/
models.py
File metadata and controls
263 lines (217 loc) · 8.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
"""HTTP request/response data models and utilities for the web runner."""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass
from typing import Any, Protocol
from aws_durable_execution_sdk_python_testing.exceptions import (
AwsApiException,
InvalidParameterValueException,
)
# Removed deprecated imports from web.errors
from aws_durable_execution_sdk_python_testing.web.routes import Route
from aws_durable_execution_sdk_python_testing.web.serialization import (
AwsRestJsonDeserializer,
JSONSerializer,
Serializer,
)
logger = logging.getLogger(__name__)
@dataclass(frozen=True)
class HTTPRequest:
"""HTTP request data model with dict or bytes body for handler logic."""
method: str
path: Route
headers: dict[str, str]
query_params: dict[str, list[str]]
body: dict[str, Any] | bytes
@classmethod
def from_raw_bytes(
cls,
body_bytes: bytes,
method: str = "POST",
path: Route | None = None,
headers: dict[str, str] | None = None,
query_params: dict[str, list[str]] | None = None,
) -> HTTPRequest:
"""Create HTTPRequest with raw bytes body (no parsing)."""
if headers is None:
headers = {}
if query_params is None:
query_params = {}
if path is None:
path = Route.from_string("")
return cls(
method=method,
path=path,
headers=headers,
query_params=query_params,
body=body_bytes,
)
@classmethod
def from_bytes(
cls,
body_bytes: bytes,
operation_name: str | None = None,
method: str = "POST",
path: Route | None = None,
headers: dict[str, str] | None = None,
query_params: dict[str, list[str]] | None = None,
) -> HTTPRequest:
"""Create HTTPRequest from raw bytes, deserializing to dict body.
Args:
body_bytes: Raw bytes to deserialize
operation_name: Optional AWS operation name for boto deserialization
method: HTTP method (default: POST)
path: Route object (required for actual usage)
headers: HTTP headers (default: empty dict)
query_params: Query parameters (default: empty dict)
Returns:
HTTPRequest: Request with deserialized dict body
Raises:
InvalidParameterValueException: If deserialization fails with both AWS and JSON methods
"""
if headers is None:
headers = {}
if query_params is None:
query_params = {}
# Skip body parsing for GET requests
if method == "GET":
body_dict = {}
logger.debug("GET request, skipping body parsing")
# Try AWS deserialization first if operation_name provided
elif operation_name:
try:
deserializer = AwsRestJsonDeserializer.create(operation_name)
body_dict = deserializer.from_bytes(body_bytes)
logger.debug(
"Successfully deserialized request using AWS deserializer for %s",
operation_name,
)
except InvalidParameterValueException as e:
logger.warning(
"AWS deserialization failed for %s, falling back to JSON: %s",
operation_name,
e,
)
# Fall back to standard JSON
try:
body_dict = json.loads(body_bytes.decode("utf-8"))
logger.debug(
"Successfully deserialized request using JSON fallback"
)
except (json.JSONDecodeError, UnicodeDecodeError) as json_error:
msg = f"Both AWS and JSON deserialization failed: AWS error: {e}, JSON error: {json_error}"
raise InvalidParameterValueException(msg) from json_error
else:
# Use standard JSON deserialization
try:
body_dict = json.loads(body_bytes.decode("utf-8"))
logger.debug("Successfully deserialized request using standard JSON")
except (json.JSONDecodeError, UnicodeDecodeError) as e:
msg = f"JSON deserialization failed: {e}"
raise InvalidParameterValueException(msg) from e
# Handle case where path is None for testing
if path is None:
path = Route.from_string("")
return cls(
method=method,
path=path,
headers=headers,
query_params=query_params,
body=body_dict,
)
@dataclass(frozen=True)
class HTTPResponse:
"""HTTP response data model with dict body and serialization capabilities."""
status_code: int
headers: dict[str, str]
body: dict[str, Any]
serializer: Serializer = JSONSerializer()
def body_to_bytes(self) -> bytes:
"""Convert response dict body to bytes for HTTP transmission.
Returns:
bytes: Serialized response body
Raises:
InvalidParameterValueException: If serialization fails with both AWS and JSON methods
"""
result = self.serializer.to_bytes(data=self.body)
logger.debug("Serialized result - before: %s, after: %s", self.body, result)
return result
@classmethod
def from_dict(
cls,
data: dict[str, Any],
status_code: int = 200,
headers: dict[str, str] | None = None,
) -> HTTPResponse:
"""Create HTTPResponse from dict data.
Args:
data: Response data as dictionary
status_code: HTTP status code (default: 200)
headers: HTTP headers (default: empty dict)
Returns:
HTTPResponse: Response with dict body
"""
if headers is None:
headers = {}
return cls(status_code=status_code, headers=headers, body=data)
@staticmethod
def create_json(
status_code: int,
data: dict[str, Any],
additional_headers: dict[str, str] | None = None,
) -> HTTPResponse:
"""Create a JSON HTTP response.
Args:
status_code: HTTP status code
data: Data to serialize as JSON
additional_headers: Optional additional headers to include
Returns:
HTTPResponse: The HTTP response with dict body
"""
headers = {"Content-Type": "application/json"}
if additional_headers:
headers.update(additional_headers)
return HTTPResponse(status_code=status_code, headers=headers, body=data)
# Removed deprecated create_error method - use create_error_from_exception instead
@staticmethod
def create_error_from_exception(aws_exception: AwsApiException) -> HTTPResponse:
"""Create AWS-compliant error response from AwsApiException.
Args:
aws_exception: The AWS API exception to convert to HTTP response
Returns:
HTTPResponse: The HTTP error response with AWS-compliant format
"""
if not isinstance(aws_exception, AwsApiException):
msg = f"Expected AwsApiException, got {type(aws_exception)}"
raise TypeError(msg)
# Use exception's http_status_code and to_dict() method
# This removes the wrapper "error" object to match AWS format
error_data = aws_exception.to_dict()
return HTTPResponse.create_json(aws_exception.http_status_code, error_data)
@staticmethod
def create_empty(
status_code: int, additional_headers: dict[str, str] | None = None
) -> HTTPResponse:
"""Create an empty HTTP response.
Args:
status_code: HTTP status code
additional_headers: Optional additional headers to include
Returns:
HTTPResponse: The HTTP response with empty dict body
"""
headers = {}
if additional_headers:
headers.update(additional_headers)
return HTTPResponse(status_code=status_code, headers=headers, body={})
class OperationHandler(Protocol):
"""Protocol for handling HTTP operations with strongly-typed paths."""
def handle(self, parsed_route: Route, request: HTTPRequest) -> HTTPResponse:
"""Handle an HTTP request and return an HTTP response.
Args:
parsed_route: The strongly-typed route object
request: The HTTP request data
Returns:
HTTPResponse: The HTTP response to send to the client
"""
... # pragma: no cover