Skip to content

armgit / E2B

Public Imported from GitHub
0

Open-source, secure environment with real-world tools for enterprise-grade agents.

Fix volume SDK issues: transports, timeouts, empty files, eager stream errors (#1431)

Mish Ushakov0b0c728fe8a6
diff --git a/.changeset/great-pears-search.md b/.changeset/great-pears-search.md
new file mode 100644
index 000000000..d116ff372
--- /dev/null
+++ b/.changeset/great-pears-search.md
@@ -0,0 +1,10 @@
+---
+"@e2b/python-sdk": patch
+---
+
+Fix several issues in the volume content API client:
+
+- `AsyncVolume` HTTP transports are now cached per event loop (and per proxy) instead of a process-wide singleton, and sync transports are cached per thread.
+- Volume metadata operations (`list`, `make_dir`, `get_info`, `update_metadata`, `remove`) now respect `request_timeout` (60s by default) instead of running with httpx timeouts disabled.
+- Volume content auth no longer falls back to the `E2B_ACCESS_TOKEN` environment variable; it requires the volume token, matching the JS SDK.
+- `VolumeConnectionConfig` no longer mutates the caller's `headers` dict.
diff --git a/.changeset/heavy-pots-repair.md b/.changeset/heavy-pots-repair.md
new file mode 100644
index 000000000..cf322ff3d
--- /dev/null
+++ b/.changeset/heavy-pots-repair.md
@@ -0,0 +1,5 @@
+---
+"e2b": patch
+---
+
+Fix `Volume.readFile` returning `undefined` instead of an empty `Blob`/`ReadableStream` for empty files, and apply the documented 60s default request timeout to volume content requests.
diff --git a/packages/js-sdk/src/volume/client.ts b/packages/js-sdk/src/volume/client.ts
index 21bd4b361..d63057b59 100644
--- a/packages/js-sdk/src/volume/client.ts
+++ b/packages/js-sdk/src/volume/client.ts
@@ -7,6 +7,7 @@ import { buildRequestSignal } from '../connectionConfig'
import { createApiLogger, Logger } from '../logs'
import type { Volume } from './index'
+const REQUEST_TIMEOUT_MS = 60_000 // 60 seconds
const FILE_TIMEOUT_MS = 3_600_000 // 1 hour
export interface VolumeApiOpts {
@@ -72,7 +73,7 @@ export class VolumeConnectionConfig {
readonly token?: string
readonly headers?: Record<string, string>
readonly logger?: Logger
- readonly requestTimeoutMs?: number
+ readonly requestTimeoutMs: number
readonly signal?: AbortSignal
readonly proxy?: string
@@ -86,7 +87,7 @@ export class VolumeConnectionConfig {
this.token = opts?.token || volume.token
this.headers = opts?.headers
this.logger = opts?.logger
- this.requestTimeoutMs = opts?.requestTimeoutMs
+ this.requestTimeoutMs = opts?.requestTimeoutMs ?? REQUEST_TIMEOUT_MS
this.signal = opts?.signal
this.proxy = opts?.proxy || volume.proxy
}
diff --git a/packages/js-sdk/src/volume/index.ts b/packages/js-sdk/src/volume/index.ts
index bb655b1c6..7a09e74ec 100644
--- a/packages/js-sdk/src/volume/index.ts
+++ b/packages/js-sdk/src/volume/index.ts
@@ -561,19 +561,22 @@ export class Volume {
throw err
}
+ // When the file is empty, `res.data` is `undefined`, so empty values are synthesized below.
if (format === 'bytes') {
- return new Uint8Array(res.data as ArrayBuffer)
+ return res.data instanceof ArrayBuffer
+ ? new Uint8Array(res.data)
+ : new Uint8Array()
}
if (format === 'text') {
- // When the file is empty, res.data is parsed as `{}`. This is a workaround to return an empty string.
- if (res.response.headers.get('content-length') === '0') {
- return ''
- }
return typeof res.data === 'string' ? res.data : ''
}
- return res.data
+ if (format === 'blob') {
+ return res.data instanceof Blob ? res.data : new Blob([])
+ }
+
+ return res.data instanceof ReadableStream ? res.data : new Blob([]).stream()
}
/**
diff --git a/packages/js-sdk/tests/volume/volume.test.ts b/packages/js-sdk/tests/volume/volume.test.ts
index b69290953..ff1d2f251 100644
--- a/packages/js-sdk/tests/volume/volume.test.ts
+++ b/packages/js-sdk/tests/volume/volume.test.ts
@@ -13,6 +13,9 @@ const volumes = new Map<
{ volumeID: string; name: string; token: string }
>()
+// In-memory store for mock volume file contents, keyed by path
+const volumeFiles = new Map<string, string>()
+
const restHandlers = [
// POST /volumes - create (returns VolumeAndToken)
http.post(apiUrl('/volumes'), async ({ request }) => {
@@ -58,6 +61,22 @@ const restHandlers = [
return new HttpResponse(null, { status: 204 })
}
),
+
+ // GET /volumecontent/:volumeID/file - read file content
+ http.get(apiUrl('/volumecontent/:volumeID/file'), ({ request }) => {
+ const path = new URL(request.url).searchParams.get('path') ?? ''
+ const content = volumeFiles.get(path)
+ if (content === undefined) {
+ return HttpResponse.json(
+ { code: 404, message: 'Not found' },
+ { status: 404 }
+ )
+ }
+ return new HttpResponse(content.length > 0 ? content : null, {
+ status: 200,
+ headers: { 'Content-Length': String(content.length) },
+ })
+ }),
]
const server = setupServer(...restHandlers)
@@ -67,6 +86,7 @@ afterAll(() => server.close())
afterEach(() => {
server.resetHandlers()
volumes.clear()
+ volumeFiles.clear()
})
describe('Volume CRUD', () => {
@@ -187,3 +207,84 @@ describe('Volume CRUD', () => {
expect(listAfter).toHaveLength(0)
})
})
+
+describe('Volume content readFile', () => {
+ it('should return content for a non-empty file in every format', async () => {
+ volumeFiles.set('hello.txt', 'hello world')
+ const vol = await Volume.create('content-volume')
+
+ const text = await vol.readFile('hello.txt')
+ expect(text).toBe('hello world')
+
+ const bytes = await vol.readFile('hello.txt', { format: 'bytes' })
+ expect(bytes).toBeInstanceOf(Uint8Array)
+ expect(new TextDecoder().decode(bytes)).toBe('hello world')
+
+ const blob = await vol.readFile('hello.txt', { format: 'blob' })
+ expect(blob).toBeInstanceOf(Blob)
+ expect(await blob.text()).toBe('hello world')
+
+ const stream = await vol.readFile('hello.txt', { format: 'stream' })
+ expect(stream).toBeInstanceOf(ReadableStream)
+ expect(await new Response(stream).text()).toBe('hello world')
+ })
+
+ it('should return empty values for an empty file in every format', async () => {
+ volumeFiles.set('empty.txt', '')
+ const vol = await Volume.create('content-volume')
+
+ const text = await vol.readFile('empty.txt')
+ expect(text).toBe('')
+
+ const bytes = await vol.readFile('empty.txt', { format: 'bytes' })
+ expect(bytes).toBeInstanceOf(Uint8Array)
+ expect(bytes.length).toBe(0)
+
+ const blob = await vol.readFile('empty.txt', { format: 'blob' })
+ expect(blob).toBeInstanceOf(Blob)
+ expect(blob.size).toBe(0)
+
+ const stream = await vol.readFile('empty.txt', { format: 'stream' })
+ expect(stream).toBeInstanceOf(ReadableStream)
+ expect(await new Response(stream).text()).toBe('')
+ })
+
+ it('should throw NotFoundError for a missing file', async () => {
+ const vol = await Volume.create('content-volume')
+
+ await expect(vol.readFile('missing.txt')).rejects.toThrow(NotFoundError)
+ })
+
+ it('should reject at call time for a missing file with stream format', async () => {
+ const vol = await Volume.create('content-volume')
+
+ await expect(
+ vol.readFile('missing.txt', { format: 'stream' })
+ ).rejects.toThrow(NotFoundError)
+ })
+})
+
+describe('VolumeConnectionConfig request timeout', () => {
+ it('should default the request timeout to 60 seconds', async () => {
+ const vol = await Volume.create('timeout-volume')
+
+ const config = new VolumeConnectionConfig(vol)
+ expect(config.requestTimeoutMs).toBe(60_000)
+ expect(config.getSignal()).toBeInstanceOf(AbortSignal)
+ })
+
+ it('should let a per-call timeout override the default', async () => {
+ const vol = await Volume.create('timeout-volume')
+
+ const config = new VolumeConnectionConfig(vol, { requestTimeoutMs: 1_000 })
+ expect(config.requestTimeoutMs).toBe(1_000)
+ })
+
+ it('should disable the timeout when requestTimeoutMs is 0', async () => {
+ const vol = await Volume.create('timeout-volume')
+
+ const config = new VolumeConnectionConfig(vol, { requestTimeoutMs: 0 })
+ expect(config.requestTimeoutMs).toBe(0)
+ expect(config.getSignal()).toBeUndefined()
+ })
+})
diff --git a/packages/python-sdk/e2b/volume/client_async/__init__.py b/packages/python-sdk/e2b/volume/client_async/__init__.py
index f1e44a8a3..98ec19fd4 100644
--- a/packages/python-sdk/e2b/volume/client_async/__init__.py
+++ b/packages/python-sdk/e2b/volume/client_async/__init__.py
@@ -1,9 +1,11 @@
+import asyncio
import logging
import os
-from typing import Optional
+from typing import Dict, Optional, Tuple
import httpx
from httpx import Limits
+from httpx._types import ProxyTypes
from e2b.api.metadata import default_headers
from e2b.exceptions import AuthenticationException
@@ -18,12 +20,15 @@ limits = Limits(
keepalive_expiry=int(os.getenv("E2B_KEEPALIVE_EXPIRY", "300")),
)
+TransportKey = Tuple[int, Optional[ProxyTypes]]
+
def get_api_client(config: VolumeConnectionConfig, **kwargs) -> AsyncVolumeApiClient:
if config.access_token is None:
raise AuthenticationException(
- "Access token is required for volume operations. "
- "Set `E2B_ACCESS_TOKEN` or pass `token` in options.",
+ "Volume token is required for volume content operations. "
+ "Use `AsyncVolume.create`/`AsyncVolume.connect` to obtain it "
+ "or pass `token` in options.",
)
headers = {
@@ -31,19 +36,24 @@ def get_api_client(config: VolumeConnectionConfig, **kwargs) -> AsyncVolumeApiCl
**(config.headers or {}),
}
+ request_timeout = config.request_timeout
+
return AsyncVolumeApiClient(
base_url=config.api_url,
token=config.access_token,
auth_header_name="Authorization",
prefix="Bearer",
headers=headers,
+ timeout=(
+ httpx.Timeout(request_timeout) if request_timeout is not None else None
+ ),
httpx_args={"proxy": config.proxy, "transport": get_transport(config)},
**kwargs,
)
class AsyncTransportWithLogger(httpx.AsyncHTTPTransport):
- singleton: Optional["AsyncTransportWithLogger"] = None
+ _instances: Dict[TransportKey, "AsyncTransportWithLogger"] = {}
async def handle_async_request(self, request):
url = f"{request.url.scheme}://{request.url.host}{request.url.path}"
@@ -58,12 +68,14 @@ class AsyncTransportWithLogger(httpx.AsyncHTTPTransport):
def get_transport(config: VolumeConnectionConfig) -> AsyncTransportWithLogger:
- if AsyncTransportWithLogger.singleton is not None:
- return AsyncTransportWithLogger.singleton
+ key: TransportKey = (id(asyncio.get_running_loop()), config.proxy)
+
+ if key in AsyncTransportWithLogger._instances:
+ return AsyncTransportWithLogger._instances[key]
transport = AsyncTransportWithLogger(
limits=limits,
proxy=config.proxy,
)
- AsyncTransportWithLogger.singleton = transport
+ AsyncTransportWithLogger._instances[key] = transport
return transport
diff --git a/packages/python-sdk/e2b/volume/client_sync/__init__.py b/packages/python-sdk/e2b/volume/client_sync/__init__.py
index 5afdcfef2..8659f7083 100644
--- a/packages/python-sdk/e2b/volume/client_sync/__init__.py
+++ b/packages/python-sdk/e2b/volume/client_sync/__init__.py
@@ -1,9 +1,11 @@
import logging
import os
-from typing import Optional
+import threading
+from typing import Dict, Optional
import httpx
from httpx import Limits
+from httpx._types import ProxyTypes
from e2b.api.metadata import default_headers
from e2b.exceptions import AuthenticationException
@@ -18,12 +20,15 @@ limits = Limits(
keepalive_expiry=int(os.getenv("E2B_KEEPALIVE_EXPIRY", "300")),
)
+TransportKey = Optional[ProxyTypes]
+
def get_api_client(config: VolumeConnectionConfig, **kwargs) -> VolumeApiClient:
if config.access_token is None:
raise AuthenticationException(
- "Access token is required for volume operations. "
- "Set `E2B_ACCESS_TOKEN` or pass `token` in options.",
+ "Volume token is required for volume content operations. "
+ "Use `Volume.create`/`Volume.connect` to obtain it "
+ "or pass `token` in options.",
)
headers = {
@@ -31,19 +36,24 @@ def get_api_client(config: VolumeConnectionConfig, **kwargs) -> VolumeApiClient:
**(config.headers or {}),
}
+ request_timeout = config.request_timeout
+
return VolumeApiClient(
base_url=config.api_url,
token=config.access_token,
auth_header_name="Authorization",
prefix="Bearer",
headers=headers,
+ timeout=(
+ httpx.Timeout(request_timeout) if request_timeout is not None else None
+ ),
httpx_args={"proxy": config.proxy, "transport": get_transport(config)},
**kwargs,
)
class TransportWithLogger(httpx.HTTPTransport):
- singleton: Optional["TransportWithLogger"] = None
+ _thread_local = threading.local()
def handle_request(self, request):
url = f"{request.url.scheme}://{request.url.host}{request.url.path}"
@@ -58,12 +68,18 @@ class TransportWithLogger(httpx.HTTPTransport):
def get_transport(config: VolumeConnectionConfig) -> TransportWithLogger:
- if TransportWithLogger.singleton is not None:
- return TransportWithLogger.singleton
+ instances: Dict[TransportKey, TransportWithLogger] = getattr(
+ TransportWithLogger._thread_local, "instances", {}
+ )
+ key: TransportKey = config.proxy
+ cached = instances.get(key)
+ if cached is not None:
+ return cached
transport = TransportWithLogger(
limits=limits,
proxy=config.proxy,
)
- TransportWithLogger.singleton = transport
+ instances[key] = transport
+ TransportWithLogger._thread_local.instances = instances
return transport
diff --git a/packages/python-sdk/e2b/volume/connection_config.py b/packages/python-sdk/e2b/volume/connection_config.py
index f5a0b4aec..4fc95367e 100644
--- a/packages/python-sdk/e2b/volume/connection_config.py
+++ b/packages/python-sdk/e2b/volume/connection_config.py
@@ -57,10 +57,6 @@ class VolumeConnectionConfig:
def _volume_api_url():
return os.getenv("E2B_VOLUME_API_URL")
- @staticmethod
- def _access_token():
- return os.getenv("E2B_ACCESS_TOKEN")
-
@staticmethod
def _get_request_timeout(
default_timeout: Optional[float],
@@ -91,11 +87,11 @@ class VolumeConnectionConfig:
or self._volume_api_url()
or ("http://localhost:8080" if self.debug else f"https://api.{self.domain}")
)
- self.access_token = token or self._access_token()
+ self.access_token = token
self.token = self.access_token
self.proxy = proxy
- self.headers = headers or {}
+ self.headers = dict(headers) if headers else {}
self.headers["User-Agent"] = f"e2b-python-sdk/{package_version}"
self.request_timeout = self._get_request_timeout(
diff --git a/packages/python-sdk/tests/async/volume_async/test_volume_content.py b/packages/python-sdk/tests/async/volume_async/test_volume_content.py
new file mode 100644
index 000000000..c306bb8c9
--- /dev/null
+++ b/packages/python-sdk/tests/async/volume_async/test_volume_content.py
@@ -0,0 +1,70 @@
+import httpx
+import pytest
+
+from e2b import AsyncVolume
+from e2b.exceptions import NotFoundException
+import e2b.volume.volume_async as volume_async_mod
+
+_files = {
+ "hello.txt": b"hello world",
+ "empty.txt": b"",
+}
+
+
+def _handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.params.get("path")
+ content = _files.get(path)
+ if content is None:
+ return httpx.Response(404)
+ return httpx.Response(200, content=content)
+
+
+def volume(monkeypatch) -> AsyncVolume:
+ real_get_api_client = volume_async_mod.get_volume_api_client
+
+ def mock_get_api_client(config, **kwargs):
+ client = real_get_api_client(config, **kwargs)
+ client.set_async_httpx_client(
+ httpx.AsyncClient(
+ base_url=config.api_url,
+ transport=httpx.MockTransport(_handler),
+ )
+ )
+ return client
+
+ monkeypatch.setattr(volume_async_mod, "get_volume_api_client", mock_get_api_client)
+ return AsyncVolume(volume_id="vol-1", name="test-volume", token="vol-token")
+
+
+async def test_read_file_stream_yields_content(volume: AsyncVolume):
+ stream = await volume.read_file("hello.txt", format="stream")
+ chunks = [chunk async for chunk in stream]
+ assert b"".join(chunks) == b"hello world"
+
+
+async def test_read_file_stream_raises_for_missing_path(volume: AsyncVolume):
+ with pytest.raises(NotFoundException):
+ async for _ in await volume.read_file("missing.txt", format="stream"):
+ pass
+
+
+async def test_read_file_stream_of_empty_file(volume: AsyncVolume):
+ stream = await volume.read_file("empty.txt", format="stream")
+ chunks = [chunk async for chunk in stream]
+ assert b"".join(chunks) == b""
+
+
+async def test_read_file_text_and_bytes(volume: AsyncVolume):
+ assert await volume.read_file("hello.txt") == "hello world"
+ assert await volume.read_file("hello.txt", format="bytes") == b"hello world"
+
+
+async def test_read_file_text_and_bytes_of_empty_file(volume: AsyncVolume):
+ assert await volume.read_file("empty.txt") == ""
+ assert await volume.read_file("empty.txt", format="bytes") == b""
+
+
+async def test_read_file_missing_path_raises(volume: AsyncVolume):
+ with pytest.raises(NotFoundException):
+ await volume.read_file("missing.txt")
diff --git a/packages/python-sdk/tests/sync/volume_sync/test_volume_content.py b/packages/python-sdk/tests/sync/volume_sync/test_volume_content.py
new file mode 100644
index 000000000..05259bc22
--- /dev/null
+++ b/packages/python-sdk/tests/sync/volume_sync/test_volume_content.py
@@ -0,0 +1,68 @@
+import httpx
+import pytest
+
+from e2b import Volume
+from e2b.exceptions import NotFoundException
+import e2b.volume.volume_sync as volume_sync_mod
+
+_files = {
+ "hello.txt": b"hello world",
+ "empty.txt": b"",
+}
+
+
+def _handler(request: httpx.Request) -> httpx.Response:
+ path = request.url.params.get("path")
+ content = _files.get(path)
+ if content is None:
+ return httpx.Response(404)
+ return httpx.Response(200, content=content)
+
+
+def volume(monkeypatch) -> Volume:
+ real_get_api_client = volume_sync_mod.get_volume_api_client
+
+ def mock_get_api_client(config, **kwargs):
+ client = real_get_api_client(config, **kwargs)
+ client.set_httpx_client(
+ httpx.Client(
+ base_url=config.api_url,
+ transport=httpx.MockTransport(_handler),
+ )
+ )
+ return client
+
+ monkeypatch.setattr(volume_sync_mod, "get_volume_api_client", mock_get_api_client)
+ return Volume(volume_id="vol-1", name="test-volume", token="vol-token")
+
+
+def test_read_file_stream_yields_content(volume: Volume):
+ stream = volume.read_file("hello.txt", format="stream")
+ assert b"".join(stream) == b"hello world"
+
+
+def test_read_file_stream_raises_for_missing_path(volume: Volume):
+ with pytest.raises(NotFoundException):
+ for _ in volume.read_file("missing.txt", format="stream"):
+ pass
+
+
+def test_read_file_stream_of_empty_file(volume: Volume):
+ stream = volume.read_file("empty.txt", format="stream")
+ assert b"".join(stream) == b""
+
+
+def test_read_file_text_and_bytes(volume: Volume):
+ assert volume.read_file("hello.txt") == "hello world"
+ assert volume.read_file("hello.txt", format="bytes") == b"hello world"
+
+
+def test_read_file_text_and_bytes_of_empty_file(volume: Volume):
+ assert volume.read_file("empty.txt") == ""
+ assert volume.read_file("empty.txt", format="bytes") == b""
+
+
+def test_read_file_missing_path_raises(volume: Volume):
+ with pytest.raises(NotFoundException):
+ volume.read_file("missing.txt")
diff --git a/packages/python-sdk/tests/test_volume_client.py b/packages/python-sdk/tests/test_volume_client.py
new file mode 100644
index 000000000..1495a0845
--- /dev/null
+++ b/packages/python-sdk/tests/test_volume_client.py
@@ -0,0 +1,115 @@
+import asyncio
+import threading
+
+import httpx
+import pytest
+
+from e2b.exceptions import AuthenticationException
+from e2b.volume.client_async import (
+ get_api_client as get_async_api_client,
+ get_transport as get_async_transport,
+)
+from e2b.volume.client_sync import (
+ get_api_client as get_sync_api_client,
+ get_transport as get_sync_transport,
+)
+from e2b.volume.connection_config import VolumeConnectionConfig
+
+
+def test_sync_client_requires_volume_token(monkeypatch):
+ monkeypatch.setenv("E2B_ACCESS_TOKEN", "env-access-token")
+
+ with pytest.raises(AuthenticationException):
+ get_sync_api_client(VolumeConnectionConfig())
+
+
+def test_async_client_requires_volume_token(monkeypatch):
+ monkeypatch.setenv("E2B_ACCESS_TOKEN", "env-access-token")
+
+ with pytest.raises(AuthenticationException):
+ get_async_api_client(VolumeConnectionConfig())
+
+
+def test_sync_client_uses_config_request_timeout():
+ client = get_sync_api_client(VolumeConnectionConfig(token="vol-token"))
+ assert client.get_httpx_client().timeout == httpx.Timeout(60.0)
+
+ client = get_sync_api_client(
+ VolumeConnectionConfig(token="vol-token", request_timeout=10.0)
+ )
+ assert client.get_httpx_client().timeout == httpx.Timeout(10.0)
+
+ client = get_sync_api_client(
+ VolumeConnectionConfig(token="vol-token", request_timeout=0)
+ )
+ assert client.get_httpx_client().timeout == httpx.Timeout(None)
+
+
+def test_async_client_uses_config_request_timeout():
+ async def run():
+ client = get_async_api_client(VolumeConnectionConfig(token="vol-token"))
+ assert client.get_async_httpx_client().timeout == httpx.Timeout(60.0)
+
+ client = get_async_api_client(
+ VolumeConnectionConfig(token="vol-token", request_timeout=0)
+ )
+ assert client.get_async_httpx_client().timeout == httpx.Timeout(None)
+
+ asyncio.run(run())
+
+
+def test_sync_transport_is_cached_per_proxy():
+ config = VolumeConnectionConfig(token="vol-token")
+ proxied = VolumeConnectionConfig(token="vol-token", proxy="http://127.0.0.1:8080")
+
+ transport_a = get_sync_transport(config)
+ transport_b = get_sync_transport(config)
+ transport_c = get_sync_transport(proxied)
+
+ assert transport_a is transport_b
+ assert transport_a is not transport_c
+
+
+def test_sync_transport_is_not_shared_across_threads():
+ config = VolumeConnectionConfig(token="vol-token")
+ main_transport = get_sync_transport(config)
+
+ result = {}
+
+ def worker():
+ result["transport"] = get_sync_transport(config)
+
+ thread = threading.Thread(target=worker)
+ thread.start()
+ thread.join()
+
+ assert result["transport"] is not main_transport
+
+
+def test_async_transport_is_cached_per_event_loop():
+ config = VolumeConnectionConfig(token="vol-token")
+ proxied = VolumeConnectionConfig(token="vol-token", proxy="http://127.0.0.1:8080")
+
+ async def get_transports():
+ return get_async_transport(config), get_async_transport(config)
+
+ async def get_proxied_transport():
+ return get_async_transport(proxied)
+
+ # Keep both loops alive at the same time so their ids cannot collide
+ loop_a = asyncio.new_event_loop()
+ loop_b = asyncio.new_event_loop()
+ try:
+ transport_a1, transport_a2 = loop_a.run_until_complete(get_transports())
+ transport_b1, _ = loop_b.run_until_complete(get_transports())
+ proxied_a = loop_a.run_until_complete(get_proxied_transport())
+
+ # Same loop reuses the transport, another loop gets its own
+ assert transport_a1 is transport_a2
+ assert transport_a1 is not transport_b1
+
+ # Different proxy gets its own transport even on the same loop
+ assert proxied_a is not transport_a1
+ finally:
+ loop_a.close()
+ loop_b.close()
diff --git a/packages/python-sdk/tests/test_volume_connection_config.py b/packages/python-sdk/tests/test_volume_connection_config.py
index 421bea813..61b54847f 100644
--- a/packages/python-sdk/tests/test_volume_connection_config.py
+++ b/packages/python-sdk/tests/test_volume_connection_config.py
@@ -48,3 +48,44 @@ def test_volume_api_url_custom_domain(monkeypatch):
def test_volume_api_url_custom_domain_in_args():
config = VolumeConnectionConfig(domain="custom.com")
assert config.api_url == "https://api.custom.com"
+
+
+def test_volume_token_does_not_fall_back_to_access_token_env(monkeypatch):
+ monkeypatch.setenv("E2B_ACCESS_TOKEN", "env-access-token")
+
+ config = VolumeConnectionConfig()
+ assert config.token is None
+ assert config.access_token is None
+
+
+def test_volume_token_in_args(monkeypatch):
+ monkeypatch.setenv("E2B_ACCESS_TOKEN", "env-access-token")
+
+ config = VolumeConnectionConfig(token="vol-token")
+ assert config.token == "vol-token"
+ assert config.access_token == "vol-token"
+
+
+def test_volume_config_does_not_mutate_caller_headers():
+ headers = {"X-Custom": "value"}
+
+ config = VolumeConnectionConfig(headers=headers)
+
+ assert headers == {"X-Custom": "value"}
+ assert config.headers["X-Custom"] == "value"
+ assert "User-Agent" in config.headers
+
+
+def test_volume_request_timeout_defaults_to_60_seconds():
+ config = VolumeConnectionConfig()
+ assert config.request_timeout == 60.0
+
+
+def test_volume_request_timeout_in_args():
+ config = VolumeConnectionConfig(request_timeout=10.0)
+ assert config.request_timeout == 10.0
+
+
+def test_volume_request_timeout_zero_disables_timeout():
+ config = VolumeConnectionConfig(request_timeout=0)
+ assert config.request_timeout is None