Skip to content

armgit / E2B

Public Imported from GitHub
0

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

feat(python-sdk): move template build-context uploads onto pyqwest (#1603)

Mish Ushakovb3a7c9f44a26
diff --git a/.changeset/python-pyqwest-template-uploads.md b/.changeset/python-pyqwest-template-uploads.md
new file mode 100644
index 000000000..27cd6b9a2
--- /dev/null
+++ b/.changeset/python-pyqwest-template-uploads.md
@@ -0,0 +1,12 @@
+---
+"@e2b/python-sdk": minor
+---
+
+Move template build-context uploads (to S3 presigned URLs) onto
+[`pyqwest`](https://pypi.org/project/pyqwest/) via its httpx-compatible
+transport adapter. Content-Length framing for the streamed archive body is
+preserved (S3 rejects chunked transfer encoding), and redirects stay with the
+httpx client instead of being followed inside the transport. The 1-hour upload
+timeout now bounds the entire upload rather than each socket operation, and
+`verify_ssl=False` on the client is no longer honored for uploads (pyqwest
+has no insecure-TLS option).
diff --git a/packages/python-sdk/e2b/template_async/build_api.py b/packages/python-sdk/e2b/template_async/build_api.py
index c9209fa5d..3d8c8f774 100644
--- a/packages/python-sdk/e2b/template_async/build_api.py
+++ b/packages/python-sdk/e2b/template_async/build_api.py
@@ -4,8 +4,10 @@ from types import TracebackType
from typing import Callable, Optional, List, Union
import httpx
+from pyqwest import HTTPTransport
+from pyqwest.httpx import AsyncPyqwestTransport
-from e2b.api import handle_api_exception
+from e2b.api import handle_api_exception, proxy_to_config
from e2b.io_utils import aiter_io_chunks
from e2b.api.client.api.templates import (
post_v3_templates,
@@ -118,6 +120,7 @@ async def upload_file(
upload_timeout = (
request_timeout if request_timeout is not None else FILE_UPLOAD_TIMEOUT_SECONDS
)
+ upload_proxy = proxy_to_config(getattr(api_client, "_proxy", None))
try:
tar_file = tar_file_stream(
file_name, context_path, ignore_patterns, resolve_symlinks, gzip
@@ -125,16 +128,30 @@ async def upload_file(
try:
size = os.fstat(tar_file.fileno()).st_size
+ # Through the pyqwest adapter the upload timeout is a
+ # whole-request deadline for the entire transfer, not a per-write
+ # bound as with the httpx transport this replaced.
async with httpx.AsyncClient(
timeout=httpx.Timeout(upload_timeout),
- verify=api_client._verify_ssl,
follow_redirects=api_client._follow_redirects,
- proxy=getattr(api_client, "_proxy", None),
- http2=False,
+ transport=AsyncPyqwestTransport(
+ HTTPTransport(
+ tls_include_system_certs=True,
+ proxy=(
+ upload_proxy.to_pyqwest()
+ if upload_proxy is not None
+ else None
+ ),
+ # Redirects belong to the httpx client above, not to
+ # reqwest.
+ follow_redirects=False,
+ )
+ ),
) as client:
# Stream the archive from disk via an async iterator. The
# explicit Content-Length suppresses chunked transfer
- # encoding, which S3 presigned URLs reject.
+ # encoding, which S3 presigned URLs reject; reqwest keeps the
+ # Content-Length framing for the streamed body.
response = await client.put(
url,
content=aiter_io_chunks(tar_file),
diff --git a/packages/python-sdk/e2b/template_sync/build_api.py b/packages/python-sdk/e2b/template_sync/build_api.py
index e838d8788..0525fa457 100644
--- a/packages/python-sdk/e2b/template_sync/build_api.py
+++ b/packages/python-sdk/e2b/template_sync/build_api.py
@@ -3,8 +3,10 @@ from types import TracebackType
from typing import Callable, Optional, List, Union
import httpx
+from pyqwest import SyncHTTPTransport
+from pyqwest.httpx import PyqwestTransport
-from e2b.api import handle_api_exception
+from e2b.api import handle_api_exception, proxy_to_config
from e2b.api.client.api.templates import (
post_v3_templates,
get_templates_template_id_files_hash,
@@ -116,21 +118,36 @@ def upload_file(
upload_timeout = (
request_timeout if request_timeout is not None else FILE_UPLOAD_TIMEOUT_SECONDS
)
+ upload_proxy = proxy_to_config(getattr(api_client, "_proxy", None))
try:
tar_file = tar_file_stream(
file_name, context_path, ignore_patterns, resolve_symlinks, gzip
)
try:
+ # Through the pyqwest adapter the upload timeout is a
+ # whole-request deadline for the entire transfer, not a per-write
+ # bound as with the httpx transport this replaced.
with httpx.Client(
timeout=httpx.Timeout(upload_timeout),
- verify=api_client._verify_ssl,
follow_redirects=api_client._follow_redirects,
- proxy=getattr(api_client, "_proxy", None),
- http2=False,
+ transport=PyqwestTransport(
+ SyncHTTPTransport(
+ tls_include_system_certs=True,
+ proxy=(
+ upload_proxy.to_pyqwest()
+ if upload_proxy is not None
+ else None
+ ),
+ # Redirects belong to the httpx client above, not to
+ # reqwest.
+ follow_redirects=False,
+ )
+ ),
) as client:
# httpx streams the archive from disk in chunks and sets
# Content-Length from the file size—S3 presigned URLs reject
- # chunked transfer encoding.
+ # chunked transfer encoding, and reqwest keeps the
+ # Content-Length framing for the streamed body.
response = client.put(url, content=tar_file)
response.raise_for_status()
finally:
diff --git a/packages/python-sdk/tests/async/template_async/test_upload_file.py b/packages/python-sdk/tests/async/template_async/test_upload_file.py
index 4b61e7c57..a8d299342 100644
--- a/packages/python-sdk/tests/async/template_async/test_upload_file.py
+++ b/packages/python-sdk/tests/async/template_async/test_upload_file.py
@@ -1,11 +1,14 @@
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
+from typing import Any, Dict
from unittest import mock
import httpx
+import pytest
from e2b.api.client.client import AuthenticatedClient
from e2b.template import utils as template_utils
+from e2b.exceptions import FileUploadException
from e2b.template.consts import FILE_UPLOAD_TIMEOUT_SECONDS
from e2b.template_async.build_api import upload_file
@@ -22,14 +25,23 @@ from e2b.template_async.build_api import upload_file
def _make_server():
- state = {"headers": None, "body_length": 0}
+ state: Dict[str, Any] = {"headers": None, "body_length": 0, "paths": []}
class Handler(BaseHTTPRequestHandler):
def do_PUT(self):
- state["headers"] = dict(self.headers)
+ # hyper (pyqwest) sends lowercase header names where httpcore
+ # title-cased them; compare case-insensitively.
+ state["headers"] = {k.lower(): v for k, v in self.headers.items()}
+ state["paths"].append(self.path)
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length) if length else b""
state["body_length"] = len(body)
+ if self.path.startswith("/redirect"):
+ self.send_response(307)
+ self.send_header("Location", "/upload")
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+ return
self.send_response(200)
self.end_headers()
@@ -72,15 +84,48 @@ async def test_upload_file_sets_content_length_and_no_chunked_encoding(tmp_path)
thread.join(timeout=5)
assert state["headers"] is not None
- content_length = state["headers"].get("Content-Length")
+ content_length = state["headers"].get("content-length")
assert content_length is not None
assert int(content_length) > 0
assert int(content_length) == state["body_length"]
- transfer_encoding = state["headers"].get("Transfer-Encoding")
+ transfer_encoding = state["headers"].get("transfer-encoding")
if transfer_encoding is not None:
assert "chunked" not in transfer_encoding.lower()
- assert "Authorization" not in state["headers"]
+ assert "authorization" not in state["headers"]
+
+
+async def test_upload_file_leaves_redirects_to_httpx(tmp_path):
+ # reqwest would otherwise follow redirects inside the transport, replaying
+ # the archive body against the new location without httpx knowing. The
+ # upload client follows the API client's setting (off), so an unexpected
+ # hop must surface as a failed upload rather than being retried behind
+ # httpx's back.
+ (tmp_path / "hello.txt").write_text("hello world")
+
+ server, thread, state = _make_server()
+ host, port = server.server_address
+
+ try:
+ client = AuthenticatedClient(base_url="http://test", token="test")
+ assert client._follow_redirects is False
+ with pytest.raises(FileUploadException, match="307"):
+ await upload_file(
+ api_client=client,
+ file_name="*.txt",
+ context_path=str(tmp_path),
+ url=f"http://{host}:{port}/redirect",
+ ignore_patterns=[],
+ resolve_symlinks=False,
+ gzip=True,
+ stack_trace=None,
+ )
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+ assert state["paths"] == ["/redirect"]
async def _capture_upload_timeout(tmp_path, request_timeout=None):
diff --git a/packages/python-sdk/tests/sync/template_sync/test_upload_file.py b/packages/python-sdk/tests/sync/template_sync/test_upload_file.py
index 74b65fa8c..a08ae9906 100644
--- a/packages/python-sdk/tests/sync/template_sync/test_upload_file.py
+++ b/packages/python-sdk/tests/sync/template_sync/test_upload_file.py
@@ -1,11 +1,14 @@
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer
+from typing import Any, Dict
from unittest import mock
import httpx
+import pytest
from e2b.api.client.client import AuthenticatedClient
from e2b.template import utils as template_utils
+from e2b.exceptions import FileUploadException
from e2b.template.consts import FILE_UPLOAD_TIMEOUT_SECONDS
from e2b.template_sync.build_api import upload_file
@@ -18,14 +21,23 @@ from e2b.template_sync.build_api import upload_file
def _make_server():
- state = {"headers": None, "body_length": 0}
+ state: Dict[str, Any] = {"headers": None, "body_length": 0, "paths": []}
class Handler(BaseHTTPRequestHandler):
def do_PUT(self):
- state["headers"] = dict(self.headers)
+ # hyper (pyqwest) sends lowercase header names where httpcore
+ # title-cased them; compare case-insensitively.
+ state["headers"] = {k.lower(): v for k, v in self.headers.items()}
+ state["paths"].append(self.path)
length = int(self.headers.get("Content-Length", 0))
body = self.rfile.read(length) if length else b""
state["body_length"] = len(body)
+ if self.path.startswith("/redirect"):
+ self.send_response(307)
+ self.send_header("Location", "/upload")
+ self.send_header("Content-Length", "0")
+ self.end_headers()
+ return
self.send_response(200)
self.end_headers()
@@ -68,15 +80,48 @@ def test_upload_file_sets_content_length_and_no_chunked_encoding(tmp_path):
thread.join(timeout=5)
assert state["headers"] is not None
- content_length = state["headers"].get("Content-Length")
+ content_length = state["headers"].get("content-length")
assert content_length is not None
assert int(content_length) > 0
assert int(content_length) == state["body_length"]
- transfer_encoding = state["headers"].get("Transfer-Encoding")
+ transfer_encoding = state["headers"].get("transfer-encoding")
if transfer_encoding is not None:
assert "chunked" not in transfer_encoding.lower()
- assert "Authorization" not in state["headers"]
+ assert "authorization" not in state["headers"]
+
+
+def test_upload_file_leaves_redirects_to_httpx(tmp_path):
+ # reqwest would otherwise follow redirects inside the transport, replaying
+ # the archive body against the new location without httpx knowing. The
+ # upload client follows the API client's setting (off), so an unexpected
+ # hop must surface as a failed upload rather than being retried behind
+ # httpx's back.
+ (tmp_path / "hello.txt").write_text("hello world")
+
+ server, thread, state = _make_server()
+ host, port = server.server_address
+
+ try:
+ client = AuthenticatedClient(base_url="http://test", token="test")
+ assert client._follow_redirects is False
+ with pytest.raises(FileUploadException, match="307"):
+ upload_file(
+ api_client=client,
+ file_name="*.txt",
+ context_path=str(tmp_path),
+ url=f"http://{host}:{port}/redirect",
+ ignore_patterns=[],
+ resolve_symlinks=False,
+ gzip=True,
+ stack_trace=None,
+ )
+ finally:
+ server.shutdown()
+ server.server_close()
+ thread.join(timeout=5)
+
+ assert state["paths"] == ["/redirect"]
def _capture_upload_timeout(tmp_path, request_timeout=None):