File size: 8,289 Bytes
097eaf0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import asyncio
import httpx
from typing import Optional, Dict, Any
from .get_version import get_version

version = get_version()


class AsyncHttpClient:
    def __init__(
        self,
        api_key: Optional[str],
        api_url: str,
        timeout: Optional[float] = None,
        max_retries: int = 3,
        backoff_factor: float = 0.5,
    ):
        self.api_key = api_key
        self.api_url = api_url
        self.timeout = timeout
        self.max_retries = max_retries
        self.backoff_factor = backoff_factor

        headers = {}

        if api_key:
            headers["Authorization"] = f"Bearer {api_key}"

        self._client = httpx.AsyncClient(
            base_url=api_url,
            headers=headers,
            limits=httpx.Limits(max_keepalive_connections=0),
        )

    async def close(self) -> None:
        await self._client.aclose()

    def _headers(self, idempotency_key: Optional[str] = None) -> Dict[str, str]:
        headers: Dict[str, str] = {}
        if idempotency_key:
            headers["x-idempotency-key"] = idempotency_key
        return headers

    async def post(
        self,
        endpoint: str,
        data: Dict[str, Any],
        headers: Optional[Dict[str, str]] = None,
        timeout: Optional[float] = None,
        retries: Optional[int] = None,
        backoff_factor: Optional[float] = None,
    ) -> httpx.Response:
        if timeout is None:
            timeout = self.timeout
        if retries is None:
            retries = self.max_retries
        if backoff_factor is None:
            backoff_factor = self.backoff_factor

        payload = dict(data)
        payload["origin"] = f"python-sdk@{version}"

        last_exception = None
        num_attempts = max(1, retries)

        for attempt in range(num_attempts):
            try:
                response = await self._client.post(
                    endpoint,
                    json=payload,
                    headers={**self._headers(), **(headers or {})},
                    timeout=timeout,
                )
                if response.status_code == 502:
                    if attempt < num_attempts - 1:
                        await asyncio.sleep(backoff_factor * (2 ** attempt))
                        continue
                return response
            except httpx.HTTPError as e:
                last_exception = e
                if attempt == num_attempts - 1:
                    raise e
                await asyncio.sleep(backoff_factor * (2 ** attempt))

        raise last_exception or Exception("Unexpected error in POST request")

    async def post_multipart(
        self,
        endpoint: str,
        data: Dict[str, Any],
        files: Dict[str, Any],
        headers: Optional[Dict[str, str]] = None,
        timeout: Optional[float] = None,
        retries: Optional[int] = None,
        backoff_factor: Optional[float] = None,
    ) -> httpx.Response:
        if timeout is None:
            timeout = self.timeout
        if retries is None:
            retries = self.max_retries
        if backoff_factor is None:
            backoff_factor = self.backoff_factor

        last_exception = None
        num_attempts = max(1, retries)

        for attempt in range(num_attempts):
            try:
                response = await self._client.post(
                    endpoint,
                    data=data,
                    files=files,
                    headers={**self._headers(), **(headers or {})},
                    timeout=timeout,
                )
                if response.status_code == 502:
                    if attempt < num_attempts - 1:
                        await asyncio.sleep(backoff_factor * (2 ** attempt))
                        continue
                return response
            except httpx.HTTPError as e:
                last_exception = e
                if attempt == num_attempts - 1:
                    raise e
                await asyncio.sleep(backoff_factor * (2 ** attempt))

        raise last_exception or Exception("Unexpected error in multipart POST request")

    async def get(
        self,
        endpoint: str,
        headers: Optional[Dict[str, str]] = None,
        timeout: Optional[float] = None,
        retries: Optional[int] = None,
        backoff_factor: Optional[float] = None,
    ) -> httpx.Response:
        if timeout is None:
            timeout = self.timeout
        if retries is None:
            retries = self.max_retries
        if backoff_factor is None:
            backoff_factor = self.backoff_factor

        last_exception = None
        num_attempts = max(1, retries)

        for attempt in range(num_attempts):
            try:
                response = await self._client.get(
                    endpoint,
                    headers={**self._headers(), **(headers or {})},
                    timeout=timeout,
                )
                if response.status_code == 502:
                    if attempt < num_attempts - 1:
                        await asyncio.sleep(backoff_factor * (2 ** attempt))
                        continue
                return response
            except httpx.HTTPError as e:
                last_exception = e
                if attempt == num_attempts - 1:
                    raise e
                await asyncio.sleep(backoff_factor * (2 ** attempt))

        raise last_exception or Exception("Unexpected error in GET request")

    async def delete(
        self,
        endpoint: str,
        headers: Optional[Dict[str, str]] = None,
        timeout: Optional[float] = None,
        retries: Optional[int] = None,
        backoff_factor: Optional[float] = None,
    ) -> httpx.Response:
        if timeout is None:
            timeout = self.timeout
        if retries is None:
            retries = self.max_retries
        if backoff_factor is None:
            backoff_factor = self.backoff_factor

        last_exception = None
        num_attempts = max(1, retries)

        for attempt in range(num_attempts):
            try:
                response = await self._client.delete(
                    endpoint,
                    headers={**self._headers(), **(headers or {})},
                    timeout=timeout,
                )
                if response.status_code == 502:
                    if attempt < num_attempts - 1:
                        await asyncio.sleep(backoff_factor * (2 ** attempt))
                        continue
                return response
            except httpx.HTTPError as e:
                last_exception = e
                if attempt == num_attempts - 1:
                    raise e
                await asyncio.sleep(backoff_factor * (2 ** attempt))

        raise last_exception or Exception("Unexpected error in DELETE request")

    async def patch(
        self,
        endpoint: str,
        data: Dict[str, Any],
        headers: Optional[Dict[str, str]] = None,
        timeout: Optional[float] = None,
        retries: Optional[int] = None,
        backoff_factor: Optional[float] = None,
    ) -> httpx.Response:
        if timeout is None:
            timeout = self.timeout
        if retries is None:
            retries = self.max_retries
        if backoff_factor is None:
            backoff_factor = self.backoff_factor

        payload = dict(data)
        payload["origin"] = f"python-sdk@{version}"

        last_exception = None
        num_attempts = max(1, retries)

        for attempt in range(num_attempts):
            try:
                response = await self._client.patch(
                    endpoint,
                    json=payload,
                    headers={**self._headers(), **(headers or {})},
                    timeout=timeout,
                )
                if response.status_code == 502 and attempt < num_attempts - 1:
                    await asyncio.sleep(backoff_factor * (2 ** attempt))
                    continue
                return response
            except httpx.HTTPError as e:
                last_exception = e
                if attempt == num_attempts - 1:
                    raise e
                await asyncio.sleep(backoff_factor * (2 ** attempt))

        raise last_exception or Exception("Unexpected error in PATCH request")