brellium-api-client 0.2.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.
- brellium_api_client/__init__.py +98 -0
- brellium_api_client/_base_client.py +2904 -0
- brellium_api_client/_client.py +721 -0
- brellium_api_client/_compat.py +195 -0
- brellium_api_client/_constants.py +14 -0
- brellium_api_client/_decoding.py +187 -0
- brellium_api_client/_event_handler.py +85 -0
- brellium_api_client/_exceptions.py +126 -0
- brellium_api_client/_files.py +173 -0
- brellium_api_client/_models.py +965 -0
- brellium_api_client/_qs.py +147 -0
- brellium_api_client/_resource.py +43 -0
- brellium_api_client/_response.py +842 -0
- brellium_api_client/_send_queue.py +90 -0
- brellium_api_client/_streaming.py +412 -0
- brellium_api_client/_types.py +279 -0
- brellium_api_client/_utils/__init__.py +64 -0
- brellium_api_client/_utils/_compat.py +45 -0
- brellium_api_client/_utils/_datetime_parse.py +156 -0
- brellium_api_client/_utils/_json.py +35 -0
- brellium_api_client/_utils/_logs.py +356 -0
- brellium_api_client/_utils/_path.py +127 -0
- brellium_api_client/_utils/_proxy.py +65 -0
- brellium_api_client/_utils/_reflection.py +42 -0
- brellium_api_client/_utils/_resources_proxy.py +24 -0
- brellium_api_client/_utils/_streams.py +12 -0
- brellium_api_client/_utils/_sync.py +58 -0
- brellium_api_client/_utils/_transform.py +472 -0
- brellium_api_client/_utils/_typing.py +156 -0
- brellium_api_client/_utils/_utils.py +428 -0
- brellium_api_client/_version.py +4 -0
- brellium_api_client/py.typed +0 -0
- brellium_api_client/resources/__init__.py +89 -0
- brellium_api_client/resources/audits.py +597 -0
- brellium_api_client/resources/coding_evaluations.py +354 -0
- brellium_api_client/resources/documents.py +654 -0
- brellium_api_client/resources/email_recipients.py +718 -0
- brellium_api_client/resources/question_sets.py +313 -0
- brellium_api_client/resources/users.py +852 -0
- brellium_api_client/types/__init__.py +49 -0
- brellium_api_client/types/audit.py +56 -0
- brellium_api_client/types/audit_batch_result.py +59 -0
- brellium_api_client/types/audit_batch_update_flags_params.py +22 -0
- brellium_api_client/types/audit_display_info_item.py +21 -0
- brellium_api_client/types/audit_list.py +26 -0
- brellium_api_client/types/audit_list_params.py +56 -0
- brellium_api_client/types/audit_person.py +23 -0
- brellium_api_client/types/audit_response.py +32 -0
- brellium_api_client/types/audit_update_params.py +13 -0
- brellium_api_client/types/coding_evaluation.py +54 -0
- brellium_api_client/types/coding_evaluation_list.py +26 -0
- brellium_api_client/types/coding_evaluation_list_params.py +50 -0
- brellium_api_client/types/created_user.py +13 -0
- brellium_api_client/types/document.py +64 -0
- brellium_api_client/types/document_create_params.py +32 -0
- brellium_api_client/types/document_list.py +26 -0
- brellium_api_client/types/document_list_params.py +50 -0
- brellium_api_client/types/document_update_params.py +16 -0
- brellium_api_client/types/document_upload_list.py +26 -0
- brellium_api_client/types/document_with_upload.py +15 -0
- brellium_api_client/types/em_evaluation.py +85 -0
- brellium_api_client/types/email_recipient.py +37 -0
- brellium_api_client/types/email_recipient_create_params.py +22 -0
- brellium_api_client/types/email_recipient_list.py +26 -0
- brellium_api_client/types/email_recipient_list_params.py +38 -0
- brellium_api_client/types/email_recipient_update_params.py +22 -0
- brellium_api_client/types/icd_code_finding.py +22 -0
- brellium_api_client/types/icd_criterion.py +21 -0
- brellium_api_client/types/icd_evaluation.py +32 -0
- brellium_api_client/types/mdm_data.py +18 -0
- brellium_api_client/types/mdm_problem.py +18 -0
- brellium_api_client/types/mdm_risk.py +18 -0
- brellium_api_client/types/presigned_upload.py +25 -0
- brellium_api_client/types/question.py +33 -0
- brellium_api_client/types/question_set.py +42 -0
- brellium_api_client/types/question_set_list.py +26 -0
- brellium_api_client/types/question_set_list_params.py +29 -0
- brellium_api_client/types/user.py +37 -0
- brellium_api_client/types/user_batch_result.py +59 -0
- brellium_api_client/types/user_batch_update_params.py +27 -0
- brellium_api_client/types/user_create_params.py +19 -0
- brellium_api_client/types/user_invitation.py +17 -0
- brellium_api_client/types/user_list.py +26 -0
- brellium_api_client/types/user_list_params.py +38 -0
- brellium_api_client/types/user_update_params.py +19 -0
- brellium_api_client-0.2.0.dist-info/METADATA +183 -0
- brellium_api_client-0.2.0.dist-info/RECORD +89 -0
- brellium_api_client-0.2.0.dist-info/WHEEL +4 -0
- brellium_api_client-0.2.0.dist-info/licenses/LICENSE +201 -0
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Any, Union, TypeVar, cast
|
|
4
|
+
from datetime import date, datetime
|
|
5
|
+
from typing_extensions import Literal, TypedDict
|
|
6
|
+
|
|
7
|
+
import pydantic
|
|
8
|
+
from pydantic.fields import FieldInfo
|
|
9
|
+
|
|
10
|
+
from ._types import IncEx, StrBytesIntFloat
|
|
11
|
+
|
|
12
|
+
_ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel)
|
|
13
|
+
|
|
14
|
+
# --------------- Pydantic v2, v3 compatibility ---------------
|
|
15
|
+
|
|
16
|
+
# Pyright incorrectly reports some of our functions as overriding a method when they don't
|
|
17
|
+
# pyright: reportIncompatibleMethodOverride=false
|
|
18
|
+
|
|
19
|
+
PYDANTIC_V1 = pydantic.VERSION.startswith("1.")
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
|
|
23
|
+
def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001
|
|
24
|
+
...
|
|
25
|
+
|
|
26
|
+
def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001
|
|
27
|
+
...
|
|
28
|
+
|
|
29
|
+
def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001
|
|
30
|
+
...
|
|
31
|
+
|
|
32
|
+
def is_union(tp: type[Any] | None) -> bool: # noqa: ARG001
|
|
33
|
+
...
|
|
34
|
+
|
|
35
|
+
def get_origin(t: type[Any]) -> type[Any] | None: # noqa: ARG001
|
|
36
|
+
...
|
|
37
|
+
|
|
38
|
+
def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001
|
|
39
|
+
...
|
|
40
|
+
|
|
41
|
+
def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001
|
|
42
|
+
...
|
|
43
|
+
|
|
44
|
+
else:
|
|
45
|
+
# v1 re-exports
|
|
46
|
+
if PYDANTIC_V1:
|
|
47
|
+
from pydantic.typing import (
|
|
48
|
+
get_args as get_args,
|
|
49
|
+
is_union as is_union,
|
|
50
|
+
get_origin as get_origin,
|
|
51
|
+
is_typeddict as is_typeddict,
|
|
52
|
+
is_literal_type as is_literal_type,
|
|
53
|
+
)
|
|
54
|
+
from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
|
|
55
|
+
else:
|
|
56
|
+
from ._utils import (
|
|
57
|
+
get_args as get_args,
|
|
58
|
+
is_union as is_union,
|
|
59
|
+
get_origin as get_origin,
|
|
60
|
+
parse_date as parse_date,
|
|
61
|
+
is_typeddict as is_typeddict,
|
|
62
|
+
parse_datetime as parse_datetime,
|
|
63
|
+
is_literal_type as is_literal_type,
|
|
64
|
+
)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
# refactored config
|
|
68
|
+
if TYPE_CHECKING:
|
|
69
|
+
from pydantic import ConfigDict as ConfigDict
|
|
70
|
+
else:
|
|
71
|
+
if PYDANTIC_V1:
|
|
72
|
+
# TODO: provide an error message here?
|
|
73
|
+
ConfigDict = None
|
|
74
|
+
else:
|
|
75
|
+
from pydantic import ConfigDict as ConfigDict
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
# renamed methods / properties
|
|
79
|
+
def parse_obj(model: type[_ModelT], value: object) -> _ModelT:
|
|
80
|
+
if PYDANTIC_V1:
|
|
81
|
+
return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
|
|
82
|
+
else:
|
|
83
|
+
return model.model_validate(value)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def field_is_required(field: FieldInfo) -> bool:
|
|
87
|
+
if PYDANTIC_V1:
|
|
88
|
+
return field.required # type: ignore
|
|
89
|
+
return field.is_required()
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def field_get_default(field: FieldInfo) -> Any:
|
|
93
|
+
value = field.get_default()
|
|
94
|
+
if PYDANTIC_V1:
|
|
95
|
+
return value
|
|
96
|
+
from pydantic_core import PydanticUndefined
|
|
97
|
+
|
|
98
|
+
if value == PydanticUndefined:
|
|
99
|
+
return None
|
|
100
|
+
return value
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def field_outer_type(field: FieldInfo) -> Any:
|
|
104
|
+
if PYDANTIC_V1:
|
|
105
|
+
return field.outer_type_ # type: ignore
|
|
106
|
+
return field.annotation
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def get_model_config(model: type[pydantic.BaseModel]) -> Any:
|
|
110
|
+
if PYDANTIC_V1:
|
|
111
|
+
return model.__config__ # type: ignore
|
|
112
|
+
return model.model_config
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]:
|
|
116
|
+
if PYDANTIC_V1:
|
|
117
|
+
return model.__fields__ # type: ignore
|
|
118
|
+
return model.model_fields
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT:
|
|
122
|
+
if PYDANTIC_V1:
|
|
123
|
+
return model.copy(deep=deep) # type: ignore
|
|
124
|
+
return model.model_copy(deep=deep)
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str:
|
|
128
|
+
if PYDANTIC_V1:
|
|
129
|
+
return model.json(indent=indent) # type: ignore
|
|
130
|
+
return model.model_dump_json(indent=indent)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
class _ModelDumpKwargs(TypedDict, total=False):
|
|
134
|
+
by_alias: bool
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def model_dump(
|
|
138
|
+
model: pydantic.BaseModel,
|
|
139
|
+
*,
|
|
140
|
+
exclude: IncEx | None = None,
|
|
141
|
+
exclude_unset: bool = False,
|
|
142
|
+
exclude_defaults: bool = False,
|
|
143
|
+
warnings: bool = True,
|
|
144
|
+
mode: Literal["json", "python"] = "python",
|
|
145
|
+
by_alias: bool | None = None,
|
|
146
|
+
) -> dict[str, Any]:
|
|
147
|
+
if (not PYDANTIC_V1) or hasattr(model, "model_dump"):
|
|
148
|
+
kwargs: _ModelDumpKwargs = {}
|
|
149
|
+
if by_alias is not None:
|
|
150
|
+
kwargs["by_alias"] = by_alias
|
|
151
|
+
return model.model_dump(
|
|
152
|
+
mode=mode,
|
|
153
|
+
exclude=exclude,
|
|
154
|
+
exclude_unset=exclude_unset,
|
|
155
|
+
exclude_defaults=exclude_defaults,
|
|
156
|
+
# warnings are not supported in Pydantic v1
|
|
157
|
+
warnings=True if PYDANTIC_V1 else warnings,
|
|
158
|
+
**kwargs,
|
|
159
|
+
)
|
|
160
|
+
return cast(
|
|
161
|
+
"dict[str, Any]",
|
|
162
|
+
model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
|
|
163
|
+
exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, by_alias=bool(by_alias)
|
|
164
|
+
),
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def model_parse(model: type[_ModelT], data: Any) -> _ModelT:
|
|
169
|
+
if PYDANTIC_V1:
|
|
170
|
+
return model.parse_obj(data) # pyright: ignore[reportDeprecated]
|
|
171
|
+
return model.model_validate(data)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
# generic models
|
|
175
|
+
if TYPE_CHECKING:
|
|
176
|
+
|
|
177
|
+
class GenericModel(pydantic.BaseModel): ...
|
|
178
|
+
|
|
179
|
+
else:
|
|
180
|
+
if PYDANTIC_V1:
|
|
181
|
+
import pydantic.generics
|
|
182
|
+
|
|
183
|
+
class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ...
|
|
184
|
+
else:
|
|
185
|
+
# there no longer needs to be a distinction in v2 but
|
|
186
|
+
# we still have to create our own subclass to avoid
|
|
187
|
+
# inconsistent MRO ordering errors
|
|
188
|
+
class GenericModel(pydantic.BaseModel): ...
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
# cached properties
|
|
192
|
+
if TYPE_CHECKING:
|
|
193
|
+
cached_property = property
|
|
194
|
+
else:
|
|
195
|
+
from functools import cached_property as cached_property
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# File generated from our OpenAPI spec by Scalar. See CONTRIBUTING.md for details.
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
|
|
5
|
+
RAW_RESPONSE_HEADER = "X-Scalar-Raw-Response"
|
|
6
|
+
OVERRIDE_CAST_TO_HEADER = "____scalar_override_cast_to"
|
|
7
|
+
|
|
8
|
+
# default timeout is 1 minute
|
|
9
|
+
DEFAULT_TIMEOUT = httpx.Timeout(timeout=60, connect=5.0)
|
|
10
|
+
DEFAULT_MAX_RETRIES = 2
|
|
11
|
+
DEFAULT_CONNECTION_LIMITS = httpx.Limits(max_connections=100, max_keepalive_connections=20)
|
|
12
|
+
|
|
13
|
+
INITIAL_RETRY_DELAY = 0.5
|
|
14
|
+
MAX_RETRY_DELAY = 8.0
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
"""Bounded decoding of a response's content codings.
|
|
2
|
+
|
|
3
|
+
httpx inflates a whole network read in one call, so with stacked codings (`gzip, gzip`) a few KiB read
|
|
4
|
+
can expand to gigabytes before any size limit sees a byte. Buffered bodies and streamed ones (SSE,
|
|
5
|
+
JSON Lines) read their bytes through `BoundedDecoder` instead, which inflates gzip and deflate in
|
|
6
|
+
steps of at most `INFLATE_STEP` bytes, so every reader can stop at its own limit after each step.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import zlib
|
|
12
|
+
from typing import Dict, List, Mapping, Iterator, AsyncIterator, cast
|
|
13
|
+
|
|
14
|
+
import httpx
|
|
15
|
+
|
|
16
|
+
from ._exceptions import APIError
|
|
17
|
+
|
|
18
|
+
# The most bytes one inflate step produces.
|
|
19
|
+
INFLATE_STEP = 64 * 1024
|
|
20
|
+
|
|
21
|
+
# The content codings `BoundedDecoder` undoes itself, with the zlib window bits that read each one.
|
|
22
|
+
ZLIB_CODINGS: Dict[str, int] = {
|
|
23
|
+
"gzip": zlib.MAX_WBITS | 16,
|
|
24
|
+
"x-gzip": zlib.MAX_WBITS | 16,
|
|
25
|
+
"deflate": zlib.MAX_WBITS,
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
# Codings only httpx can undo, each through an optional package and without bounding the output, so a
|
|
29
|
+
# body that uses one is refused. httpx skips one whose package is missing, and so does `BoundedDecoder`.
|
|
30
|
+
HTTPX_ONLY_CODINGS = frozenset({"br", "zstd"})
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class CodingRefused(Exception):
|
|
34
|
+
"""A success body coded br or zstd, which no limit could bound; the caller reports it as an SDK error."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, message: str) -> None:
|
|
37
|
+
super().__init__(message)
|
|
38
|
+
self.message = message
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
class Inflater:
|
|
42
|
+
"""One gzip or deflate layer, inflated at most `INFLATE_STEP` bytes per step.
|
|
43
|
+
|
|
44
|
+
A deflate body should be zlib-wrapped, but some servers send it raw; as httpx does, a stream whose
|
|
45
|
+
first bytes are not a zlib header is read again as raw deflate.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
def __init__(self, wbits: int) -> None:
|
|
49
|
+
self._wbits = wbits
|
|
50
|
+
self._decompressor = zlib.decompressobj(wbits)
|
|
51
|
+
self._started = False
|
|
52
|
+
|
|
53
|
+
def feed(self, data: bytes) -> Iterator[bytes]:
|
|
54
|
+
"""Inflates `data`, yielding the output in pieces of at most `INFLATE_STEP` bytes."""
|
|
55
|
+
while not self._decompressor.eof:
|
|
56
|
+
try:
|
|
57
|
+
out = self._decompressor.decompress(data, INFLATE_STEP)
|
|
58
|
+
except zlib.error:
|
|
59
|
+
if self._started or self._wbits != zlib.MAX_WBITS:
|
|
60
|
+
raise
|
|
61
|
+
self._wbits = -zlib.MAX_WBITS
|
|
62
|
+
self._decompressor = zlib.decompressobj(self._wbits)
|
|
63
|
+
continue
|
|
64
|
+
self._started = True
|
|
65
|
+
# Input past the step stays in `unconsumed_tail`; an empty step with nothing left means
|
|
66
|
+
# zlib needs more input.
|
|
67
|
+
data = self._decompressor.unconsumed_tail
|
|
68
|
+
if out:
|
|
69
|
+
yield out
|
|
70
|
+
elif not data:
|
|
71
|
+
break
|
|
72
|
+
|
|
73
|
+
def flush(self) -> Iterator[bytes]:
|
|
74
|
+
"""Whatever the layer still holds once the body has ended; `feed` has drained it to a few bytes."""
|
|
75
|
+
out = self._decompressor.flush()
|
|
76
|
+
if out:
|
|
77
|
+
yield out
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def httpx_decoders() -> Mapping[str, object]:
|
|
81
|
+
"""The content codings the installed httpx decodes; br and zstd appear only with their optional packages."""
|
|
82
|
+
try:
|
|
83
|
+
from httpx._decoders import SUPPORTED_DECODERS # pyright: ignore[reportPrivateUsage]
|
|
84
|
+
except ImportError:
|
|
85
|
+
return {}
|
|
86
|
+
return cast("Mapping[str, object]", SUPPORTED_DECODERS)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class BoundedDecoder:
|
|
90
|
+
"""Undoes a response's gzip and deflate content codings, stacked ones included, in bounded steps.
|
|
91
|
+
|
|
92
|
+
Each layer hands the next a piece of at most `INFLATE_STEP` bytes, so a reader can stop at its
|
|
93
|
+
limit after every step instead of after httpx has inflated a whole network read at once.
|
|
94
|
+
"""
|
|
95
|
+
|
|
96
|
+
def __init__(self, layers: List[Inflater]) -> None:
|
|
97
|
+
self._layers = layers
|
|
98
|
+
|
|
99
|
+
@classmethod
|
|
100
|
+
def for_response(cls, response: httpx.Response, *, capped: bool) -> BoundedDecoder | None:
|
|
101
|
+
"""The decoder for `response`'s `Content-Encoding`, or None when httpx must decode it.
|
|
102
|
+
|
|
103
|
+
httpx decodes a body read uncapped and a body it already holds (a transport may hand back a
|
|
104
|
+
response read in full): that one has no raw stream left and is served from memory. Codings
|
|
105
|
+
are undone last-applied first. `identity` and codings httpx does not know pass through
|
|
106
|
+
unchanged, as they do in httpx. A br or zstd coding httpx would decode raises `CodingRefused`
|
|
107
|
+
on a success; an error body with one is read raw.
|
|
108
|
+
"""
|
|
109
|
+
if hasattr(response, "_content") or not capped:
|
|
110
|
+
# An uncapped body (a successful binary download) is the caller's to bound, so httpx
|
|
111
|
+
# decodes it as it would.
|
|
112
|
+
return None
|
|
113
|
+
codings = [coding.strip().lower() for coding in response.headers.get("content-encoding", "").split(",")]
|
|
114
|
+
if any(coding in HTTPX_ONLY_CODINGS and coding in httpx_decoders() for coding in codings):
|
|
115
|
+
# httpx inflates br and zstd a whole network read per call, which no limit can stop, and the
|
|
116
|
+
# SDK never asks for them (`Accept-Encoding: gzip, deflate`).
|
|
117
|
+
if not response.is_success:
|
|
118
|
+
# An error body is read for its message only: keep its raw bytes, so the status error
|
|
119
|
+
# (and its retry) still stands.
|
|
120
|
+
return cls([])
|
|
121
|
+
raise CodingRefused(
|
|
122
|
+
"A br or zstd content coding is not decoded for a buffered or streamed response; "
|
|
123
|
+
"the SDK accepts gzip and deflate"
|
|
124
|
+
)
|
|
125
|
+
return cls([Inflater(ZLIB_CODINGS[coding]) for coding in reversed(codings) if coding in ZLIB_CODINGS])
|
|
126
|
+
|
|
127
|
+
def decode(self, data: bytes) -> Iterator[bytes]:
|
|
128
|
+
"""Decodes one network read, yielding the body in bounded pieces."""
|
|
129
|
+
return self._push(0, data)
|
|
130
|
+
|
|
131
|
+
def flush(self) -> Iterator[bytes]:
|
|
132
|
+
"""Decodes what the layers still hold once the body has ended."""
|
|
133
|
+
for index, layer in enumerate(self._layers):
|
|
134
|
+
for piece in layer.flush():
|
|
135
|
+
yield from self._push(index + 1, piece)
|
|
136
|
+
|
|
137
|
+
def _push(self, index: int, data: bytes) -> Iterator[bytes]:
|
|
138
|
+
"""Runs `data` through the layers from `index` on."""
|
|
139
|
+
if index == len(self._layers):
|
|
140
|
+
yield data
|
|
141
|
+
return
|
|
142
|
+
for piece in self._layers[index].feed(data):
|
|
143
|
+
yield from self._push(index + 1, piece)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def decoding_error(response: httpx.Response, exc: zlib.error) -> httpx.DecodingError:
|
|
147
|
+
"""The error for a body that is not valid for its `Content-Encoding`, as httpx raises it."""
|
|
148
|
+
return httpx.DecodingError(f"Error decoding the response body: {exc}", request=response.request)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _stream_decoder(response: httpx.Response) -> BoundedDecoder | None:
|
|
152
|
+
"""The bounded decoder for a streamed body, reporting a br or zstd one as an `APIError`."""
|
|
153
|
+
try:
|
|
154
|
+
return BoundedDecoder.for_response(response, capped=True)
|
|
155
|
+
except CodingRefused as exc:
|
|
156
|
+
raise APIError(exc.message, response.request, body=None) from None
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def iter_decoded(response: httpx.Response) -> Iterator[bytes]:
|
|
160
|
+
"""A streamed body's bytes, decoded in bounded pieces as they arrive (SSE and JSON Lines read this)."""
|
|
161
|
+
decoder = _stream_decoder(response)
|
|
162
|
+
if decoder is None:
|
|
163
|
+
yield from response.iter_bytes()
|
|
164
|
+
return
|
|
165
|
+
try:
|
|
166
|
+
for raw in response.iter_raw():
|
|
167
|
+
yield from decoder.decode(raw)
|
|
168
|
+
yield from decoder.flush()
|
|
169
|
+
except zlib.error as exc:
|
|
170
|
+
raise decoding_error(response, exc) from exc
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
async def aiter_decoded(response: httpx.Response) -> AsyncIterator[bytes]:
|
|
174
|
+
"""The async twin of `iter_decoded`."""
|
|
175
|
+
decoder = _stream_decoder(response)
|
|
176
|
+
if decoder is None:
|
|
177
|
+
async for chunk in response.aiter_bytes():
|
|
178
|
+
yield chunk
|
|
179
|
+
return
|
|
180
|
+
try:
|
|
181
|
+
async for raw in response.aiter_raw():
|
|
182
|
+
for piece in decoder.decode(raw):
|
|
183
|
+
yield piece
|
|
184
|
+
for piece in decoder.flush():
|
|
185
|
+
yield piece
|
|
186
|
+
except zlib.error as exc:
|
|
187
|
+
raise decoding_error(response, exc) from exc
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# File generated from our OpenAPI spec by Scalar. See CONTRIBUTING.md for details.
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import threading
|
|
6
|
+
from typing import Any, Callable
|
|
7
|
+
|
|
8
|
+
EventHandler = Callable[..., Any]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class EventHandlerRegistry:
|
|
12
|
+
"""Thread-safe (optional) registry of event handlers."""
|
|
13
|
+
|
|
14
|
+
def __init__(self, *, use_lock: bool = False) -> None:
|
|
15
|
+
self._handlers: dict[str, list[EventHandler]] = {}
|
|
16
|
+
self._once_ids: set[int] = set()
|
|
17
|
+
self._lock: threading.Lock | None = threading.Lock() if use_lock else None
|
|
18
|
+
|
|
19
|
+
def _acquire(self) -> None:
|
|
20
|
+
if self._lock is not None:
|
|
21
|
+
self._lock.acquire()
|
|
22
|
+
|
|
23
|
+
def _release(self) -> None:
|
|
24
|
+
if self._lock is not None:
|
|
25
|
+
self._lock.release()
|
|
26
|
+
|
|
27
|
+
def add(self, event_type: str, handler: EventHandler, *, once: bool = False) -> None:
|
|
28
|
+
self._acquire()
|
|
29
|
+
try:
|
|
30
|
+
handlers = self._handlers.setdefault(event_type, [])
|
|
31
|
+
handlers.append(handler)
|
|
32
|
+
if once:
|
|
33
|
+
self._once_ids.add(id(handler))
|
|
34
|
+
finally:
|
|
35
|
+
self._release()
|
|
36
|
+
|
|
37
|
+
def remove(self, event_type: str, handler: EventHandler) -> None:
|
|
38
|
+
self._acquire()
|
|
39
|
+
try:
|
|
40
|
+
handlers = self._handlers.get(event_type)
|
|
41
|
+
if handlers is not None:
|
|
42
|
+
try:
|
|
43
|
+
handlers.remove(handler)
|
|
44
|
+
except ValueError:
|
|
45
|
+
pass
|
|
46
|
+
self._once_ids.discard(id(handler))
|
|
47
|
+
finally:
|
|
48
|
+
self._release()
|
|
49
|
+
|
|
50
|
+
def get_handlers(self, event_type: str) -> list[EventHandler]:
|
|
51
|
+
"""Return a snapshot of handlers for the given event type, removing once-handlers."""
|
|
52
|
+
self._acquire()
|
|
53
|
+
try:
|
|
54
|
+
handlers = self._handlers.get(event_type)
|
|
55
|
+
if not handlers:
|
|
56
|
+
return []
|
|
57
|
+
result = list(handlers)
|
|
58
|
+
to_remove = [h for h in result if id(h) in self._once_ids]
|
|
59
|
+
for h in to_remove:
|
|
60
|
+
handlers.remove(h)
|
|
61
|
+
self._once_ids.discard(id(h))
|
|
62
|
+
return result
|
|
63
|
+
finally:
|
|
64
|
+
self._release()
|
|
65
|
+
|
|
66
|
+
def has_handlers(self, event_type: str) -> bool:
|
|
67
|
+
self._acquire()
|
|
68
|
+
try:
|
|
69
|
+
handlers = self._handlers.get(event_type)
|
|
70
|
+
return bool(handlers)
|
|
71
|
+
finally:
|
|
72
|
+
self._release()
|
|
73
|
+
|
|
74
|
+
def merge_into(self, target: EventHandlerRegistry) -> None:
|
|
75
|
+
"""Move all handlers from this registry into *target*, then clear self."""
|
|
76
|
+
self._acquire()
|
|
77
|
+
try:
|
|
78
|
+
for event_type, handlers in self._handlers.items():
|
|
79
|
+
for handler in handlers:
|
|
80
|
+
once = id(handler) in self._once_ids
|
|
81
|
+
target.add(event_type, handler, once=once)
|
|
82
|
+
self._handlers.clear()
|
|
83
|
+
self._once_ids.clear()
|
|
84
|
+
finally:
|
|
85
|
+
self._release()
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
# File generated from our OpenAPI spec by Scalar. See CONTRIBUTING.md for details.
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing_extensions import Literal
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"BadRequestError",
|
|
11
|
+
"AuthenticationError",
|
|
12
|
+
"PermissionDeniedError",
|
|
13
|
+
"NotFoundError",
|
|
14
|
+
"ConflictError",
|
|
15
|
+
"UnprocessableEntityError",
|
|
16
|
+
"RateLimitError",
|
|
17
|
+
"InternalServerError",
|
|
18
|
+
"WebSocketConnectionClosedError",
|
|
19
|
+
"WebSocketQueueFullError",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class BrelliumClientError(Exception):
|
|
24
|
+
pass
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class APIError(BrelliumClientError):
|
|
28
|
+
message: str
|
|
29
|
+
request: httpx.Request
|
|
30
|
+
|
|
31
|
+
body: object | None
|
|
32
|
+
"""The API response body.
|
|
33
|
+
|
|
34
|
+
If the API responded with a valid JSON structure then this property will be the
|
|
35
|
+
decoded result.
|
|
36
|
+
|
|
37
|
+
If it isn't a valid JSON structure then this will be the raw response.
|
|
38
|
+
|
|
39
|
+
If there was no response associated with this error then it will be `None`.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __init__(self, message: str, request: httpx.Request, *, body: object | None) -> None: # noqa: ARG002
|
|
43
|
+
super().__init__(message)
|
|
44
|
+
self.request = request
|
|
45
|
+
self.message = message
|
|
46
|
+
self.body = body
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class APIResponseValidationError(APIError):
|
|
50
|
+
response: httpx.Response
|
|
51
|
+
status_code: int
|
|
52
|
+
|
|
53
|
+
def __init__(self, response: httpx.Response, body: object | None, *, message: str | None = None) -> None:
|
|
54
|
+
super().__init__(message or "Data returned by API invalid for expected schema.", response.request, body=body)
|
|
55
|
+
self.response = response
|
|
56
|
+
self.status_code = response.status_code
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class APIStatusError(APIError):
|
|
60
|
+
"""Raised when an API response has a status code of 4xx or 5xx."""
|
|
61
|
+
|
|
62
|
+
response: httpx.Response
|
|
63
|
+
status_code: int
|
|
64
|
+
|
|
65
|
+
def __init__(self, message: str, *, response: httpx.Response, body: object | None) -> None:
|
|
66
|
+
super().__init__(message, response.request, body=body)
|
|
67
|
+
self.response = response
|
|
68
|
+
self.status_code = response.status_code
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
class APIConnectionError(APIError):
|
|
72
|
+
def __init__(self, *, message: str = "Connection error.", request: httpx.Request) -> None:
|
|
73
|
+
super().__init__(message, request, body=None)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
class APITimeoutError(APIConnectionError):
|
|
77
|
+
def __init__(self, request: httpx.Request) -> None:
|
|
78
|
+
super().__init__(message="Request timed out.", request=request)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class BadRequestError(APIStatusError):
|
|
82
|
+
status_code: Literal[400] = 400 # pyright: ignore[reportIncompatibleVariableOverride]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
class AuthenticationError(APIStatusError):
|
|
86
|
+
status_code: Literal[401] = 401 # pyright: ignore[reportIncompatibleVariableOverride]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class PermissionDeniedError(APIStatusError):
|
|
90
|
+
status_code: Literal[403] = 403 # pyright: ignore[reportIncompatibleVariableOverride]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class NotFoundError(APIStatusError):
|
|
94
|
+
status_code: Literal[404] = 404 # pyright: ignore[reportIncompatibleVariableOverride]
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class ConflictError(APIStatusError):
|
|
98
|
+
status_code: Literal[409] = 409 # pyright: ignore[reportIncompatibleVariableOverride]
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
class UnprocessableEntityError(APIStatusError):
|
|
102
|
+
status_code: Literal[422] = 422 # pyright: ignore[reportIncompatibleVariableOverride]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class RateLimitError(APIStatusError):
|
|
106
|
+
status_code: Literal[429] = 429 # pyright: ignore[reportIncompatibleVariableOverride]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class InternalServerError(APIStatusError):
|
|
110
|
+
pass
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class WebSocketConnectionClosedError(BrelliumClientError):
|
|
114
|
+
"""Raised when a WebSocket connection closes with unsent messages."""
|
|
115
|
+
|
|
116
|
+
unsent_messages: list[str]
|
|
117
|
+
|
|
118
|
+
def __init__(self, message: str, *, unsent_messages: list[str]) -> None:
|
|
119
|
+
super().__init__(message)
|
|
120
|
+
self.unsent_messages = unsent_messages
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
class WebSocketQueueFullError(BrelliumClientError):
|
|
124
|
+
"""Raised when the outgoing WebSocket message queue exceeds its byte-size limit."""
|
|
125
|
+
|
|
126
|
+
pass
|