Skip to content

armgit / E2B

Public Imported from GitHub
0

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

feat(js-sdk): run the template test suite on Deno (#1595)

Mish Ushakov9ee4414e6df8
diff --git a/.changeset/deno-template-uploads.md b/.changeset/deno-template-uploads.md
new file mode 100644
index 000000000..551527740
--- /dev/null
+++ b/.changeset/deno-template-uploads.md
@@ -0,0 +1,5 @@
+---
+'e2b': patch
+---
+
+Fix template file uploads under Deno. Deno's native `fetch` ignores a `Content-Length` header on stream bodies and fell back to `Transfer-Encoding: chunked`, which S3-compatible presigned upload URLs reject (see #1243). `Template.build` uploads now stream the spooled archive through undici's `fetch`, which honors the header on every runtime, falling back to the global `fetch` where undici isn't resolvable.
diff --git a/.github/workflows/js_sdk_tests.yml b/.github/workflows/js_sdk_tests.yml
index bc251e7b5..b32ce4ab7 100644
--- a/.github/workflows/js_sdk_tests.yml
+++ b/.github/workflows/js_sdk_tests.yml
@@ -29,9 +29,9 @@ jobs:
strategy:
fail-fast: false
# With node-only (set by staging callers) the matrix collapses to the
- # Node legs: Bun/Deno only run API-free unit suites and the Cloudflare
- # legs add sandbox load without extra backend signal, so the other
- # runtimes are exercised against production only.
+ # Node legs: the Bun/Deno/Cloudflare legs re-run suites the Node legs
+ # already cover and add sandbox/build load without extra backend
+ # signal, so the other runtimes are exercised against production only.
matrix:
include: >-
${{ inputs.node-only
diff --git a/packages/js-sdk/package.json b/packages/js-sdk/package.json
index e225db957..18c9f1e90 100644
--- a/packages/js-sdk/package.json
+++ b/packages/js-sdk/package.json
@@ -39,7 +39,7 @@
"test:bun": "bunx --bun vitest run --project unit --project connectionConfig",
"test:cf": "vitest run --config tests/runtimes/cloudflare/vitest.config.mts",
"test:cf:deploy": "vitest run --config tests/runtimes/cloudflare-deploy/vitest.config.mts",
- "test:deno": "deno run -A npm:vitest run --project unit --project connectionConfig",
+ "test:deno": "deno run -A npm:vitest run --project unit --project connectionConfig --project template",
"typecheck": "tsc --noEmit",
"lint": "oxlint --config ../../.oxlintrc.json src tests",
"format": "prettier --write src/ tests/ example.mts"
diff --git a/packages/js-sdk/src/template/buildApi.ts b/packages/js-sdk/src/template/buildApi.ts
index 8b48b62ce..f79321166 100644
--- a/packages/js-sdk/src/template/buildApi.ts
+++ b/packages/js-sdk/src/template/buildApi.ts
@@ -1,11 +1,13 @@
-import type { Readable } from 'node:stream'
+import fs from 'node:fs'
+import stream from 'node:stream'
+
import { ApiClient, handleApiError, components } from '../api'
import { buildRequestSignal } from '../connectionConfig'
-import { dynamicImport } from '../utils'
+import { loadUndici } from '../undici'
import { BuildError, FileUploadError, TemplateError } from '../errors'
import { FILE_UPLOAD_TIMEOUT_MS } from './consts'
import { LogEntry } from './logger'
-import { getBuildStepIndex, tarFileStream } from './utils'
+import { getBuildStepIndex, spoolTarArchive } from './utils'
import {
BuildStatusReason,
TemplateBuildStatus,
@@ -130,40 +132,27 @@ export async function uploadFile(
gzip,
} = options
// Spool the archive to a temporary file and stream it from disk instead of
- // buffering in memory. S3 presigned PUT URLs reject Transfer-Encoding:
+ // buffering it in memory. S3 presigned PUT URLs reject Transfer-Encoding:
// chunked with 501 NotImplemented (see e2b-dev/e2b#1243), so the upload
- // sends an explicit Content-Length, which fetch honors for stream bodies.
- // The spooled file deletes itself once the stream is consumed, so there is
- // no cleanup to manage here. The Python SDK takes the same approach
- // (build_api.py:upload_file).
- let uploadStream: Readable | undefined
+ // must carry an exact Content-Length. The Python SDK takes the same
+ // approach (build_api.py:upload_file).
+ let cleanup: (() => Promise<void>) | undefined
try {
- // Dynamically import so the browser bundle doesn't pull in node:stream.
- const { Readable } =
- await dynamicImport<typeof import('node:stream')>('node:stream')
-
- const tar = await tarFileStream(
+ const tar = await spoolTarArchive(
fileName,
fileContextPath,
ignorePatterns,
resolveSymlinks,
gzip
)
- uploadStream = tar.stream
+ cleanup = tar.cleanup
- const res = await fetch(url, {
- method: 'PUT',
- body: Readable.toWeb(uploadStream) as ReadableStream<Uint8Array>,
- headers: {
- 'Content-Length': tar.size.toString(),
- },
- // Streaming request bodies require half-duplex mode.
- duplex: 'half',
- signal: buildRequestSignal(
- abortOpts?.requestTimeoutMs ?? FILE_UPLOAD_TIMEOUT_MS,
- abortOpts?.signal
- ),
- } as RequestInit)
+ const signal = buildRequestSignal(
+ abortOpts?.requestTimeoutMs ?? FILE_UPLOAD_TIMEOUT_MS,
+ abortOpts?.signal
+ )
+
+ const res = await putFileStream(url, tar.path, tar.size, signal)
if (!res.ok) {
throw new FileUploadError(
@@ -172,17 +161,44 @@ export async function uploadFile(
)
}
} catch (error) {
- // Ensure the spooled archive is removed even if fetch never consumed the
- // stream (e.g. it threw before reading the body). Destroying the stream
- // fires its `close` handler, which deletes the temp file.
- uploadStream?.destroy()
if (error instanceof FileUploadError) {
throw error
}
throw new FileUploadError(`Failed to upload file: ${error}`, stackTrace)
+ } finally {
+ await cleanup?.()
}
}
+async function putFileStream(
+ url: string,
+ filePath: string,
+ size: number,
+ signal: AbortSignal | undefined
+): Promise<{ ok: boolean; statusText: string }> {
+ // Prefer undici's fetch: it honors the explicit Content-Length on stream
+ // bodies on every runtime, while Deno's native fetch ignores the header and
+ // falls back to chunked. Where undici isn't resolvable (e.g. bundled apps),
+ // fall back to the global fetch — Node's and Bun's native fetch also honor
+ // Content-Length on stream bodies. loadUndici tries undici 8 first and
+ // falls back to undici 7 where 8 doesn't import (Bun).
+ const undici = await loadUndici()
+ const fetchImpl = (undici?.fetch as typeof fetch | undefined) ?? fetch
+
+ return await fetchImpl(url, {
+ method: 'PUT',
+ body: stream.Readable.toWeb(
+ fs.createReadStream(filePath)
+ ) as ReadableStream,
+ headers: {
+ 'Content-Length': size.toString(),
+ },
+ // Streaming request bodies require half-duplex mode.
+ duplex: 'half',
+ signal,
+ } as RequestInit)
+}
+
export async function triggerBuild(
client: ApiClient,
{ templateID, buildID, template }: TriggerBuildInput,
diff --git a/packages/js-sdk/src/template/utils.ts b/packages/js-sdk/src/template/utils.ts
index 3a953d180..5eccbc5d6 100644
--- a/packages/js-sdk/src/template/utils.ts
+++ b/packages/js-sdk/src/template/utils.ts
@@ -6,7 +6,6 @@ import url from 'node:url'
import { dynamicImport } from '../utils'
import { TemplateError } from '../errors'
import { BASE_STEP_NAME, FINALIZE_STEP_NAME } from './consts'
-import type { Readable } from 'node:stream'
import type { Path } from 'glob'
import type { BuildOptions } from './types'
@@ -353,35 +352,31 @@ export function padOctal(mode: number): string {
}
/**
- * Create a gzipped tar archive of files matching a pattern and return a
- * readable stream over it.
+ * Create a gzipped tar archive of files matching a pattern, spooled to a
+ * temporary file on disk.
*
- * The archive is spooled to a temporary file on disk so it can be uploaded as
- * a stream with a known `Content-Length` instead of being buffered in memory.
- * The temporary file is removed automatically once the returned stream is
- * closed — whether it was fully read, errored, or destroyed. This mirrors the
- * Python SDK's `tar_file_stream`, where closing the temp-file handle deletes
- * it (Node has no portable delete-on-close, so cleanup is tied to the stream's
- * `close` event instead).
+ * Spooling instead of buffering keeps memory bounded and gives the archive a
+ * known size, so the upload can send an exact `Content-Length`. The caller
+ * owns the archive's lifetime and must invoke `cleanup` once done with it.
+ * This mirrors the Python SDK's `tar_file_stream`.
*
* @param fileName Glob pattern for files to include
* @param fileContextPath Base directory for resolving file paths
* @param ignorePatterns Ignore patterns to exclude from the archive
* @param resolveSymlinks Whether to follow symbolic links
* @param gzip Whether to gzip the archive
- * @returns The readable stream and the archive size in bytes
+ * @returns The archive path, its size in bytes, and a cleanup callback that
+ * removes the spooled archive. Cleanup is best-effort so it can never mask
+ * the upload result — a leaked temp dir is non-fatal, the OS reclaims it.
*/
-export async function tarFileStream(
+export async function spoolTarArchive(
fileName: string,
fileContextPath: string,
ignorePatterns: string[],
resolveSymlinks: boolean,
gzip: boolean
-): Promise<{ stream: Readable; size: number }> {
+): Promise<{ path: string; size: number; cleanup: () => Promise<void> }> {
const { create } = await dynamicImport<typeof import('tar')>('tar')
- // Dynamically import so the browser bundle doesn't pull in node:fs.
- const { createReadStream } =
- await dynamicImport<typeof import('node:fs')>('node:fs')
const allFiles = await getAllFilesInPath(
fileName,
@@ -396,9 +391,7 @@ export async function tarFileStream(
path.join(os.tmpdir(), 'e2b-template-')
)
const tarPath = path.join(tmpDir, 'context.tar.gz')
- // Best-effort removal so it can never mask the archive-creation error or the
- // upload result. A leaked temp dir is non-fatal — the OS reclaims it.
- const removeTmpDir = () =>
+ const cleanup = () =>
fs.promises.rm(tmpDir, { recursive: true, force: true }).catch(() => {})
try {
@@ -414,14 +407,9 @@ export async function tarFileStream(
)
const { size } = await fs.promises.stat(tarPath)
-
- const stream = createReadStream(tarPath)
- // Remove the spooled archive once the stream is done — `close` fires after
- // the fd is released on every path (end, error, or destroy).
- stream.once('close', removeTmpDir)
- return { stream, size }
+ return { path: tarPath, size, cleanup }
} catch (err) {
- await removeTmpDir()
+ await cleanup()
throw err
}
}
diff --git a/packages/js-sdk/tests/template/uploadFile.test.ts b/packages/js-sdk/tests/template/uploadFile.test.ts
index 280b959a6..e9f7492c9 100644
--- a/packages/js-sdk/tests/template/uploadFile.test.ts
+++ b/packages/js-sdk/tests/template/uploadFile.test.ts
@@ -10,7 +10,9 @@ import { uploadFile } from '../../src/template/buildApi'
// Readable directly to fetch, which made undici fall back to
// Transfer-Encoding: chunked. S3 presigned PUT URLs reject that with 501
// NotImplemented. The fix spools the archive to a temporary file and streams
-// it from disk with an explicit Content-Length.
+// it from disk with an explicit Content-Length via undici's fetch, which
+// honors the header on stream bodies on every runtime (Deno's native fetch
+// ignores it and chunks). This suite runs under both Node and Deno.
describe('uploadFile transfer encoding', () => {
let testDir: string
let server: Server
@@ -66,5 +68,10 @@ describe('uploadFile transfer encoding', () => {
if (transferEncoding !== undefined) {
expect(transferEncoding.toLowerCase()).not.toContain('chunked')
}
+
+ // Presigned upload URLs sign the request headers, so an implicit
+ // Content-Type (e.g. inferred from the archive's file extension) makes
+ // the storage backend reject the upload with 403 Forbidden.
+ expect(capturedHeaders['content-type']).toBeUndefined()
})
})
diff --git a/packages/js-sdk/tests/template/utils/tarFileStream.test.ts b/packages/js-sdk/tests/template/utils/spoolTarArchive.test.ts
similarity index 53%
rename from packages/js-sdk/tests/template/utils/tarFileStream.test.ts
rename to packages/js-sdk/tests/template/utils/spoolTarArchive.test.ts
index 762fc6d93..397f5b3ee 100644
--- a/packages/js-sdk/tests/template/utils/tarFileStream.test.ts
+++ b/packages/js-sdk/tests/template/utils/spoolTarArchive.test.ts
@@ -1,23 +1,12 @@
-import {
- expect,
- test,
- describe,
- beforeAll,
- afterAll,
- beforeEach,
- vi,
-} from 'vitest'
+import { expect, test, describe, beforeAll, afterAll, beforeEach } from 'vitest'
import { writeFile, mkdir, rm, symlink, readFile, access } from 'fs/promises'
-import fs from 'node:fs'
-import { Readable } from 'node:stream'
-import { pipeline } from 'node:stream/promises'
-import { join } from 'path'
+import { join, dirname } from 'path'
import { tmpdir } from 'os'
-import { tarFileStream } from '../../../src/template/utils'
+import { spoolTarArchive } from '../../../src/template/utils'
import * as tar from 'tar'
import { ReadEntry } from 'tar'
-describe('tarFileStream', () => {
+describe('spoolTarArchive', () => {
const testDir = join(__dirname, 'tar-test-folder')
beforeAll(async () => {
@@ -35,26 +24,10 @@ describe('tarFileStream', () => {
})
/**
- * Wait until a path no longer exists. Cleanup runs asynchronously from the
- * stream's `close` handler, so it may not complete in the same tick.
+ * Extract a spooled archive and collect its entries, then remove the spool.
*/
- async function waitUntilGone(target: string): Promise<void> {
- for (let i = 0; i < 100; i++) {
- try {
- await access(target)
- } catch {
- return
- }
- await new Promise((resolve) => setTimeout(resolve, 10))
- }
- throw new Error(`path was not removed: ${target}`)
- }
-
- /**
- * Pipe an archive stream into tar's extractor and collect its entries.
- */
- async function extractTarStream(
- stream: Readable
+ async function extractTarArchive(
+ archive: Awaited<ReturnType<typeof spoolTarArchive>>
): Promise<{ extractDir: string; members: ReadEntry[] }> {
const extractDir = join(
tmpdir(),
@@ -63,16 +36,17 @@ describe('tarFileStream', () => {
await mkdir(extractDir, { recursive: true })
const members: ReadEntry[] = []
- await pipeline(
- stream,
- tar.extract({
+ try {
+ await tar.extract({
+ file: archive.path,
cwd: extractDir,
- gzip: true,
onentry: (entry: ReadEntry) => {
members.push(entry)
},
})
- )
+ } finally {
+ await archive.cleanup()
+ }
return { extractDir, members }
}
@@ -81,9 +55,9 @@ describe('tarFileStream', () => {
* Extract archive contents into a map of path -> file contents.
*/
async function extractTarContents(
- stream: Readable
+ archive: Awaited<ReturnType<typeof spoolTarArchive>>
): Promise<Map<string, Buffer | null>> {
- const { extractDir, members } = await extractTarStream(stream)
+ const { extractDir, members } = await extractTarArchive(archive)
const contents = new Map<string, Buffer | null>()
for (const member of members) {
@@ -111,9 +85,9 @@ describe('tarFileStream', () => {
* Extract archive members into a map of path -> entry.
*/
async function getTarMembers(
- stream: Readable
+ archive: Awaited<ReturnType<typeof spoolTarArchive>>
): Promise<Map<string, ReadEntry>> {
- const { extractDir, members } = await extractTarStream(stream)
+ const { extractDir, members } = await extractTarArchive(archive)
const map = new Map<string, ReadEntry>()
for (const member of members) {
map.set(member.path, member)
@@ -126,16 +100,10 @@ describe('tarFileStream', () => {
await writeFile(join(testDir, 'file1.txt'), 'content1')
await writeFile(join(testDir, 'file2.txt'), 'content2')
- const { stream, size } = await tarFileStream(
- '*.txt',
- testDir,
- [],
- false,
- true
- )
- expect(size).toBeGreaterThan(0)
+ const archive = await spoolTarArchive('*.txt', testDir, [], false, true)
+ expect(archive.size).toBeGreaterThan(0)
- const contents = await extractTarContents(stream)
+ const contents = await extractTarContents(archive)
expect(contents.size).toBe(2)
expect(contents.get('file1.txt')?.toString()).toBe('content1')
@@ -146,33 +114,32 @@ describe('tarFileStream', () => {
await writeFile(join(testDir, 'file1.txt'), 'content1')
await writeFile(join(testDir, 'file2.txt'), 'content2')
- const { stream } = await tarFileStream('*.txt', testDir, [], false, false)
+ const archive = await spoolTarArchive('*.txt', testDir, [], false, false)
- // Buffer the archive so we can both assert it is not gzipped and extract it
- const chunks: Buffer[] = []
- for await (const chunk of stream as unknown as AsyncIterable<Buffer>) {
- chunks.push(Buffer.from(chunk))
+ try {
+ const raw = await readFile(archive.path)
+
+ // gzip streams start with the magic bytes 0x1f 0x8b — an uncompressed tar must not
+ expect(raw[0]).not.toBe(0x1f)
+ expect(raw.subarray(0, 2).equals(Buffer.from([0x1f, 0x8b]))).toBe(false)
+
+ // And it should still extract to the original files
+ const extractDir = join(
+ tmpdir(),
+ `tar-uncompressed-extract-${Date.now()}`
+ )
+ await mkdir(extractDir, { recursive: true })
+ await tar.extract({ file: archive.path, cwd: extractDir })
+ expect((await readFile(join(extractDir, 'file1.txt'))).toString()).toBe(
+ 'content1'
+ )
+ expect((await readFile(join(extractDir, 'file2.txt'))).toString()).toBe(
+ 'content2'
+ )
+ await rm(extractDir, { recursive: true, force: true })
+ } finally {
+ await archive.cleanup()
}
- const archive = Buffer.concat(chunks)
-
- // gzip streams start with the magic bytes 0x1f 0x8b — an uncompressed tar must not
- expect(archive[0]).not.toBe(0x1f)
- expect(archive.subarray(0, 2).equals(Buffer.from([0x1f, 0x8b]))).toBe(false)
-
- // And it should still extract to the original files
- const tarFile = join(tmpdir(), `tar-uncompressed-${Date.now()}.tar`)
- await writeFile(tarFile, archive)
- const extractDir = join(tmpdir(), `tar-uncompressed-extract-${Date.now()}`)
- await mkdir(extractDir, { recursive: true })
- await tar.extract({ file: tarFile, cwd: extractDir })
- expect((await readFile(join(extractDir, 'file1.txt'))).toString()).toBe(
- 'content1'
- )
- expect((await readFile(join(extractDir, 'file2.txt'))).toString()).toBe(
- 'content2'
- )
- await rm(tarFile, { force: true })
- await rm(extractDir, { recursive: true, force: true })
})
test('should respect ignore patterns', async () => {
@@ -181,7 +148,7 @@ describe('tarFileStream', () => {
await writeFile(join(testDir, 'temp.txt'), 'temp content')
await writeFile(join(testDir, 'backup.txt'), 'backup content')
- const { stream } = await tarFileStream(
+ const archive = await spoolTarArchive(
'*.txt',
testDir,
['temp*', 'backup*'],
@@ -189,7 +156,7 @@ describe('tarFileStream', () => {
true
)
- const contents = await extractTarContents(stream)
+ const contents = await extractTarContents(archive)
expect(contents.size).toBe(2)
expect(contents.get('file1.txt')?.toString()).toBe('content1')
@@ -205,9 +172,9 @@ describe('tarFileStream', () => {
await writeFile(join(testDir, 'src', 'index.ts'), 'index content')
await writeFile(join(nestedDir, 'Button.tsx'), 'button content')
- const { stream } = await tarFileStream('src', testDir, [], false, true)
+ const archive = await spoolTarArchive('src', testDir, [], false, true)
- const contents = await extractTarContents(stream)
+ const contents = await extractTarContents(archive)
const paths = Array.from(contents.keys())
expect(paths.some((p) => p.includes('src'))).toBe(true)
expect(paths.some((p) => p.includes('index.ts'))).toBe(true)
@@ -228,9 +195,9 @@ describe('tarFileStream', () => {
}
// Test with resolveSymlinks=true
- const { stream } = await tarFileStream('*.txt', testDir, [], true, true)
+ const archive = await spoolTarArchive('*.txt', testDir, [], true, true)
- const contents = await extractTarContents(stream)
+ const contents = await extractTarContents(archive)
expect(contents.get('original.txt')?.toString()).toBe('original content')
// Symlink should be resolved (contain actual content, not link)
expect(contents.get('link.txt')?.toString()).toBe('original content')
@@ -250,65 +217,26 @@ describe('tarFileStream', () => {
}
// Test with resolveSymlinks=false
- const { stream } = await tarFileStream('*.txt', testDir, [], false, true)
+ const archive = await spoolTarArchive('*.txt', testDir, [], false, true)
- const members = await getTarMembers(stream)
+ const members = await getTarMembers(archive)
expect(members.get('original.txt')?.type).toBe('File')
const link = members.get('link.txt')!
expect(link.type).toBe('SymbolicLink')
expect(link.linkpath).toBe('original.txt')
})
- test('removes the spooled archive once the stream is consumed', async () => {
- await writeFile(join(testDir, 'file1.txt'), 'content1')
-
- // Capture the temp dir the helper creates so we can assert it is gone.
- let tmpDir: string | undefined
- const mkdtemp = fs.promises.mkdtemp.bind(fs.promises)
- const spy = vi
- .spyOn(fs.promises, 'mkdtemp')
- .mockImplementation(async (prefix: any, ...rest: any[]) => {
- const dir = await mkdtemp(prefix, ...rest)
- tmpDir = dir
- return dir
- })
-
- try {
- const { stream } = await tarFileStream('*.txt', testDir, [], false)
- expect(tmpDir).toBeDefined()
- await access(tmpDir!)
-
- // Drain the stream to completion; the `close` handler then removes the
- // spooled archive.
- stream.resume()
- await waitUntilGone(tmpDir!)
- } finally {
- spy.mockRestore()
- }
- })
-
- test('cleans up the spooled archive if it is never consumed', async () => {
+ test('cleanup removes the spooled archive and its temp dir', async () => {
await writeFile(join(testDir, 'file1.txt'), 'content1')
- let tmpDir: string | undefined
- const mkdtemp = fs.promises.mkdtemp.bind(fs.promises)
- const spy = vi
- .spyOn(fs.promises, 'mkdtemp')
- .mockImplementation(async (prefix: any, ...rest: any[]) => {
- const dir = await mkdtemp(prefix, ...rest)
- tmpDir = dir
- return dir
- })
+ const archive = await spoolTarArchive('*.txt', testDir, [], false, true)
+ const spoolDir = dirname(archive.path)
+ await access(spoolDir)
- try {
- const { stream } = await tarFileStream('*.txt', testDir, [], false)
- await access(tmpDir!)
+ await archive.cleanup()
- // Destroying without reading still fires `close` and removes the file.
- stream.destroy()
- await waitUntilGone(tmpDir!)
- } finally {
- spy.mockRestore()
- }
+ await expect(access(spoolDir)).rejects.toThrow()
+ // Cleanup is idempotent
+ await archive.cleanup()
})
})