-
Notifications
You must be signed in to change notification settings - Fork 980
Expand file tree
/
Copy path__init__.py
More file actions
82 lines (62 loc) · 2.34 KB
/
Copy path__init__.py
File metadata and controls
82 lines (62 loc) · 2.34 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
import asyncio
import weakref
from typing import Dict, Optional, Tuple
from httpx._types import ProxyTypes
from e2b.api import (
_TCPKeepaliveAsyncHTTPTransport,
AsyncApiClient,
connection_retries,
limits,
)
from e2b.connection_config import ConnectionConfig
TransportKey = Tuple[bool, Optional[ProxyTypes]]
def get_api_client(config: ConnectionConfig, **kwargs) -> AsyncApiClient:
return AsyncApiClient(
config,
async_transport_factory=lambda: get_transport(config),
**kwargs,
)
class AsyncTransportWithLogger(_TCPKeepaliveAsyncHTTPTransport):
# Keyed weakly by the event loop object itself, not id(loop) — CPython
# reuses object ids, so a new loop could otherwise inherit a transport
# bound to a previous, closed loop.
_instances: weakref.WeakKeyDictionary[
asyncio.AbstractEventLoop,
Dict[TransportKey, "AsyncTransportWithLogger"],
] = weakref.WeakKeyDictionary()
@property
def pool(self):
return self._pool
def _create_transport(cls, config: ConnectionConfig, http2: bool):
"""Build a keepalive transport of the given class for this config."""
return cls(
limits=limits,
proxy=config.proxy,
http2=http2,
retries=connection_retries,
)
def _get_cached_transport(cls, config: ConnectionConfig, http2: bool):
loop = asyncio.get_running_loop()
loop_instances = cls._instances.get(loop)
if loop_instances is None:
loop_instances = {}
cls._instances[loop] = loop_instances
key: TransportKey = (http2, config.proxy)
transport = loop_instances.get(key)
if transport is None:
transport = _create_transport(cls, config, http2)
loop_instances[key] = transport
return transport
def get_transport(
config: ConnectionConfig, http2: bool = True
) -> AsyncTransportWithLogger:
return _get_cached_transport(AsyncTransportWithLogger, config, http2)
class AsyncEnvdTransportWithLogger(AsyncTransportWithLogger):
_instances: weakref.WeakKeyDictionary[
asyncio.AbstractEventLoop,
Dict[TransportKey, "AsyncEnvdTransportWithLogger"],
] = weakref.WeakKeyDictionary()
def get_envd_transport(
config: ConnectionConfig, http2: bool = True
) -> AsyncEnvdTransportWithLogger:
return _get_cached_transport(AsyncEnvdTransportWithLogger, config, http2)