capo-sagemaker-runtime-http2 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. capo_sagemaker_runtime_http2/__init__.py +74 -0
  2. capo_sagemaker_runtime_http2/_async.py +25 -0
  3. capo_sagemaker_runtime_http2/_auth/_identity.py +16 -0
  4. capo_sagemaker_runtime_http2/_auth/_providers.py +886 -0
  5. capo_sagemaker_runtime_http2/_auth/_signers.py +88 -0
  6. capo_sagemaker_runtime_http2/_auth/_sigv4.py +434 -0
  7. capo_sagemaker_runtime_http2/_auth/_zapros_handler.py +80 -0
  8. capo_sagemaker_runtime_http2/_iter.py +113 -0
  9. capo_sagemaker_runtime_http2/_operations/amazon_sage_maker_runtime_http2/invoke_endpoint_with_bidirectional_stream.py +264 -0
  10. capo_sagemaker_runtime_http2/_pagination.py +21 -0
  11. capo_sagemaker_runtime_http2/_protocol/__init__.py +1 -0
  12. capo_sagemaker_runtime_http2/_protocol/errors.py +93 -0
  13. capo_sagemaker_runtime_http2/_protocol/eventstream.py +238 -0
  14. capo_sagemaker_runtime_http2/_protocol/serialize.py +47 -0
  15. capo_sagemaker_runtime_http2/_protocol/xml.py +33 -0
  16. capo_sagemaker_runtime_http2/_rule_engine/__init__.py +0 -0
  17. capo_sagemaker_runtime_http2/_rule_engine/_aws_partition.py +160 -0
  18. capo_sagemaker_runtime_http2/_rule_engine/_endpoint_rule_set.py +560 -0
  19. capo_sagemaker_runtime_http2/_rule_engine/_endpoint_runtime.py +389 -0
  20. capo_sagemaker_runtime_http2/_services/_aws_config.py +160 -0
  21. capo_sagemaker_runtime_http2/_services/_pipeline.py +198 -0
  22. capo_sagemaker_runtime_http2/_services/async_sage_maker_runtime_http2.py +204 -0
  23. capo_sagemaker_runtime_http2/_services/sage_maker_runtime_http2.py +203 -0
  24. capo_sagemaker_runtime_http2/errors/__init__.py +31 -0
  25. capo_sagemaker_runtime_http2/errors/_base.py +94 -0
  26. capo_sagemaker_runtime_http2/errors/input_validation_error.py +53 -0
  27. capo_sagemaker_runtime_http2/errors/internal_server_error.py +51 -0
  28. capo_sagemaker_runtime_http2/errors/internal_stream_failure.py +61 -0
  29. capo_sagemaker_runtime_http2/errors/model_error.py +69 -0
  30. capo_sagemaker_runtime_http2/errors/model_stream_error.py +65 -0
  31. capo_sagemaker_runtime_http2/errors/service_unavailable_error.py +53 -0
  32. capo_sagemaker_runtime_http2/py.typed +0 -0
  33. capo_sagemaker_runtime_http2/types/_prelude/blob.py +12 -0
  34. capo_sagemaker_runtime_http2/types/_prelude/timestamp.py +17 -0
  35. capo_sagemaker_runtime_http2/types/invoke_endpoint_with_bidirectional_stream_input.py +21 -0
  36. capo_sagemaker_runtime_http2/types/invoke_endpoint_with_bidirectional_stream_output.py +15 -0
  37. capo_sagemaker_runtime_http2/types/request_payload_part.py +62 -0
  38. capo_sagemaker_runtime_http2/types/request_stream_event.py +52 -0
  39. capo_sagemaker_runtime_http2/types/response_payload_part.py +62 -0
  40. capo_sagemaker_runtime_http2/types/response_stream_event.py +100 -0
  41. capo_sagemaker_runtime_http2/types/sensitive_blob.py +15 -0
  42. capo_sagemaker_runtime_http2-0.1.0.dist-info/METADATA +108 -0
  43. capo_sagemaker_runtime_http2-0.1.0.dist-info/RECORD +46 -0
  44. capo_sagemaker_runtime_http2-0.1.0.dist-info/WHEEL +5 -0
  45. capo_sagemaker_runtime_http2-0.1.0.dist-info/licenses/LICENSE +21 -0
  46. capo_sagemaker_runtime_http2-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,113 @@
1
+ """Iterator helpers used by generated streaming operations.
2
+
3
+ Hand-written, not regenerated.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from collections.abc import AsyncIterable, AsyncIterator, Callable, Iterable, Iterator
9
+ from typing import Generic, TypeVar, cast
10
+
11
+ T = TypeVar("T")
12
+ U = TypeVar("U")
13
+
14
+
15
+ class AnyIterator(AsyncIterator[T], Iterator[T], Generic[T]):
16
+ """A type that is both a synchronous and asynchronous iterator.
17
+
18
+ Streaming output fields use this so the same TypedDict type works for
19
+ both sync and async operation variants.
20
+ """
21
+
22
+ ...
23
+
24
+
25
+ class StaticAnyIterator(AnyIterator[T], Generic[T]):
26
+ """An :class:`AnyIterator` backed by static, in-memory content.
27
+
28
+ Used when streaming output is produced from already-materialized bytes
29
+ rather than a live stream. The ``content`` is yielded once and remains
30
+ accessible as a public attribute.
31
+ """
32
+
33
+ def __init__(self, content: T) -> None:
34
+ self.content = content
35
+ self._consumed = False
36
+
37
+ def __next__(self) -> T:
38
+ if self._consumed:
39
+ raise StopIteration
40
+ self._consumed = True
41
+ return self.content
42
+
43
+ async def __anext__(self) -> T:
44
+ if self._consumed:
45
+ raise StopAsyncIteration
46
+ self._consumed = True
47
+ return self.content
48
+
49
+
50
+ def map_sync_iterator(iterable: Iterable[T], fn: Callable[[T], U]) -> Iterator[U]:
51
+ """Map ``fn`` over a synchronous iterable, yielding results lazily."""
52
+ for item in iterable:
53
+ yield fn(item)
54
+
55
+
56
+ async def map_async_iterator(
57
+ async_iterable: AsyncIterable[T], fn: Callable[[T], U]
58
+ ) -> AsyncIterator[U]:
59
+ """Map ``fn`` over an asynchronous iterable, yielding results lazily."""
60
+ async for item in async_iterable:
61
+ yield fn(item)
62
+
63
+
64
+ def chain_sync_iterator(*iterables: Iterable[T]) -> Iterator[T]:
65
+ """Yield items from each iterable in order."""
66
+ for iterable in iterables:
67
+ yield from iterable
68
+
69
+
70
+ async def chain_async_iterator(
71
+ prefix: Iterable[T], rest: AsyncIterable[T]
72
+ ) -> AsyncIterator[T]:
73
+ """Yield the synchronous ``prefix`` items, then the async ``rest`` items."""
74
+ for item in prefix:
75
+ yield item
76
+ async for item in rest:
77
+ yield item
78
+
79
+
80
+ def ensure_async_iterator(value: AsyncIterator[T] | T) -> AnyIterator[T]:
81
+ """Return ``value`` as an :class:`AnyIterator`.
82
+
83
+ An async iterator is returned unchanged; a single value is wrapped in a
84
+ fresh single-item async iterator.
85
+ """
86
+ if isinstance(value, AsyncIterator):
87
+ return cast(AnyIterator[T], value)
88
+
89
+ return StaticAnyIterator(value)
90
+
91
+
92
+ def ensure_sync_iterator(value: Iterator[T] | T) -> AnyIterator[T]:
93
+ """Return ``value`` as an :class:`AnyIterator`.
94
+
95
+ A sync iterator is returned unchanged; a single value is wrapped in a
96
+ fresh single-item sync iterator.
97
+ """
98
+ if isinstance(value, Iterator):
99
+ return cast(AnyIterator[T], value)
100
+
101
+ return StaticAnyIterator(value)
102
+
103
+
104
+ __all__ = [
105
+ "AnyIterator",
106
+ "StaticAnyIterator",
107
+ "chain_async_iterator",
108
+ "chain_sync_iterator",
109
+ "ensure_async_iterator",
110
+ "ensure_sync_iterator",
111
+ "map_async_iterator",
112
+ "map_sync_iterator",
113
+ ]
@@ -0,0 +1,264 @@
1
+ """Generated from Smithy shape ``com.amazonaws.sagemakerruntimehttp2#InvokeEndpointWithBidirectionalStream``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from typing import Any, cast
7
+ from urllib.parse import quote
8
+
9
+ import zapros
10
+ from typing_extensions import Never
11
+
12
+ import capo_sagemaker_runtime_http2._auth._signers
13
+ import capo_sagemaker_runtime_http2._auth._sigv4
14
+ import capo_sagemaker_runtime_http2._iter
15
+ import capo_sagemaker_runtime_http2._protocol.eventstream
16
+ import capo_sagemaker_runtime_http2.errors.input_validation_error
17
+ import capo_sagemaker_runtime_http2.errors.internal_server_error
18
+ import capo_sagemaker_runtime_http2.errors.internal_stream_failure
19
+ import capo_sagemaker_runtime_http2.errors.model_error
20
+ import capo_sagemaker_runtime_http2.errors.model_stream_error
21
+ import capo_sagemaker_runtime_http2.errors.service_unavailable_error
22
+ import capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_input
23
+ import capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_output
24
+ import capo_sagemaker_runtime_http2.types.request_stream_event
25
+ import capo_sagemaker_runtime_http2.types.response_stream_event
26
+ from capo_sagemaker_runtime_http2._protocol.errors import parse_error_metadata_json
27
+ from capo_sagemaker_runtime_http2._protocol.eventstream import (
28
+ MessageDecoder,
29
+ async_raw_stream_to_events,
30
+ raw_stream_to_events,
31
+ )
32
+ from capo_sagemaker_runtime_http2._rule_engine._endpoint_rule_set import (
33
+ EndpointParams,
34
+ resolve,
35
+ )
36
+ from capo_sagemaker_runtime_http2._services._pipeline import (
37
+ AsyncOperationOptions,
38
+ OperationOptions,
39
+ )
40
+ from capo_sagemaker_runtime_http2.errors import UnknownServiceError
41
+
42
+
43
+ def handle_error(response: zapros.Response) -> Never:
44
+ data = json.loads(response.read())
45
+ code, message = parse_error_metadata_json(response, data)
46
+ match code:
47
+ case "InputValidationError":
48
+ raise capo_sagemaker_runtime_http2.errors.input_validation_error.InputValidationError.from_json(
49
+ data, message
50
+ )
51
+ case "InternalServerError":
52
+ raise capo_sagemaker_runtime_http2.errors.internal_server_error.InternalServerError.from_json(
53
+ data, message
54
+ )
55
+ case "InternalStreamFailure":
56
+ raise capo_sagemaker_runtime_http2.errors.internal_stream_failure.InternalStreamFailure.from_json(
57
+ data, message
58
+ )
59
+ case "ModelError":
60
+ raise capo_sagemaker_runtime_http2.errors.model_error.ModelError.from_json(
61
+ data, message
62
+ )
63
+ case "ModelStreamError":
64
+ raise capo_sagemaker_runtime_http2.errors.model_stream_error.ModelStreamError.from_json(
65
+ data, message
66
+ )
67
+ case "ServiceUnavailableError":
68
+ raise capo_sagemaker_runtime_http2.errors.service_unavailable_error.ServiceUnavailableError.from_json(
69
+ data, message
70
+ )
71
+ case _:
72
+ raise UnknownServiceError(code=code, message=message, response=response)
73
+
74
+
75
+ def handle_response(
76
+ response: zapros.Response,
77
+ ) -> capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_output.InvokeEndpointWithBidirectionalStreamOutput:
78
+ _message_decoder = MessageDecoder()
79
+ _union_deser = (
80
+ capo_sagemaker_runtime_http2.types.response_stream_event.deserialize_event_json
81
+ )
82
+ _iter = cast(Any, response.iter_bytes())
83
+ out: capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_output.InvokeEndpointWithBidirectionalStreamOutput = {
84
+ "body": cast(Any, raw_stream_to_events(_iter, _message_decoder, _union_deser))
85
+ } # type: ignore[reportAssignmentType]
86
+ if "X-Amzn-Invoked-Production-Variant" in response.headers:
87
+ out["invoked_production_variant"] = response.headers[
88
+ "X-Amzn-Invoked-Production-Variant"
89
+ ]
90
+ return out
91
+
92
+
93
+ async def async_handle_response(
94
+ response: zapros.Response,
95
+ ) -> capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_output.InvokeEndpointWithBidirectionalStreamOutput:
96
+ _message_decoder = MessageDecoder()
97
+ _union_deser = (
98
+ capo_sagemaker_runtime_http2.types.response_stream_event.deserialize_event_json
99
+ )
100
+ _iter = cast(Any, response.async_iter_bytes())
101
+ out: capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_output.InvokeEndpointWithBidirectionalStreamOutput = {
102
+ "body": cast(
103
+ Any, async_raw_stream_to_events(_iter, _message_decoder, _union_deser)
104
+ )
105
+ } # type: ignore[reportAssignmentType]
106
+ if "X-Amzn-Invoked-Production-Variant" in response.headers:
107
+ out["invoked_production_variant"] = response.headers[
108
+ "X-Amzn-Invoked-Production-Variant"
109
+ ]
110
+ return out
111
+
112
+
113
+ def get_signer(
114
+ options: AsyncOperationOptions | OperationOptions,
115
+ auth_schemes: list[dict[str, Any]] | None = None,
116
+ ) -> capo_sagemaker_runtime_http2._auth._signers.Signer | None:
117
+ name_to_schema = {s["name"]: s for s in (auth_schemes or [])} # noqa: F841
118
+ if (
119
+ options.credentials_provider is not None
120
+ and name_to_schema
121
+ and not name_to_schema.keys() & {"sigv4", "sigv4-s3express"}
122
+ ):
123
+ raise RuntimeError(
124
+ "Endpoint requires an unsupported auth scheme: " + ", ".join(name_to_schema)
125
+ )
126
+ if options.credentials_provider is not None:
127
+ endpoint_scheme = name_to_schema.get("sigv4") or name_to_schema.get(
128
+ "sigv4-s3express"
129
+ )
130
+ if endpoint_scheme is not None or not name_to_schema:
131
+ sigv4_config = (
132
+ capo_sagemaker_runtime_http2._auth._sigv4.build_sigv4_auth_scheme(
133
+ "sagemaker", options.region, endpoint_scheme
134
+ )
135
+ )
136
+ if sigv4_config is not None:
137
+ return capo_sagemaker_runtime_http2._auth._signers.SigV4Signer(
138
+ options.credentials_provider, auth_scheme=sigv4_config
139
+ )
140
+ raise RuntimeError("Auth was not resolved")
141
+
142
+
143
+ def build_request(
144
+ options: OperationOptions | AsyncOperationOptions,
145
+ input_: capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_input.InvokeEndpointWithBidirectionalStreamInput,
146
+ ) -> zapros.Request:
147
+ endpoint = resolve(
148
+ EndpointParams(
149
+ UseDualStack=options.use_dual_stack,
150
+ UseFIPS=options.use_fips,
151
+ Endpoint=options.endpoint,
152
+ Region=options.region,
153
+ )
154
+ ) # noqa: F841
155
+ url = (
156
+ endpoint.url.rstrip("/")
157
+ + "/endpoints/{EndpointName}/invocations-bidirectional-stream"
158
+ )
159
+ url = url.replace("{EndpointName}", quote(input_["endpoint_name"], safe=""))
160
+ params: list[tuple[str, str]] = []
161
+ headers: dict[str, str] = {k: ", ".join(v) for k, v in endpoint.headers.items()}
162
+ if "target_variant" in input_:
163
+ headers["X-Amzn-SageMaker-Target-Variant"] = input_["target_variant"]
164
+ if "model_invocation_path" in input_:
165
+ headers["X-Amzn-SageMaker-Model-Invocation-Path"] = input_[
166
+ "model_invocation_path"
167
+ ]
168
+ if "model_query_string" in input_:
169
+ headers["X-Amzn-SageMaker-Model-Query-String"] = input_["model_query_string"]
170
+
171
+ body = capo_sagemaker_runtime_http2._iter.map_sync_iterator(
172
+ input_["body"],
173
+ capo_sagemaker_runtime_http2.types.request_stream_event.serialize_event_json,
174
+ )
175
+
176
+ headers["content-type"] = "application/vnd.amazon-eventstream"
177
+ signer = get_signer(options, auth_schemes=endpoint.properties.get("authSchemes"))
178
+ normalized_url = zapros.URL(url)
179
+ for k, v in params:
180
+ normalized_url.search_params.append(k, v)
181
+ return zapros.Request(
182
+ normalized_url, "POST", headers=headers, body=body, context={"signer": signer}
183
+ )
184
+
185
+
186
+ def async_build_request(
187
+ options: OperationOptions | AsyncOperationOptions,
188
+ input_: capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_input.InvokeEndpointWithBidirectionalStreamInput,
189
+ ) -> zapros.Request:
190
+ endpoint = resolve(
191
+ EndpointParams(
192
+ UseDualStack=options.use_dual_stack,
193
+ UseFIPS=options.use_fips,
194
+ Endpoint=options.endpoint,
195
+ Region=options.region,
196
+ )
197
+ ) # noqa: F841
198
+ url = (
199
+ endpoint.url.rstrip("/")
200
+ + "/endpoints/{EndpointName}/invocations-bidirectional-stream"
201
+ )
202
+ url = url.replace("{EndpointName}", quote(input_["endpoint_name"], safe=""))
203
+ params: list[tuple[str, str]] = []
204
+ headers: dict[str, str] = {k: ", ".join(v) for k, v in endpoint.headers.items()}
205
+ if "target_variant" in input_:
206
+ headers["X-Amzn-SageMaker-Target-Variant"] = input_["target_variant"]
207
+ if "model_invocation_path" in input_:
208
+ headers["X-Amzn-SageMaker-Model-Invocation-Path"] = input_[
209
+ "model_invocation_path"
210
+ ]
211
+ if "model_query_string" in input_:
212
+ headers["X-Amzn-SageMaker-Model-Query-String"] = input_["model_query_string"]
213
+
214
+ body = capo_sagemaker_runtime_http2._iter.map_async_iterator(
215
+ input_["body"],
216
+ capo_sagemaker_runtime_http2.types.request_stream_event.serialize_event_json,
217
+ )
218
+
219
+ headers["content-type"] = "application/vnd.amazon-eventstream"
220
+ signer = get_signer(options, auth_schemes=endpoint.properties.get("authSchemes"))
221
+ normalized_url = zapros.URL(url)
222
+ for k, v in params:
223
+ normalized_url.search_params.append(k, v)
224
+ return zapros.Request(
225
+ normalized_url, "POST", headers=headers, body=body, context={"signer": signer}
226
+ )
227
+
228
+
229
+ def invoke_endpoint_with_bidirectional_stream(
230
+ options: OperationOptions,
231
+ input_: capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_input.InvokeEndpointWithBidirectionalStreamInput,
232
+ ) -> tuple[
233
+ capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_output.InvokeEndpointWithBidirectionalStreamOutput,
234
+ zapros.Response,
235
+ ]:
236
+ response = options.client.handler.handle(build_request(options, input_))
237
+ try:
238
+ if response.status >= 300:
239
+ response.read()
240
+ handle_error(response)
241
+ return handle_response(response), response
242
+ except BaseException:
243
+ response.close()
244
+ raise
245
+
246
+
247
+ async def async_invoke_endpoint_with_bidirectional_stream(
248
+ options: AsyncOperationOptions,
249
+ input_: capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_input.InvokeEndpointWithBidirectionalStreamInput,
250
+ ) -> tuple[
251
+ capo_sagemaker_runtime_http2.types.invoke_endpoint_with_bidirectional_stream_output.InvokeEndpointWithBidirectionalStreamOutput,
252
+ zapros.Response,
253
+ ]:
254
+ response = await options.client.handler.ahandle(
255
+ async_build_request(options, input_)
256
+ )
257
+ try:
258
+ if response.status >= 300:
259
+ await response.aread()
260
+ handle_error(response)
261
+ return await async_handle_response(response), response
262
+ except BaseException:
263
+ await response.aclose()
264
+ raise
@@ -0,0 +1,21 @@
1
+ """Runtime helpers for generated paginated ``iter_*`` operation methods."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+
8
+ def resolve_path(obj: Any, path: tuple[str, ...]) -> Any:
9
+ """Walk ``path`` segments on a nested ``dict`` (TypedDict at runtime).
10
+
11
+ Returns ``None`` as soon as any intermediate value is missing or non-dict —
12
+ the generated iter loop uses a falsy token as the terminate signal, so this
13
+ short-circuit gives the same semantics for dotted paths as for top-level ones.
14
+ """
15
+ for key in path:
16
+ if not isinstance(obj, dict):
17
+ return None
18
+ obj = obj.get(key)
19
+ if obj is None:
20
+ return None
21
+ return obj
@@ -0,0 +1 @@
1
+ """Protocol runtime modules. Hand-written; not generated."""
@@ -0,0 +1,93 @@
1
+ """Shared service-error runtime.
2
+
3
+ Hand-written, not regenerated. Helpers for extracting error metadata
4
+ from HTTP error responses.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from typing import TYPE_CHECKING
10
+
11
+ from zapros import Response
12
+
13
+ from .xml import fromstring
14
+
15
+ if TYPE_CHECKING:
16
+ from xml.etree.ElementTree import Element
17
+
18
+
19
+ def find_error_element(root: Element) -> Element:
20
+ """Return the element holding the error structure's members.
21
+
22
+ Handles the three XML error envelopes: a bare ``<Error>`` root
23
+ (restXml with ``noErrorWrapping``), an ``<ErrorResponse><Error>``
24
+ wrapper (restXml/awsQuery), and the ec2Query
25
+ ``<Response><Errors><Error>`` envelope. Falls back to ``root``
26
+ when no ``<Error>`` element is found.
27
+ """
28
+ if root.tag.endswith("Error"):
29
+ return root
30
+ for path in ("Error", "Errors/Error"):
31
+ err = root.find(path)
32
+ if err is not None:
33
+ return err
34
+ return root
35
+
36
+
37
+ def parse_error_metadata(root: Element) -> tuple[str | None, str | None]:
38
+ """Return ``(code, message)`` from an XML error envelope.
39
+
40
+ Accepts any envelope understood by :func:`find_error_element`.
41
+ Missing children yield ``None``.
42
+ """
43
+ err = find_error_element(root)
44
+ code_el = err.find("Code")
45
+ msg_el = err.find("Message")
46
+ code = code_el.text if code_el is not None else None
47
+ message = msg_el.text if msg_el is not None else None
48
+ return code, message
49
+
50
+
51
+ def parse_error_metadata_json(
52
+ response: Response, data: dict
53
+ ) -> tuple[str | None, str | None]:
54
+ """Return ``(code, message)`` from a restJson1 error response.
55
+
56
+ Code precedence: the ``X-Amzn-Errortype`` response header, then the
57
+ ``__type`` body field, then ``code``. The raw value is normalized by
58
+ dropping a trailing ``:uri`` suffix first, then a ``prefix#``
59
+ namespace — in that order, so a ``#`` inside the uri suffix cannot
60
+ hijack the code. Message comes from ``message`` or ``Message``.
61
+ Missing values yield ``None``.
62
+ """
63
+ code = (
64
+ response.headers.get("X-Amzn-Errortype")
65
+ or data.get("__type")
66
+ or data.get("code")
67
+ )
68
+ if code is not None:
69
+ code = code.split(":", 1)[0].rsplit("#", 1)[-1]
70
+ message = data.get("message") or data.get("Message")
71
+ return code, message
72
+
73
+
74
+ def is_xml_error_body(body: bytes) -> bool:
75
+ """Whether a 2xx response body is really an XML error document.
76
+
77
+ S3 answers CopyObject, UploadPartCopy and CompleteMultipartUpload
78
+ with ``200 OK`` before the operation finishes; a failure after that
79
+ point is reported as an ``<Error>`` body (or an empty body) on the
80
+ 200 response. Official SDKs check the body for exactly these
81
+ operations.
82
+ """
83
+ if not body:
84
+ return True
85
+ return fromstring(body).tag == "Error"
86
+
87
+
88
+ __all__ = [
89
+ "find_error_element",
90
+ "is_xml_error_body",
91
+ "parse_error_metadata",
92
+ "parse_error_metadata_json",
93
+ ]