Skip to content
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/empty-fans-wave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'e2b': patch
---

Use HTTP/2 for JS SDK envd/api requests and require Node.js 20.18.1 or newer.
5 changes: 3 additions & 2 deletions packages/js-sdk/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,11 @@
"glob": "^11.1.0",
"openapi-fetch": "^0.14.1",
"platform": "^1.3.6",
"tar": "^7.5.11"
"tar": "^7.5.11",
"undici": "^7.25.0"
},
"engines": {
"node": ">=20"
"node": ">=20.18.1"
},
"browserslist": [
"defaults"
Expand Down
83 changes: 83 additions & 0 deletions packages/js-sdk/src/envd/http2.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { dynamicRequire, runtime } from '../utils'

type Undici = typeof import('undici')
type UndiciDispatcher = InstanceType<Undici['Agent']>
type UndiciRequestInit = RequestInit & {
dispatcher: UndiciDispatcher
duplex?: 'half'
}

let envdFetch: typeof fetch | undefined

export function createEnvdFetchForRuntime(
currentRuntime = runtime
): typeof fetch {
if (currentRuntime !== 'node') {
return fetch
}

const { Agent, fetch: undiciFetch } = dynamicRequire<Undici>('undici')
const dispatcher = new Agent({
allowH2: true,
// Keep one origin connection for h2 multiplexing. If ALPN falls back to h1,
// this favors connection pressure over per-sandbox throughput.
connections: 1,
})
const fetchWithDispatcher = undiciFetch as unknown as (
input: RequestInfo | URL,
init?: UndiciRequestInit
) => Promise<Response>

return ((input, init) => {
const request = toRequestInput(input, init)

return fetchWithDispatcher(request.input, {
...request.init,
dispatcher,
})
}) as typeof fetch
}

export function createEnvdFetch(): typeof fetch {
if (envdFetch) {
return envdFetch
}

envdFetch = createEnvdFetchForRuntime(runtime)

return envdFetch
}

function toRequestInput(
input: RequestInfo | URL,
init?: RequestInit
): { input: RequestInfo | URL; init?: RequestInit & { duplex?: 'half' } } {
if (!(input instanceof Request)) {
return { input, init }
}

const requestInit: RequestInit & { duplex?: 'half' } = {
body: input.body,
cache: input.cache,
credentials: input.credentials,
headers: input.headers,
integrity: input.integrity,
keepalive: input.keepalive,
method: input.method,
mode: input.mode,
redirect: input.redirect,
referrer: input.referrer,
referrerPolicy: input.referrerPolicy,
signal: input.signal,
...init,
}

if (requestInit.body) {
requestInit.duplex = 'half'
}

return {
input: input.url,
init: requestInit,
}
}
3 changes: 3 additions & 0 deletions packages/js-sdk/src/sandbox/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
Username,
} from '../connectionConfig'
import { EnvdApiClient, handleEnvdApiError } from '../envd/api'
import { createEnvdFetch } from '../envd/http2'
import { createRpcLogger } from '../logs'
import { Commands, Pty } from './commands'
import { Filesystem } from './filesystem'
Expand Down Expand Up @@ -150,6 +151,7 @@ export class Sandbox extends SandboxApi {
'E2b-Sandbox-Id': this.sandboxId,
'E2b-Sandbox-Port': this.envdPort.toString(),
}
const envdFetch = createEnvdFetch()

const rpcTransport = createConnectTransport({
baseUrl: this.envdApiUrl,
Expand Down Expand Up @@ -195,6 +197,7 @@ export class Sandbox extends SandboxApi {
? { 'X-Access-Token': this.envdAccessToken }
: {}),
},
fetch: (request) => envdFetch(request),
Comment thread
cursor[bot] marked this conversation as resolved.
},
{
version: opts.envdVersion,
Expand Down
78 changes: 78 additions & 0 deletions packages/js-sdk/tests/envd/http2.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import { afterEach, expect, test, vi } from 'vitest'

afterEach(() => {
vi.restoreAllMocks()
vi.resetModules()
vi.doUnmock('../../src/utils')
})

test('uses undici with HTTP/2 enabled in Node', async () => {
const agents: Array<{ allowH2?: boolean; connections?: number }> = []
const requests: Array<{ init?: RequestInit & { dispatcher?: unknown } }> = []

class Agent {
constructor(options: { allowH2?: boolean; connections?: number }) {
agents.push(options)
}
}

const undiciFetch = vi.fn((input, init) => {
requests.push({ init })
return Promise.resolve(new Response('ok'))
})

vi.doMock('../../src/utils', () => ({
dynamicRequire: () => ({ Agent, fetch: undiciFetch }),
runtime: 'node',
}))
const { createEnvdFetchForRuntime } = await import('../../src/envd/http2')

const fetcher = createEnvdFetchForRuntime('node')
const res = await fetcher('https://example.com/status')

expect(await res.text()).toBe('ok')
expect(agents).toEqual([{ allowH2: true, connections: 1 }])
expect(requests[0].init?.dispatcher).toBeInstanceOf(Agent)
})

test('passes Request objects to undici as URL plus init', async () => {
const requests: Array<{ input: RequestInfo | URL; init?: RequestInit }> = []

class Agent {}

const undiciFetch = vi.fn((input, init) => {
requests.push({ input, init })
return Promise.resolve(new Response('ok'))
})

vi.doMock('../../src/utils', () => ({
dynamicRequire: () => ({ Agent, fetch: undiciFetch }),
runtime: 'node',
}))
const { createEnvdFetchForRuntime } = await import('../../src/envd/http2')

const fetcher = createEnvdFetchForRuntime('node')
const body = JSON.stringify({ ok: true })
await fetcher(
new Request('https://example.com/rpc', {
body,
headers: { 'content-type': 'application/json' },
method: 'POST',
})
)

expect(requests[0].input).toBe('https://example.com/rpc')
expect(requests[0].init?.method).toBe('POST')
expect(requests[0].init?.headers).toBeInstanceOf(Headers)
expect(requests[0].init?.body).toBeInstanceOf(ReadableStream)
})

test('uses global fetch outside Node', async () => {
const fallbackFetch = vi.fn() as unknown as typeof fetch
vi.stubGlobal('fetch', fallbackFetch)

const { createEnvdFetchForRuntime } = await import('../../src/envd/http2')

expect(createEnvdFetchForRuntime('browser')).toBe(fallbackFetch)
expect(createEnvdFetchForRuntime('vercel-edge')).toBe(fallbackFetch)
})
9 changes: 9 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading