Skip to content

armgit / E2B

Public Imported from GitHub
0

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

feat: add gzip content encoding option for file operations (#1252)

Mish Ushakovb5f26311414a
diff --git a/.changeset/gzip-file-upload.md b/.changeset/gzip-file-upload.md
new file mode 100644
index 000000000..d53912dc7
--- /dev/null
+++ b/.changeset/gzip-file-upload.md
@@ -0,0 +1,6 @@
+---
+'@e2b/python-sdk': patch
+'e2b': patch
+---
+
+added gzip support for sandbox file upload/download
diff --git a/packages/js-sdk/src/index.ts b/packages/js-sdk/src/index.ts
index 1a52e70e6..e67092a01 100644
--- a/packages/js-sdk/src/index.ts
+++ b/packages/js-sdk/src/index.ts
@@ -25,7 +25,13 @@ export type { Logger } from './logs'
export { getSignature } from './sandbox/signature'
export { FileType } from './sandbox/filesystem'
-export type { WriteInfo, EntryInfo, Filesystem } from './sandbox/filesystem'
+export type {
+ WriteInfo,
+ EntryInfo,
+ Filesystem,
+ FilesystemWriteOpts,
+ FilesystemReadOpts,
+} from './sandbox/filesystem'
export { FilesystemEventType } from './sandbox/filesystem/watchHandle'
export type {
FilesystemEvent,
diff --git a/packages/js-sdk/src/sandbox/filesystem/index.ts b/packages/js-sdk/src/sandbox/filesystem/index.ts
index cf58160c7..2803cc8ce 100644
--- a/packages/js-sdk/src/sandbox/filesystem/index.ts
+++ b/packages/js-sdk/src/sandbox/filesystem/index.ts
@@ -37,7 +37,7 @@ import {
InvalidArgumentError,
TemplateError,
} from '../../errors'
-import { toBlob } from '../../utils'
+import { toBlob, toUploadBody } from '../../utils'
const FILESYSTEM_HTTP_ERROR_MAP: Record<number, (message: string) => Error> = {
404: (message: string) => new FileNotFoundError(message),
@@ -164,6 +164,26 @@ export interface FilesystemRequestOpts
user?: Username
}
+/**
+ * Options for writing files to the sandbox filesystem.
+ */
+export interface FilesystemWriteOpts extends FilesystemRequestOpts {
+ /**
+ * When true, the upload will be gzip-compressed.
+ */
+ gzip?: boolean
+}
+
+/**
+ * Options for reading files from the sandbox filesystem.
+ */
+export interface FilesystemReadOpts extends FilesystemRequestOpts {
+ /**
+ * When true, the download will request gzip-encoded responses.
+ */
+ gzip?: boolean
+}
+
export interface FilesystemListOpts extends FilesystemRequestOpts {
/**
* Depth of the directory to list.
@@ -222,7 +242,7 @@ export class Filesystem {
*/
async read(
path: string,
- opts?: FilesystemRequestOpts & { format?: 'text' }
+ opts?: FilesystemReadOpts & { format?: 'text' }
): Promise<string>
/**
* Read file content as a `Uint8Array`.
@@ -237,7 +257,7 @@ export class Filesystem {
*/
async read(
path: string,
- opts?: FilesystemRequestOpts & { format: 'bytes' }
+ opts?: FilesystemReadOpts & { format: 'bytes' }
): Promise<Uint8Array>
/**
* Read file content as a `Blob`.
@@ -252,7 +272,7 @@ export class Filesystem {
*/
async read(
path: string,
- opts?: FilesystemRequestOpts & { format: 'blob' }
+ opts?: FilesystemReadOpts & { format: 'blob' }
): Promise<Blob>
/**
* Read file content as a `ReadableStream`.
@@ -267,12 +287,12 @@ export class Filesystem {
*/
async read(
path: string,
- opts?: FilesystemRequestOpts & { format: 'stream' }
+ opts?: FilesystemReadOpts & { format: 'stream' }
): Promise<ReadableStream<Uint8Array>>
async read(
path: string,
- opts?: FilesystemRequestOpts & {
- format?: 'text' | 'stream' | 'bytes' | 'blob'
+ opts?: FilesystemReadOpts & {
+ format?: 'text' | 'bytes' | 'blob' | 'stream'
}
): Promise<unknown> {
const format = opts?.format ?? 'text'
@@ -285,6 +305,11 @@ export class Filesystem {
user = defaultUsername
}
+ const headers: Record<string, string> = {}
+ if (opts?.gzip) {
+ headers['Accept-Encoding'] = 'gzip'
+ }
+
const res = await this.envdApi.api.GET('/files', {
params: {
query: {
@@ -294,6 +319,7 @@ export class Filesystem {
},
parseAs: format === 'bytes' ? 'arrayBuffer' : format,
signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ headers,
})
const err = await handleFilesystemEnvdApiError(res)
@@ -332,11 +358,11 @@ export class Filesystem {
async write(
path: string,
data: string | ArrayBuffer | Blob | ReadableStream,
- opts?: FilesystemRequestOpts
+ opts?: FilesystemWriteOpts
): Promise<WriteInfo>
async write(
files: WriteEntry[],
- opts?: FilesystemRequestOpts
+ opts?: FilesystemWriteOpts
): Promise<WriteInfo[]>
async write(
pathOrFiles: string | WriteEntry[],
@@ -345,8 +371,8 @@ export class Filesystem {
| ArrayBuffer
| Blob
| ReadableStream
- | FilesystemRequestOpts,
- opts?: FilesystemRequestOpts
+ | FilesystemWriteOpts,
+ opts?: FilesystemWriteOpts
): Promise<WriteInfo | WriteInfo[]> {
if (typeof pathOrFiles !== 'string' && !Array.isArray(pathOrFiles)) {
throw new Error('Path or files are required')
@@ -362,7 +388,7 @@ export class Filesystem {
typeof pathOrFiles === 'string'
? {
path: pathOrFiles,
- writeOpts: opts as FilesystemRequestOpts,
+ writeOpts: opts as FilesystemWriteOpts,
writeFiles: [
{
data: dataOrOpts as
@@ -375,7 +401,7 @@ export class Filesystem {
}
: {
path: undefined,
- writeOpts: dataOrOpts as FilesystemRequestOpts,
+ writeOpts: dataOrOpts as FilesystemWriteOpts,
writeFiles: pathOrFiles as WriteEntry[],
}
@@ -394,11 +420,20 @@ export class Filesystem {
const results: WriteInfo[] = []
+ const useGzip = writeOpts?.gzip === true
+
if (useOctetStream) {
+ const headers: Record<string, string> = {
+ 'Content-Type': 'application/octet-stream',
+ }
+ if (useGzip) {
+ headers['Content-Encoding'] = 'gzip'
+ }
+
const uploadResults = await Promise.all(
writeFiles.map(async (file) => {
const filePath = path ?? (file as WriteEntry).path
- const blob = await toBlob(file.data)
+ const body = await toUploadBody(file.data, useGzip)
const res = await this.envdApi.api.POST('/files', {
params: {
@@ -407,10 +442,8 @@ export class Filesystem {
username: user,
},
},
- bodySerializer: () => blob,
- headers: {
- 'Content-Type': 'application/octet-stream',
- },
+ bodySerializer: () => body,
+ headers,
signal: this.connectionConfig.getSignal(
writeOpts?.requestTimeoutMs
),
@@ -491,7 +524,7 @@ export class Filesystem {
*/
async writeFiles(
files: WriteEntry[],
- opts?: FilesystemRequestOpts
+ opts?: FilesystemWriteOpts
): Promise<WriteInfo[]> {
return this.write(files, opts) as Promise<WriteInfo[]>
}
diff --git a/packages/js-sdk/src/utils.ts b/packages/js-sdk/src/utils.ts
index 92c925b8d..052574b50 100644
--- a/packages/js-sdk/src/utils.ts
+++ b/packages/js-sdk/src/utils.ts
@@ -124,3 +124,25 @@ export function toBlob(
// ReadableStream - must consume to get Blob
return new Response(data).blob()
}
+
+/**
+ * Prepare data for upload as a BodyInit, optionally gzip-compressed.
+ * When gzip is enabled, compresses the data and returns a Blob.
+ */
+export async function toUploadBody(
+ data: string | ArrayBuffer | Blob | ReadableStream,
+ gzip?: boolean
+): Promise<BodyInit> {
+ if (gzip) {
+ const stream =
+ data instanceof ReadableStream
+ ? data
+ : data instanceof Blob
+ ? data.stream()
+ : new Blob([data]).stream()
+ const compressed = stream.pipeThrough(new CompressionStream('gzip'))
+ return new Response(compressed).blob()
+ }
+
+ return toBlob(data)
+}
diff --git a/packages/js-sdk/tests/sandbox/files/contentEncoding.test.ts b/packages/js-sdk/tests/sandbox/files/contentEncoding.test.ts
new file mode 100644
index 000000000..2135cdc43
--- /dev/null
+++ b/packages/js-sdk/tests/sandbox/files/contentEncoding.test.ts
@@ -0,0 +1,94 @@
+import { assert } from 'vitest'
+
+import { WriteEntry } from '../../../src/sandbox/filesystem'
+import { isDebug, sandboxTest } from '../../setup.js'
+
+sandboxTest(
+ 'write and read file with gzip content encoding',
+ async ({ sandbox }) => {
+ const filename = 'test_gzip_write.txt'
+ const content = 'This is a test file with gzip encoding.'
+
+ const info = await sandbox.files.write(filename, content, {
+ gzip: true,
+ })
+ assert.equal(info.name, filename)
+ assert.equal(info.type, 'file')
+ assert.equal(info.path, `/home/user/${filename}`)
+
+ const readContent = await sandbox.files.read(filename, {
+ gzip: true,
+ })
+ assert.equal(readContent, content)
+
+ if (isDebug) {
+ await sandbox.files.remove(filename)
+ }
+ }
+)
+
+sandboxTest(
+ 'write with gzip and read without encoding',
+ async ({ sandbox }) => {
+ const filename = 'test_gzip_write_plain_read.txt'
+ const content = 'Written with gzip, read without.'
+
+ await sandbox.files.write(filename, content, {
+ gzip: true,
+ })
+
+ const readContent = await sandbox.files.read(filename)
+ assert.equal(readContent, content)
+
+ if (isDebug) {
+ await sandbox.files.remove(filename)
+ }
+ }
+)
+
+sandboxTest('writeFiles with gzip content encoding', async ({ sandbox }) => {
+ const files: WriteEntry[] = [
+ { path: 'gzip_multi_1.txt', data: 'File 1 content' },
+ { path: 'gzip_multi_2.txt', data: 'File 2 content' },
+ { path: 'gzip_multi_3.txt', data: 'File 3 content' },
+ ]
+
+ const infos = await sandbox.files.writeFiles(files, {
+ gzip: true,
+ })
+
+ assert.equal(infos.length, files.length)
+
+ for (let i = 0; i < files.length; i++) {
+ const readContent = await sandbox.files.read(files[i].path)
+ assert.equal(readContent, files[i].data)
+ }
+
+ if (isDebug) {
+ for (const file of files) {
+ await sandbox.files.remove(file.path)
+ }
+ }
+})
+
+sandboxTest(
+ 'read file as bytes with gzip content encoding',
+ async ({ sandbox }) => {
+ const filename = 'test_gzip_bytes.txt'
+ const content = 'Binary content with gzip.'
+
+ await sandbox.files.write(filename, content)
+
+ const readBytes = await sandbox.files.read(filename, {
+ format: 'bytes',
+ gzip: true,
+ })
+ assert.instanceOf(readBytes, Uint8Array)
+ const decoded = new TextDecoder().decode(readBytes)
+ assert.equal(decoded, content)
+
+ if (isDebug) {
+ await sandbox.files.remove(filename)
+ }
+ }
+)
diff --git a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
index ff6c23574..1cee7327a 100644
--- a/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox/filesystem/filesystem.py
@@ -1,9 +1,12 @@
+import gzip
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
+from io import IOBase, TextIOBase
from typing import IO, Optional, Union, TypedDict
from e2b.envd.filesystem import filesystem_pb2
+from e2b.exceptions import InvalidArgumentException
class FileType(Enum):
@@ -92,3 +95,22 @@ class WriteEntry(TypedDict):
path: str
data: Union[str, bytes, IO]
+
+
+def to_upload_body(
+ data: Union[str, bytes, IO],
+ use_gzip: bool = False,
+) -> bytes:
+ """Prepare file data for upload, optionally gzip-compressed."""
+ if isinstance(data, str):
+ raw = data.encode("utf-8")
+ elif isinstance(data, bytes):
+ raw = data
+ elif isinstance(data, TextIOBase):
+ raw = data.read().encode("utf-8")
+ elif isinstance(data, IOBase):
+ raw = data.read()
+ else:
+ raise InvalidArgumentException(f"Unsupported data type: {type(data)}")
+
+ return gzip.compress(raw) if use_gzip else raw
diff --git a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
index bfaf5492f..8f70f58a1 100644
--- a/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_async/filesystem/filesystem.py
@@ -2,6 +2,7 @@ import asyncio
from io import IOBase, TextIOBase
from typing import IO, AsyncIterator, List, Literal, Optional, Union, overload
+
import httpcore
import httpx
from packaging.version import Version
@@ -33,6 +34,7 @@ from e2b.sandbox.filesystem.filesystem import (
WriteEntry,
WriteInfo,
map_file_type,
+ to_upload_body,
)
from e2b.sandbox.filesystem.watch_handle import FilesystemEvent
from e2b.sandbox_async.filesystem.watch_handle import AsyncWatchHandle
@@ -91,6 +93,7 @@ class Filesystem:
format: Literal["text"] = "text",
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
) -> str:
"""
Read file content as a `str`.
@@ -99,6 +102,7 @@ class Filesystem:
:param user: Run the operation as this user
:param format: Format of the file content—`text` by default
:param request_timeout: Timeout for the request in **seconds**
+ :param gzip: Use gzip compression for the request
:return: File content as a `str`
"""
@@ -111,6 +115,7 @@ class Filesystem:
format: Literal["bytes"],
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
) -> bytearray:
"""
Read file content as a `bytearray`.
@@ -119,6 +124,7 @@ class Filesystem:
:param user: Run the operation as this user
:param format: Format of the file content—`bytes`
:param request_timeout: Timeout for the request in **seconds**
+ :param gzip: Use gzip compression for the request
:return: File content as a `bytearray`
"""
@@ -131,6 +137,7 @@ class Filesystem:
format: Literal["stream"],
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
) -> AsyncIterator[bytes]:
"""
Read file content as a `AsyncIterator[bytes]`.
@@ -139,6 +146,7 @@ class Filesystem:
:param user: Run the operation as this user
:param format: Format of the file content—`stream`
:param request_timeout: Timeout for the request in **seconds**
+ :param gzip: Use gzip compression for the request
:return: File content as an `AsyncIterator[bytes]`
"""
@@ -150,6 +158,7 @@ class Filesystem:
format: Literal["text", "bytes", "stream"] = "text",
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
):
username = user
if username is None and self._envd_version < ENVD_DEFAULT_USER:
@@ -159,9 +168,14 @@ class Filesystem:
if username:
params["username"] = username
+ headers = {}
+ if gzip:
+ headers["Accept-Encoding"] = "gzip"
+
r = await self._envd_api.get(
ENVD_API_FILES_ROUTE,
params=params,
+ headers=headers,
timeout=self._connection_config.get_request_timeout(request_timeout),
)
@@ -182,6 +196,7 @@ class Filesystem:
data: Union[str, bytes, IO],
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
) -> WriteInfo:
"""
Write content to a file on the path.
@@ -193,11 +208,15 @@ class Filesystem:
:param data: Data to write to the file, can be a `str`, `bytes`, or `IO`.
:param user: Run the operation as this user
:param request_timeout: Timeout for the request in **seconds**
+ :param gzip: Use gzip compression for the request
:return: Information about the written file
"""
result = await self.write_files(
- [WriteEntry(path=path, data=data)], user, request_timeout
+ [WriteEntry(path=path, data=data)],
+ user,
+ request_timeout,
+ gzip,
)
if len(result) != 1:
@@ -210,6 +229,7 @@ class Filesystem:
files: List[WriteEntry],
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
) -> List[WriteInfo]:
"""
Writes multiple files.
@@ -222,6 +242,7 @@ class Filesystem:
:param files: list of files to write as `WriteEntry` objects, each containing `path` and `data`
:param user: Run the operation as this user
:param request_timeout: Timeout for the request
+ :param gzip: Use gzip compression for the request
:return: Information about the written files
"""
username = user
@@ -240,27 +261,20 @@ class Filesystem:
async def _upload_file(file):
file_path, file_data = file["path"], file["data"]
- if isinstance(file_data, str):
- content = file_data.encode("utf-8")
- elif isinstance(file_data, bytes):
- content = file_data
- elif isinstance(file_data, TextIOBase):
- content = file_data.read().encode("utf-8")
- elif isinstance(file_data, IOBase):
- content = file_data.read()
- else:
- raise InvalidArgumentException(
- f"Unsupported data type for file {file_path}"
- )
+ content = to_upload_body(file_data, gzip)
params = {"path": file_path}
if username:
params["username"] = username
+ headers = {"Content-Type": "application/octet-stream"}
+ if gzip:
+ headers["Content-Encoding"] = "gzip"
+
r = await self._envd_api.post(
ENVD_API_FILES_ROUTE,
content=content,
- headers={"Content-Type": "application/octet-stream"},
+ headers=headers,
params=params,
timeout=self._connection_config.get_request_timeout(
request_timeout
diff --git a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
index 7548a9e27..9b26a22d0 100644
--- a/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
+++ b/packages/python-sdk/e2b/sandbox_sync/filesystem/filesystem.py
@@ -34,6 +34,7 @@ from e2b.sandbox.filesystem.filesystem import (
WriteEntry,
WriteInfo,
map_file_type,
+ to_upload_body,
)
from e2b.sandbox_sync.filesystem.watch_handle import WatchHandle
@@ -90,6 +91,7 @@ class Filesystem:
format: Literal["text"] = "text",
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
) -> str:
"""
Read file content as a `str`.
@@ -98,6 +100,7 @@ class Filesystem:
:param user: Run the operation as this user
:param format: Format of the file content—`text` by default
:param request_timeout: Timeout for the request in **seconds**
+ :param gzip: Use gzip compression for the request
:return: File content as a `str`
"""
@@ -110,6 +113,7 @@ class Filesystem:
format: Literal["bytes"],
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
) -> bytearray:
"""
Read file content as a `bytearray`.
@@ -118,6 +122,7 @@ class Filesystem:
:param user: Run the operation as this user
:param format: Format of the file content—`bytes`
:param request_timeout: Timeout for the request in **seconds**
+ :param gzip: Use gzip compression for the request
:return: File content as a `bytearray`
"""
@@ -130,6 +135,7 @@ class Filesystem:
format: Literal["stream"],
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
) -> Iterator[bytes]:
"""
Read file content as a `Iterator[bytes]`.
@@ -138,6 +144,7 @@ class Filesystem:
:param user: Run the operation as this user
:param format: Format of the file content—`stream`
:param request_timeout: Timeout for the request in **seconds**
+ :param gzip: Use gzip compression for the request
:return: File content as an `Iterator[bytes]`
"""
@@ -149,6 +156,7 @@ class Filesystem:
format: Literal["text", "bytes", "stream"] = "text",
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
):
username = user
if username is None and self._envd_version < ENVD_DEFAULT_USER:
@@ -158,9 +166,14 @@ class Filesystem:
if username:
params["username"] = username
+ headers = {}
+ if gzip:
+ headers["Accept-Encoding"] = "gzip"
+
r = self._envd_api.get(
ENVD_API_FILES_ROUTE,
params=params,
+ headers=headers,
timeout=self._connection_config.get_request_timeout(request_timeout),
)
@@ -181,6 +194,7 @@ class Filesystem:
data: Union[str, bytes, IO],
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
) -> WriteInfo:
"""
Write content to a file on the path.
@@ -192,6 +206,7 @@ class Filesystem:
:param data: Data to write to the file, can be a `str`, `bytes`, or `IO`.
:param user: Run the operation as this user
:param request_timeout: Timeout for the request in **seconds**
+ :param gzip: Use gzip compression for the request
:return: Information about the written file
"""
@@ -199,6 +214,7 @@ class Filesystem:
[WriteEntry(path=path, data=data)],
user=user,
request_timeout=request_timeout,
+ gzip=gzip,
)
if len(result) != 1:
@@ -211,6 +227,7 @@ class Filesystem:
files: List[WriteEntry],
user: Optional[Username] = None,
request_timeout: Optional[float] = None,
+ gzip: bool = False,
) -> List[WriteInfo]:
"""
Writes a list of files to the filesystem.
@@ -221,6 +238,7 @@ class Filesystem:
:param files: list of files to write as `WriteEntry` objects, each containing `path` and `data`
:param user: Run the operation as this user
:param request_timeout: Timeout for the request
+ :param gzip: Use gzip compression for the request
:return: Information about the written files
"""
username = user
@@ -238,27 +256,20 @@ class Filesystem:
for file in files:
file_path, file_data = file["path"], file["data"]
- if isinstance(file_data, str):
- content = file_data.encode("utf-8")
- elif isinstance(file_data, bytes):
- content = file_data
- elif isinstance(file_data, TextIOBase):
- content = file_data.read().encode("utf-8")
- elif isinstance(file_data, IOBase):
- content = file_data.read()
- else:
- raise InvalidArgumentException(
- f"Unsupported data type for file {file_path}"
- )
+ content = to_upload_body(file_data, gzip)
params = {"path": file_path}
if username:
params["username"] = username
+ headers = {"Content-Type": "application/octet-stream"}
+ if gzip:
+ headers["Content-Encoding"] = "gzip"
+
r = self._envd_api.post(
ENVD_API_FILES_ROUTE,
content=content,
- headers={"Content-Type": "application/octet-stream"},
+ headers=headers,
params=params,
timeout=self._connection_config.get_request_timeout(
request_timeout
diff --git a/packages/python-sdk/tests/async/sandbox_async/files/test_content_encoding.py b/packages/python-sdk/tests/async/sandbox_async/files/test_content_encoding.py
new file mode 100644
index 000000000..c6b2df85a
--- /dev/null
+++ b/packages/python-sdk/tests/async/sandbox_async/files/test_content_encoding.py
@@ -0,0 +1,62 @@
+from e2b import AsyncSandbox
+from e2b.sandbox.filesystem.filesystem import WriteEntry
+
+
+async def test_write_and_read_with_gzip(async_sandbox: AsyncSandbox, debug):
+ filename = "test_gzip_write.txt"
+ content = "This is a test file with gzip encoding."
+
+ info = await async_sandbox.files.write(filename, content, gzip=True)
+ assert info.path == f"/home/user/{filename}"
+
+ read_content = await async_sandbox.files.read(filename, gzip=True)
+ assert read_content == content
+
+ if debug:
+ await async_sandbox.files.remove(filename)
+
+
+async def test_write_gzip_read_plain(async_sandbox: AsyncSandbox, debug):
+ filename = "test_gzip_write_plain_read.txt"
+ content = "Written with gzip, read without."
+
+ await async_sandbox.files.write(filename, content, gzip=True)
+
+ read_content = await async_sandbox.files.read(filename)
+ assert read_content == content
+
+ if debug:
+ await async_sandbox.files.remove(filename)
+
+
+async def test_write_files_with_gzip(async_sandbox: AsyncSandbox, debug):
+ files = [
+ WriteEntry(path="gzip_multi_1.txt", data="File 1 content"),
+ WriteEntry(path="gzip_multi_2.txt", data="File 2 content"),
+ WriteEntry(path="gzip_multi_3.txt", data="File 3 content"),
+ ]
+
+ infos = await async_sandbox.files.write_files(files, gzip=True)
+ assert len(infos) == len(files)
+
+ for file in files:
+ read_content = await async_sandbox.files.read(file["path"])
+ assert read_content == file["data"]
+
+ if debug:
+ for file in files:
+ await async_sandbox.files.remove(file["path"])
+
+
+async def test_read_bytes_with_gzip(async_sandbox: AsyncSandbox, debug):
+ filename = "test_gzip_bytes.txt"
+ content = "Binary content with gzip."
+
+ await async_sandbox.files.write(filename, content)
+
+ read_bytes = await async_sandbox.files.read(filename, format="bytes", gzip=True)
+ assert isinstance(read_bytes, bytearray)
+ assert read_bytes.decode("utf-8") == content
+
+ if debug:
+ await async_sandbox.files.remove(filename)
diff --git a/packages/python-sdk/tests/sync/sandbox_sync/files/test_content_encoding.py b/packages/python-sdk/tests/sync/sandbox_sync/files/test_content_encoding.py
new file mode 100644
index 000000000..3d8b68bc0
--- /dev/null
+++ b/packages/python-sdk/tests/sync/sandbox_sync/files/test_content_encoding.py
@@ -0,0 +1,61 @@
+from e2b.sandbox.filesystem.filesystem import WriteEntry
+
+
+def test_write_and_read_with_gzip(sandbox, debug):
+ filename = "test_gzip_write.txt"
+ content = "This is a test file with gzip encoding."
+
+ info = sandbox.files.write(filename, content, gzip=True)
+ assert info.path == f"/home/user/{filename}"
+
+ read_content = sandbox.files.read(filename, gzip=True)
+ assert read_content == content
+
+ if debug:
+ sandbox.files.remove(filename)
+
+
+def test_write_gzip_read_plain(sandbox, debug):
+ filename = "test_gzip_write_plain_read.txt"
+ content = "Written with gzip, read without."
+
+ sandbox.files.write(filename, content, gzip=True)
+
+ read_content = sandbox.files.read(filename)
+ assert read_content == content
+
+ if debug:
+ sandbox.files.remove(filename)
+
+
+def test_write_files_with_gzip(sandbox, debug):
+ files = [
+ WriteEntry(path="gzip_multi_1.txt", data="File 1 content"),
+ WriteEntry(path="gzip_multi_2.txt", data="File 2 content"),
+ WriteEntry(path="gzip_multi_3.txt", data="File 3 content"),
+ ]
+
+ infos = sandbox.files.write_files(files, gzip=True)
+ assert len(infos) == len(files)
+
+ for i, file in enumerate(files):
+ read_content = sandbox.files.read(file["path"])
+ assert read_content == file["data"]
+
+ if debug:
+ for file in files:
+ sandbox.files.remove(file["path"])
+
+
+def test_read_bytes_with_gzip(sandbox, debug):
+ filename = "test_gzip_bytes.txt"
+ content = "Binary content with gzip."
+
+ sandbox.files.write(filename, content)
+
+ read_bytes = sandbox.files.read(filename, format="bytes", gzip=True)
+ assert isinstance(read_bytes, bytearray)
+ assert read_bytes.decode("utf-8") == content
+
+ if debug:
+ sandbox.files.remove(filename)