-
Notifications
You must be signed in to change notification settings - Fork 980
Expand file tree
/
Copy path__init__.py
More file actions
295 lines (238 loc) · 10.4 KB
/
Copy path__init__.py
File metadata and controls
295 lines (238 loc) · 10.4 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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
import json
import logging
import os
import re
from dataclasses import dataclass
from types import TracebackType
from typing import NamedTuple, Optional, Protocol, Tuple, Union
import httpx
from httpx import AsyncBaseTransport, BaseTransport, Limits, Timeout
from pyqwest import Proxy
from e2b.api.client.client import AuthenticatedClient
from e2b.api.client.types import Response
from e2b.api.metadata import default_headers
from e2b.connection_config import ConnectionConfig, ProxyTypes
from e2b.exceptions import (
AuthenticationException,
InvalidArgumentException,
RateLimitException,
SandboxException,
)
def make_logging_event_hooks(log: Optional[logging.Logger]) -> dict:
"""Build synchronous httpx ``event_hooks`` that log requests and responses
to the given ``logging.Logger``. Requests log at ``INFO``, successful
responses at ``INFO`` and responses with status >= 400 at ``ERROR``.
Returns no hooks when ``log`` is ``None`` so that nothing is logged unless a
logger was explicitly supplied."""
if log is None:
return {}
def on_request(request) -> None:
log.info(f"Request {request.method} {request.url}")
def on_response(response: Response) -> None:
if response.status_code >= 400:
log.error(f"Response {response.status_code}")
else:
log.info(f"Response {response.status_code}")
return {"request": [on_request], "response": [on_response]}
def make_async_logging_event_hooks(log: Optional[logging.Logger]) -> dict:
"""Asynchronous counterpart of :func:`make_logging_event_hooks`."""
if log is None:
return {}
async def on_request(request) -> None:
log.info(f"Request {request.method} {request.url}")
async def on_response(response: Response) -> None:
if response.status_code >= 400:
log.error(f"Response {response.status_code}")
else:
log.info(f"Response {response.status_code}")
return {"request": [on_request], "response": [on_response]}
limits = Limits(
max_keepalive_connections=int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS") or "20"),
max_connections=int(os.getenv("E2B_MAX_CONNECTIONS") or "2000"),
keepalive_expiry=int(os.getenv("E2B_KEEPALIVE_EXPIRY") or "300"),
)
connection_retries = int(os.getenv("E2B_CONNECTION_RETRIES") or "3")
# Mirror the httpx pool tuning above with pyqwest's equivalents, shared by
# the REST API and envd RPC transports. `pool_max_idle_per_host` is per host
# rather than httpx's global idle cap, which suits both: API traffic goes to
# a single host and each sandbox is its own host. reqwest has no counterpart
# to `E2B_MAX_CONNECTIONS` (it does not cap concurrent connections).
pool_idle_timeout = float(os.getenv("E2B_KEEPALIVE_EXPIRY") or "300")
pool_max_idle_per_host = int(os.getenv("E2B_MAX_KEEPALIVE_CONNECTIONS") or "20")
class ProxyConfig(NamedTuple):
"""The ``proxy`` connection option in the shape pyqwest transports take.
A tuple so it can key the transport caches directly: it is hashable and
compares by value, where a ``pyqwest.Proxy`` compares by identity and
would hand every call its own connection pool."""
url: str
auth: Optional[Tuple[str, str]] = None
headers: Tuple[Tuple[str, str], ...] = ()
def to_pyqwest(self) -> Proxy:
"""The ``pyqwest.Proxy`` to hand a transport."""
return Proxy(self.url, auth=self.auth, headers=self.headers or None)
def proxy_to_config(proxy: Optional[ProxyTypes]) -> Optional[ProxyConfig]:
"""Convert the ``proxy`` connection option — a URL string, an
``httpx.URL``, or an ``httpx.Proxy`` — to the proxy configuration pyqwest
transports take: a proxy URL (scheme http, https, socks5, or socks5h,
credentials allowed in the userinfo), basic-auth credentials, and headers
to send to the proxy. An ``httpx.Proxy`` ``ssl_context`` has no pyqwest
counterpart and is rejected rather than silently dropped."""
if proxy is None:
return None
if isinstance(proxy, str):
return ProxyConfig(proxy)
if isinstance(proxy, httpx.URL):
return ProxyConfig(str(proxy))
if isinstance(proxy, httpx.Proxy):
if proxy.ssl_context is not None:
raise InvalidArgumentException("httpx.Proxy ssl_context is not supported")
# httpx.Proxy splits userinfo out of the URL into `.auth`; pyqwest
# takes the credentials the same way, so they pass straight through.
return ProxyConfig(
str(proxy.url),
auth=proxy.auth,
headers=tuple(proxy.headers.items()),
)
raise InvalidArgumentException(
"Only URL-string, httpx.URL, and httpx.Proxy proxies are supported, "
'e.g. proxy="http://user:pass@localhost:8030"'
)
@dataclass
class SandboxCreateResponse:
sandbox_id: str
sandbox_domain: Optional[str]
envd_version: str
envd_access_token: Optional[str]
traffic_access_token: Optional[str]
def api_exception_from_code(
status_code: int,
message: Optional[str] = None,
default_exception_class: type[Exception] = SandboxException,
stack_trace: Optional[TracebackType] = None,
) -> Exception:
"""Map an API error code and message to the matching exception class — the
same mapping :func:`handle_api_exception` applies to HTTP responses, usable
for error objects embedded in response bodies (e.g. per-fork results)."""
if status_code == 401:
text = f"{status_code}: Unauthorized, please check your credentials."
if message:
text += f" - {message}"
return AuthenticationException(text)
if status_code == 429:
text = f"{status_code}: Rate limit exceeded, please try again later."
if message:
text += f" - {message}"
return RateLimitException(text)
return default_exception_class(f"{status_code}: {message}").with_traceback(
stack_trace
)
def handle_api_exception(
e: "SupportsApiErrorResponse",
default_exception_class: type[Exception] = SandboxException,
stack_trace: Optional[TracebackType] = None,
):
try:
body = json.loads(e.content) if e.content else {}
except json.JSONDecodeError:
body = {}
message = body["message"] if "message" in body else None
if message is None and e.status_code not in (401, 429):
return default_exception_class(f"{e.status_code}: {e.content}").with_traceback(
stack_trace
)
return api_exception_from_code(
e.status_code, message, default_exception_class, stack_trace
)
class SupportsApiErrorResponse(Protocol):
@property
def status_code(self) -> int: ...
@property
def content(self) -> Union[str, bytes]: ...
_API_KEY_PATTERN = re.compile(r"\Ae2b_[0-9a-f]+\Z")
_API_KEY_EXAMPLE = "e2b_" + "0" * 40
def validate_api_key(api_key: str) -> None:
"""Validate that an E2B API key has the expected ``e2b_`` prefix
followed by hex characters. Raises ``AuthenticationException`` otherwise.
"""
if not _API_KEY_PATTERN.match(api_key):
raise AuthenticationException(
'Invalid API key format: expected "e2b_" followed by hex '
f'characters (e.g. "{_API_KEY_EXAMPLE}"). '
"Visit the API Keys tab at https://e2b.dev/dashboard?tab=keys to get your API key."
)
class ApiClient(AuthenticatedClient):
"""
The client for interacting with the E2B API.
A single lazily-created httpx client (see the generated
``AuthenticatedClient``) serves all threads and event loops: the pyqwest
transports it delegates to are thread-safe and loop-independent, and
``httpx.Client`` is documented thread-safe.
"""
def __init__(
self,
config: ConnectionConfig,
transport: Optional[Union[BaseTransport, AsyncBaseTransport]] = None,
*args,
**kwargs,
):
self._proxy = config.proxy
if config.api_key is None:
raise AuthenticationException(
"API key is required, please visit the API Keys tab at https://e2b.dev/dashboard?tab=keys to get your API key. "
"You can either set the environment variable `E2B_API_KEY` "
'or you can pass it directly to the method like api_key="e2b_..."',
)
if config.api_key is not None and config.validate_api_key:
validate_api_key(config.api_key)
token = config.api_key
auth_header_name = "X-API-KEY"
prefix = ""
self._logger = config.logger
headers = {
**default_headers,
# Deprecated: send the access token alongside the API key when one
# is available, mirroring the JS SDK. Prefer `api_headers` instead.
# Spread before `config.headers` so a custom `Authorization` in
# `api_headers` wins over the deprecated access token, matching JS.
**(
{"Authorization": f"Bearer {config.access_token}"}
if config.access_token is not None
else {}
),
**(config.headers or {}),
}
# Prevent passing these parameters twice
more_headers: Optional[dict] = kwargs.pop("headers", None)
if more_headers:
headers.update(more_headers)
kwargs.pop("token", None)
kwargs.pop("auth_header_name", None)
kwargs.pop("prefix", None)
httpx_args = {
"event_hooks": self._logging_event_hooks(),
}
if transport is not None:
# The proxy lives in the transport; passing `proxy` here too
# would mount a fresh, never-closed proxy transport per client.
httpx_args["transport"] = transport
else:
httpx_args["proxy"] = config.proxy
# config.request_timeout is None when the timeout is explicitly
# disabled (request_timeout=0), which httpx.Timeout(None) preserves.
kwargs.setdefault("timeout", Timeout(config.request_timeout))
super().__init__(
base_url=config.api_url,
httpx_args=httpx_args,
headers=headers,
token=token or "",
auth_header_name=auth_header_name,
prefix=prefix,
*args,
**kwargs,
)
def _logging_event_hooks(self) -> dict:
return make_logging_event_hooks(self._logger)
# We need to override the logging hooks for the async usage
class AsyncApiClient(ApiClient):
def _logging_event_hooks(self) -> dict:
return make_async_logging_event_hooks(self._logger)