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): support AbortSignal for request cancellation (#1328)

Mish Ushakov2ac5de2edf67
diff --git a/.changeset/abort-signal-support.md b/.changeset/abort-signal-support.md
new file mode 100644
index 000000000..bbf26b660
--- /dev/null
+++ b/.changeset/abort-signal-support.md
@@ -0,0 +1,9 @@
+---
+'e2b': minor
+---
+
+Add `signal: AbortSignal` option to JS SDK methods to support cancelling in-flight requests. The signal can be passed to `Sandbox.create`, `Sandbox.connect`, `sandbox.commands.run`, `sandbox.files.*`, volume methods, and other request options. When the signal is aborted, the underlying `fetch` is aborted and the returned promise rejects with an `AbortError`.
+
+`SandboxPaginator.nextItems` and `SnapshotPaginator.nextItems` now accept a `SandboxApiOpts` argument (including `signal`) — when provided, the per-call options override the connection options the paginator was constructed with for that single request.
+
+Same change in the Python SDK: `SandboxPaginator.next_items` / `SnapshotPaginator.next_items` (sync and async) now accept `**opts: ApiParams` (e.g. `api_key`, `domain`, `headers`, `request_timeout`); when provided, the per-call options override the ones the paginator was constructed with.
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 9d2b56a77..269446dcd 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -59,7 +59,7 @@
"json2md": "^2.0.1",
"knip": "^5.43.6",
"tsup": "^8.4.0",
- "typescript": "^5.2.2",
+ "typescript": "^5.4.5",
"vitest": "^3.2.4"
},
"files": [
diff --git a/packages/js-sdk/src/connectionConfig.ts b/packages/js-sdk/src/connectionConfig.ts
index 298dff1dd..dd713cf05 100644
--- a/packages/js-sdk/src/connectionConfig.ts
+++ b/packages/js-sdk/src/connectionConfig.ts
@@ -62,6 +62,105 @@ export interface ConnectionOpts {
* Additional headers to send with the request.
*/
headers?: Record<string, string>
+
+ /**
+ * An optional `AbortSignal` that can be used to cancel the in-flight request.
+ * When the signal is aborted, the underlying `fetch` is aborted and the
+ * returned promise rejects with an `AbortError`.
+ */
+ signal?: AbortSignal
+}
+
+/**
+ * Build an `AbortSignal` that combines an optional request-timeout signal
+ * (via `AbortSignal.timeout`) with an optional user-provided signal.
+ *
+ * Returns `undefined` when neither input would produce a signal.
+ *
+ * @internal
+ */
+export function buildRequestSignal(
+ requestTimeoutMs: number | undefined,
+ userSignal: AbortSignal | undefined
+): AbortSignal | undefined {
+ const timeoutSignal = requestTimeoutMs
+ ? AbortSignal.timeout(requestTimeoutMs)
+ : undefined
+
+ if (timeoutSignal && userSignal) {
+ return AbortSignal.any([timeoutSignal, userSignal])
+ }
+
+ return timeoutSignal ?? userSignal
+}
+
+/**
+ * Set up an internal `AbortController` for a streaming request.
+ *
+ * Until `clearStartTimeout` is called, the controller aborts when either
+ * - the optional user signal aborts, or
+ * - the optional request timeout elapses (used to bound the initial
+ * handshake; long-lived streams should call `clearStartTimeout` once
+ * the handshake succeeds).
+ *
+ * The user-signal listener stays attached for the full stream lifetime
+ * so the caller can cancel a long-running stream by aborting the signal.
+ *
+ * `cleanup` is idempotent and detaches the listener, clears the handshake
+ * timer (if still pending), and aborts the controller. Call it when the
+ * stream finishes or when startup fails.
+ *
+ * @internal
+ */
+export function setupRequestController(
+ requestTimeoutMs: number | undefined,
+ userSignal: AbortSignal | undefined
+): {
+ controller: AbortController
+ clearStartTimeout: () => void
+ cleanup: () => void
+} {
+ const controller = new AbortController()
+
+ const onUserAbort = () => controller.abort(userSignal?.reason)
+ if (userSignal) {
+ if (userSignal.aborted) {
+ controller.abort(userSignal.reason)
+ } else {
+ userSignal.addEventListener('abort', onUserAbort, { once: true })
+ }
+ }
+
+ let reqTimeout: ReturnType<typeof setTimeout> | undefined = requestTimeoutMs
+ ? setTimeout(
+ () =>
+ controller.abort(
+ new DOMException(
+ `Request handshake timed out after ${requestTimeoutMs}ms`,
+ 'TimeoutError'
+ )
+ ),
+ requestTimeoutMs
+ )
+ : undefined
+
+ const clearStartTimeout = () => {
+ if (reqTimeout) {
+ clearTimeout(reqTimeout)
+ reqTimeout = undefined
+ }
+ }
+
+ let cleaned = false
+ const cleanup = () => {
+ if (cleaned) return
+ cleaned = true
+ userSignal?.removeEventListener('abort', onUserAbort)
+ clearStartTimeout()
+ controller.abort()
+ }
+
+ return { controller, clearStartTimeout, cleanup }
}
/**
@@ -125,10 +224,8 @@ export class ConnectionConfig {
return getEnvVar('E2B_ACCESS_TOKEN')
}
- getSignal(requestTimeoutMs?: number) {
- const timeout = requestTimeoutMs ?? this.requestTimeoutMs
-
- return timeout ? AbortSignal.timeout(timeout) : undefined
+ getSignal(requestTimeoutMs?: number, signal?: AbortSignal) {
+ return buildRequestSignal(requestTimeoutMs ?? this.requestTimeoutMs, signal)
}
getSandboxUrl(
diff --git a/packages/js-sdk/src/sandbox/commands/commandHandle.ts b/packages/js-sdk/src/sandbox/commands/commandHandle.ts
index 67852a900..d23adfca2 100644
--- a/packages/js-sdk/src/sandbox/commands/commandHandle.ts
+++ b/packages/js-sdk/src/sandbox/commands/commandHandle.ts
@@ -235,6 +235,8 @@ export class CommandHandle
}
} catch (e) {
this.iterationError = handleRpcError(e)
+ } finally {
+ this.handleDisconnect()
}
}
}
diff --git a/packages/js-sdk/src/sandbox/commands/index.ts b/packages/js-sdk/src/sandbox/commands/index.ts
index 61cb9e283..108a75073 100644
--- a/packages/js-sdk/src/sandbox/commands/index.ts
+++ b/packages/js-sdk/src/sandbox/commands/index.ts
@@ -12,6 +12,7 @@ import {
ConnectionOpts,
KEEPALIVE_PING_HEADER,
KEEPALIVE_PING_INTERVAL_SEC,
+ setupRequestController,
Username,
} from '../../connectionConfig'
import { handleProcessStartEvent } from '../../envd/api'
@@ -29,7 +30,7 @@ export { Pty } from './pty'
* Options for sending a command request.
*/
export interface CommandRequestOpts
- extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs'>> {}
+ extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>> {}
/**
* Options for starting a new command.
@@ -160,7 +161,10 @@ export class Commands {
const res = await this.rpc.list(
{},
{
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
@@ -209,7 +213,10 @@ export class Commands {
},
},
{
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
} catch (err) {
@@ -239,7 +246,10 @@ export class Commands {
},
},
{
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
} catch (err) {
@@ -269,7 +279,10 @@ export class Commands {
signal: Signal.SIGKILL,
},
{
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
@@ -301,13 +314,10 @@ export class Commands {
const requestTimeoutMs =
opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
- const controller = new AbortController()
-
- const reqTimeout = requestTimeoutMs
- ? setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
- : undefined
+ const { controller, clearStartTimeout, cleanup } = setupRequestController(
+ requestTimeoutMs,
+ opts?.signal
+ )
const events = this.rpc.connect(
{
@@ -329,12 +339,11 @@ export class Commands {
try {
const pid = await handleProcessStartEvent(events)
-
- clearTimeout(reqTimeout)
+ clearStartTimeout()
return new CommandHandle(
pid,
- () => controller.abort(),
+ cleanup,
() => this.kill(pid),
events,
opts?.onStdout,
@@ -342,6 +351,7 @@ export class Commands {
undefined
)
} catch (err) {
+ cleanup()
throw handleRpcError(err)
}
}
@@ -402,17 +412,6 @@ export class Commands {
cmd: string,
opts?: CommandStartOpts
): Promise<CommandHandle> {
- const requestTimeoutMs =
- opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
-
- const controller = new AbortController()
-
- const reqTimeout = requestTimeoutMs
- ? setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
- : undefined
-
if (
opts?.stdin === false &&
compareVersions(this.envdVersion, ENVD_COMMANDS_STDIN) < 0
@@ -422,6 +421,14 @@ export class Commands {
)
}
+ const requestTimeoutMs =
+ opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
+
+ const { controller, clearStartTimeout, cleanup } = setupRequestController(
+ requestTimeoutMs,
+ opts?.signal
+ )
+
const events = this.rpc.start(
{
process: {
@@ -444,12 +451,11 @@ export class Commands {
try {
const pid = await handleProcessStartEvent(events)
-
- clearTimeout(reqTimeout)
+ clearStartTimeout()
return new CommandHandle(
pid,
- () => controller.abort(),
+ cleanup,
() => this.kill(pid),
events,
opts?.onStdout,
@@ -457,6 +463,7 @@ export class Commands {
undefined
)
} catch (err) {
+ cleanup()
throw handleRpcError(err)
}
}
diff --git a/packages/js-sdk/src/sandbox/commands/pty.ts b/packages/js-sdk/src/sandbox/commands/pty.ts
index 714651c4e..089361250 100644
--- a/packages/js-sdk/src/sandbox/commands/pty.ts
+++ b/packages/js-sdk/src/sandbox/commands/pty.ts
@@ -16,13 +16,14 @@ import {
Username,
KEEPALIVE_PING_HEADER,
KEEPALIVE_PING_INTERVAL_SEC,
+ setupRequestController,
} from '../../connectionConfig'
import { CommandHandle } from './commandHandle'
import { authenticationHeader, handleRpcError } from '../../envd/rpc'
import { handleProcessStartEvent } from '../../envd/api'
export interface PtyCreateOpts
- extends Pick<ConnectionOpts, 'requestTimeoutMs'> {
+ extends Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'> {
/**
* Number of columns for the PTY.
*/
@@ -65,7 +66,7 @@ export interface PtyCreateOpts
* Options for connecting to a command.
*/
export type PtyConnectOpts = Pick<PtyCreateOpts, 'onData' | 'timeoutMs'> &
- Pick<ConnectionOpts, 'requestTimeoutMs'>
+ Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>
/**
* Module for interacting with PTYs (pseudo-terminals) in the sandbox.
@@ -101,11 +102,11 @@ export class Pty {
envs.TERM = envs.TERM ?? 'xterm-256color'
envs.LANG = envs.LANG ?? 'C.UTF-8'
envs.LC_ALL = envs.LC_ALL ?? 'C.UTF-8'
- const controller = new AbortController()
- const reqTimeout = setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
+ const { controller, clearStartTimeout, cleanup } = setupRequestController(
+ requestTimeoutMs,
+ opts?.signal
+ )
const events = this.rpc.start(
{
@@ -134,12 +135,11 @@ export class Pty {
try {
const pid = await handleProcessStartEvent(events)
-
- clearTimeout(reqTimeout)
+ clearStartTimeout()
return new CommandHandle(
pid,
- () => controller.abort(),
+ cleanup,
() => this.kill(pid),
events,
undefined,
@@ -147,6 +147,7 @@ export class Pty {
opts.onData
)
} catch (err) {
+ cleanup()
throw handleRpcError(err)
}
}
@@ -163,13 +164,10 @@ export class Pty {
const requestTimeoutMs =
opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
- const controller = new AbortController()
-
- const reqTimeout = requestTimeoutMs
- ? setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
- : undefined
+ const { controller, clearStartTimeout, cleanup } = setupRequestController(
+ requestTimeoutMs,
+ opts?.signal
+ )
const events = this.rpc.connect(
{
@@ -191,12 +189,11 @@ export class Pty {
try {
const pid = await handleProcessStartEvent(events)
-
- clearTimeout(reqTimeout)
+ clearStartTimeout()
return new CommandHandle(
pid,
- () => controller.abort(),
+ cleanup,
() => this.kill(pid),
events,
undefined,
@@ -204,6 +201,7 @@ export class Pty {
opts?.onData
)
} catch (err) {
+ cleanup()
throw handleRpcError(err)
}
}
@@ -218,7 +216,7 @@ export class Pty {
async sendInput(
pid: number,
data: Uint8Array,
- opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>
+ opts?: Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>
): Promise<void> {
try {
await this.rpc.sendInput(
@@ -237,7 +235,10 @@ export class Pty {
},
},
{
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
} catch (err) {
@@ -259,7 +260,7 @@ export class Pty {
cols: number
rows: number
},
- opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>
+ opts?: Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>
): Promise<void> {
try {
await this.rpc.update(
@@ -275,7 +276,10 @@ export class Pty {
},
},
{
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
} catch (err) {
@@ -294,7 +298,7 @@ export class Pty {
*/
async kill(
pid: number,
- opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>
+ opts?: Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>
): Promise<boolean> {
try {
await this.rpc.sendSignal(
@@ -308,7 +312,10 @@ export class Pty {
signal: Signal.SIGKILL,
},
{
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
diff --git a/packages/js-sdk/src/sandbox/filesystem/index.ts b/packages/js-sdk/src/sandbox/filesystem/index.ts
index e5d14f2b3..14e7a2e94 100644
--- a/packages/js-sdk/src/sandbox/filesystem/index.ts
+++ b/packages/js-sdk/src/sandbox/filesystem/index.ts
@@ -11,6 +11,7 @@ import {
defaultUsername,
KEEPALIVE_PING_HEADER,
KEEPALIVE_PING_INTERVAL_SEC,
+ setupRequestController,
Username,
} from '../../connectionConfig'
@@ -156,7 +157,7 @@ function mapModifiedTime(modifiedTime: Timestamp | undefined) {
* Options for the sandbox filesystem operations.
*/
export interface FilesystemRequestOpts
- extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs'>> {
+ extends Partial<Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>> {
/**
* User to use for the operation in the sandbox.
* This affects the resolution of relative paths and ownership of the created filesystem objects.
@@ -325,7 +326,10 @@ export class Filesystem {
},
},
parseAs: format === 'bytes' ? 'arrayBuffer' : format,
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
headers,
})
@@ -454,7 +458,8 @@ export class Filesystem {
bodySerializer: () => body,
headers,
signal: this.connectionConfig.getSignal(
- writeOpts?.requestTimeoutMs
+ writeOpts?.requestTimeoutMs,
+ writeOpts?.signal
),
body: {},
})
@@ -496,7 +501,10 @@ export class Filesystem {
},
},
bodySerializer: () => formData,
- signal: this.connectionConfig.getSignal(writeOpts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ writeOpts?.requestTimeoutMs,
+ writeOpts?.signal
+ ),
body: {},
})
@@ -559,7 +567,10 @@ export class Filesystem {
},
{
headers: authenticationHeader(this.envdApi.version, opts?.user),
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
@@ -604,7 +615,10 @@ export class Filesystem {
{ path },
{
headers: authenticationHeader(this.envdApi.version, opts?.user),
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
@@ -642,7 +656,10 @@ export class Filesystem {
},
{
headers: authenticationHeader(this.envdApi.version, opts?.user),
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
@@ -680,7 +697,10 @@ export class Filesystem {
{ path },
{
headers: authenticationHeader(this.envdApi.version, opts?.user),
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
} catch (err) {
@@ -702,7 +722,10 @@ export class Filesystem {
{ path },
{
headers: authenticationHeader(this.envdApi.version, opts?.user),
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
@@ -735,7 +758,10 @@ export class Filesystem {
{ path },
{
headers: authenticationHeader(this.envdApi.version, opts?.user),
- signal: this.connectionConfig.getSignal(opts?.requestTimeoutMs),
+ signal: this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ ),
}
)
@@ -792,13 +818,10 @@ export class Filesystem {
const requestTimeoutMs =
opts?.requestTimeoutMs ?? this.connectionConfig.requestTimeoutMs
- const controller = new AbortController()
-
- const reqTimeout = requestTimeoutMs
- ? setTimeout(() => {
- controller.abort()
- }, requestTimeoutMs)
- : undefined
+ const { controller, clearStartTimeout, cleanup } = setupRequestController(
+ requestTimeoutMs,
+ opts?.signal
+ )
const events = this.rpc.watchDir(
{
@@ -817,16 +840,11 @@ export class Filesystem {
try {
await handleWatchDirStartEvent(events)
+ clearStartTimeout()
- clearTimeout(reqTimeout)
-
- return new WatchHandle(
- () => controller.abort(),
- events,
- onEvent,
- opts?.onExit
- )
+ return new WatchHandle(cleanup, events, onEvent, opts?.onExit)
} catch (err) {
+ cleanup()
throw handleFilesystemRpcError(err)
}
}
diff --git a/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts b/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
index 40dce4f15..6d4bd80e8 100644
--- a/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
+++ b/packages/js-sdk/src/sandbox/filesystem/watchHandle.ts
@@ -111,6 +111,8 @@ export class WatchHandle {
this.onExit?.()
} catch (err) {
this.onExit?.(err as Error)
+ } finally {
+ this.handleStop()
}
}
}
diff --git a/packages/js-sdk/src/sandbox/index.ts b/packages/js-sdk/src/sandbox/index.ts
index 0f10f060a..54b2a82d2 100644
--- a/packages/js-sdk/src/sandbox/index.ts
+++ b/packages/js-sdk/src/sandbox/index.ts
@@ -522,9 +522,12 @@ export class Sandbox extends SandboxApi {
* ```
*/
async isRunning(
- opts?: Pick<ConnectionOpts, 'requestTimeoutMs'>
+ opts?: Pick<ConnectionOpts, 'requestTimeoutMs' | 'signal'>
): Promise<boolean> {
- const signal = this.connectionConfig.getSignal(opts?.requestTimeoutMs)
+ const signal = this.connectionConfig.getSignal(
+ opts?.requestTimeoutMs,
+ opts?.signal
+ )
const res = await this.envdApi.api.GET('/health', {
signal,
@@ -553,7 +556,7 @@ export class Sandbox extends SandboxApi {
*/
async setTimeout(
timeoutMs: number,
- opts?: Pick<SandboxOpts, 'requestTimeoutMs'>
+ opts?: Pick<SandboxOpts, 'requestTimeoutMs' | 'signal'>
) {
if (this.connectionConfig.debug) {
// Skip timeout in debug mode
@@ -572,7 +575,7 @@ export class Sandbox extends SandboxApi {
*
* @param opts connection options.
*/
- async kill(opts?: Pick<SandboxOpts, 'requestTimeoutMs'>) {
+ async kill(opts?: Pick<SandboxOpts, 'requestTimeoutMs' | 'signal'>) {
if (this.connectionConfig.debug) {
// Skip killing in debug mode
return
@@ -788,7 +791,7 @@ export class Sandbox extends SandboxApi {
*
* @returns information about the sandbox
*/
- async getInfo(opts?: Pick<SandboxOpts, 'requestTimeoutMs'>) {
+ async getInfo(opts?: Pick<SandboxOpts, 'requestTimeoutMs' | 'signal'>) {
return await SandboxApi.getInfo(this.sandboxId, this.resolveApiOpts(opts))
}
diff --git a/packages/js-sdk/src/sandbox/sandboxApi.ts b/packages/js-sdk/src/sandbox/sandboxApi.ts
index 404eb81c7..0ab54ab7e 100644
--- a/packages/js-sdk/src/sandbox/sandboxApi.ts
+++ b/packages/js-sdk/src/sandbox/sandboxApi.ts
@@ -99,7 +99,7 @@ export interface SandboxApiOpts
extends Partial<
Pick<
ConnectionOpts,
- 'apiKey' | 'headers' | 'debug' | 'domain' | 'requestTimeoutMs'
+ 'apiKey' | 'headers' | 'debug' | 'domain' | 'requestTimeoutMs' | 'signal'
>
> {}
@@ -214,7 +214,7 @@ export type SandboxConnectOpts = ConnectionOpts & {
*/
export type SandboxState = 'running' | 'paused'
-export interface SandboxListOpts extends SandboxApiOpts {
+export interface SandboxListOpts extends Omit<SandboxApiOpts, 'signal'> {
/**
* Filter the list of sandboxes, e.g. by metadata `metadata:{"key": "value"}`, if there are multiple filters they are combined with AND.
*
@@ -255,7 +255,7 @@ export interface SandboxMetricsOpts extends SandboxApiOpts {
/**
* Options for listing snapshots.
*/
-export interface SnapshotListOpts extends SandboxApiOpts {
+export interface SnapshotListOpts extends Omit<SandboxApiOpts, 'signal'> {
/**
* Filter snapshots by source sandbox ID.
*/
@@ -463,7 +463,7 @@ export class SandboxApi {
sandboxID: sandboxId,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.error?.code === 404) {
@@ -525,7 +525,7 @@ export class SandboxApi {
end,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
const err = handleApiError(res)
@@ -575,7 +575,7 @@ export class SandboxApi {
body: {
timeout: timeoutToSeconds(timeoutMs),
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.error?.code === 404) {
@@ -598,7 +598,7 @@ export class SandboxApi {
sandboxID: sandboxId,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.error?.code === 404) {
@@ -667,7 +667,7 @@ export class SandboxApi {
sandboxID: sandboxId,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.error?.code === 404) {
@@ -723,7 +723,7 @@ export class SandboxApi {
},
},
body: opts?.name ? { name: opts.name } : {},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.error?.code === 404) {
@@ -773,7 +773,7 @@ export class SandboxApi {
templateID: snapshotId,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.error?.code === 404) {
@@ -828,7 +828,7 @@ export class SandboxApi {
const res = await client.api.POST('/sandboxes', {
body,
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
const err = handleApiError(res)
@@ -871,7 +871,7 @@ export class SandboxApi {
body: {
timeout: timeoutToSeconds(timeoutMs),
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.error?.code === 404) {
@@ -894,21 +894,18 @@ export class SandboxApi {
}
abstract class BasePaginator<T> {
- protected readonly config: ConnectionConfig
- protected client: ApiClient
+ protected readonly opts?: SandboxApiOpts
protected readonly limit?: number
private _hasNext: boolean
private _nextToken?: string
- constructor(config: ConnectionConfig, limit?: number, nextToken?: string) {
- this.config = config
- this.client = new ApiClient(this.config)
+ constructor(opts?: SandboxApiOpts, limit?: number, nextToken?: string) {
+ this.opts = opts
+ this.limit = limit
this._hasNext = true
this._nextToken = nextToken
-
- this.limit = limit
}
/**
@@ -933,11 +930,17 @@ abstract class BasePaginator<T> {
/**
* Get the next page of items.
*
+ * @param opts per-call connection options. When provided, this call uses
+ * these options (e.g. `apiKey`, `domain`, `headers`, `requestTimeoutMs`,
+ * `signal`) instead of the ones the paginator was constructed with.
+ * Aborting a page via `signal` does not affect subsequent {@link BasePaginator.nextItems}
+ * calls — pass a fresh signal each call you want to be cancellable.
+ *
* @throws Error if there are no more items to fetch. Call this method only if `hasNext` is `true`.
*
* @returns List of items
*/
- abstract nextItems(): Promise<T[]>
+ abstract nextItems(opts?: SandboxApiOpts): Promise<T[]>
}
/**
@@ -956,12 +959,12 @@ export class SandboxPaginator extends BasePaginator<SandboxInfo> {
private query: SandboxListOpts['query']
constructor(opts?: SandboxListOpts) {
- super(new ConnectionConfig(opts), opts?.limit, opts?.nextToken)
+ super(opts, opts?.limit, opts?.nextToken)
this.query = opts?.query
}
- async nextItems(): Promise<SandboxInfo[]> {
+ async nextItems(opts?: SandboxApiOpts): Promise<SandboxInfo[]> {
if (!this.hasNext) {
throw new Error('No more items to fetch')
}
@@ -978,7 +981,10 @@ export class SandboxPaginator extends BasePaginator<SandboxInfo> {
metadata = new URLSearchParams(encodedPairs).toString()
}
- const res = await this.client.api.GET('/v2/sandboxes', {
+ const config = new ConnectionConfig({ ...this.opts, ...opts })
+ const client = new ApiClient(config)
+
+ const res = await client.api.GET('/v2/sandboxes', {
params: {
query: {
metadata,
@@ -987,8 +993,7 @@ export class SandboxPaginator extends BasePaginator<SandboxInfo> {
nextToken: this.nextToken,
},
},
- // requestTimeoutMs is already passed here via the connectionConfig.
- signal: this.config.getSignal(),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
const err = handleApiError(res)
@@ -1032,17 +1037,20 @@ export class SnapshotPaginator extends BasePaginator<SnapshotInfo> {
private readonly sandboxId?: string
constructor(opts?: SnapshotListOpts) {
- super(new ConnectionConfig(opts), opts?.limit, opts?.nextToken)
+ super(opts, opts?.limit, opts?.nextToken)
this.sandboxId = opts?.sandboxId
}
- async nextItems(): Promise<SnapshotInfo[]> {
+ async nextItems(opts?: SandboxApiOpts): Promise<SnapshotInfo[]> {
if (!this.hasNext) {
throw new Error('No more items to fetch')
}
- const res = await this.client.api.GET('/snapshots', {
+ const config = new ConnectionConfig({ ...this.opts, ...opts })
+ const client = new ApiClient(config)
+
+ const res = await client.api.GET('/snapshots', {
params: {
query: {
sandboxID: this.sandboxId,
@@ -1050,7 +1058,7 @@ export class SnapshotPaginator extends BasePaginator<SnapshotInfo> {
nextToken: this.nextToken,
},
},
- signal: this.config.getSignal(),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
const err = handleApiError(res)
diff --git a/packages/js-sdk/src/volume/client.ts b/packages/js-sdk/src/volume/client.ts
index 1cf71a821..22b04afcc 100644
--- a/packages/js-sdk/src/volume/client.ts
+++ b/packages/js-sdk/src/volume/client.ts
@@ -2,6 +2,7 @@ import createClient from 'openapi-fetch'
import type { components, paths } from './schema.gen'
import { defaultHeaders, getEnvVar } from '../api/metadata'
+import { buildRequestSignal } from '../connectionConfig'
import { createApiLogger, Logger } from '../logs'
import type { Volume } from './index'
@@ -47,6 +48,13 @@ export interface VolumeApiOpts {
* Additional headers to send with the request.
*/
headers?: Record<string, string>
+
+ /**
+ * An optional `AbortSignal` that can be used to cancel the in-flight request.
+ * When the signal is aborted, the underlying `fetch` is aborted and the
+ * returned promise rejects with an `AbortError`.
+ */
+ signal?: AbortSignal
}
export class VolumeConnectionConfig {
@@ -83,10 +91,8 @@ export class VolumeConnectionConfig {
return getEnvVar('E2B_VOLUME_API_URL')
}
- getSignal(requestTimeoutMs?: number) {
- const timeout = requestTimeoutMs ?? this.requestTimeoutMs
-
- return timeout ? AbortSignal.timeout(timeout) : undefined
+ getSignal(requestTimeoutMs?: number, signal?: AbortSignal) {
+ return buildRequestSignal(requestTimeoutMs ?? this.requestTimeoutMs, signal)
}
}
diff --git a/packages/js-sdk/src/volume/index.ts b/packages/js-sdk/src/volume/index.ts
index 029049df7..0e8bcab00 100644
--- a/packages/js-sdk/src/volume/index.ts
+++ b/packages/js-sdk/src/volume/index.ts
@@ -104,7 +104,7 @@ export class Volume {
body: {
name,
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
const err = handleApiError(res, VolumeError)
@@ -163,7 +163,7 @@ export class Volume {
volumeID: volumeId,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.response.status === 404) {
@@ -194,7 +194,7 @@ export class Volume {
const client = new ApiClient(config)
const res = await client.api.GET('/volumes', {
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
const err = handleApiError(res, VolumeError)
@@ -227,7 +227,7 @@ export class Volume {
volumeID: volumeId,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.response.status === 404) {
@@ -268,7 +268,7 @@ export class Volume {
depth: opts?.depth,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.response.status === 404) {
@@ -312,7 +312,7 @@ export class Volume {
force: opts?.force,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.response.status === 404) {
@@ -354,7 +354,7 @@ export class Volume {
path,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.response.status === 404) {
@@ -429,7 +429,7 @@ export class Volume {
gid: metadata.gid,
mode: metadata.mode,
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.response.status === 404) {
@@ -530,7 +530,10 @@ export class Volume {
},
},
parseAs: format === 'bytes' ? 'arrayBuffer' : format,
- signal: config.getSignal(opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS),
+ signal: config.getSignal(
+ opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS,
+ opts?.signal
+ ),
})
if (res.response.status === 404) {
@@ -599,7 +602,10 @@ export class Volume {
headers: {
'Content-Type': 'application/octet-stream',
},
- signal: config.getSignal(opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS),
+ signal: config.getSignal(
+ opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS,
+ opts?.signal
+ ),
})
if (res.response.status === 404) {
@@ -639,7 +645,7 @@ export class Volume {
path,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs),
+ signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
})
if (res.response.status === 404) {
diff --git a/packages/js-sdk/tests/connectionConfig.test.ts b/packages/js-sdk/tests/connectionConfig.test.ts
index cfaafc77f..4a01900e0 100644
--- a/packages/js-sdk/tests/connectionConfig.test.ts
+++ b/packages/js-sdk/tests/connectionConfig.test.ts
@@ -1,5 +1,8 @@
import { assert, test, beforeEach, afterEach } from 'vitest'
-import { ConnectionConfig } from '../src/connectionConfig'
+import {
+ ConnectionConfig,
+ setupRequestController,
+} from '../src/connectionConfig'
// Store original env vars to restore after tests
let originalEnv: { [key: string]: string | undefined }
@@ -51,3 +54,104 @@ test('api_url has correct priority', () => {
const config = new ConnectionConfig({ apiUrl: 'http://localhost:8080' })
assert.equal(config.apiUrl, 'http://localhost:8080')
})
+
+test('getSignal returns user signal when no timeout is set', () => {
+ const config = new ConnectionConfig({ requestTimeoutMs: 0 })
+ const controller = new AbortController()
+ const signal = config.getSignal(0, controller.signal)
+ assert.strictEqual(signal, controller.signal)
+})
+
+test('getSignal aborts when user signal is aborted', () => {
+ const config = new ConnectionConfig({ requestTimeoutMs: 60_000 })
+ const controller = new AbortController()
+ const signal = config.getSignal(undefined, controller.signal)
+ assert.ok(signal)
+ assert.equal(signal!.aborted, false)
+ controller.abort()
+ assert.equal(signal!.aborted, true)
+})
+
+test('getSignal returns timeout signal when no user signal is provided', () => {
+ const config = new ConnectionConfig({ requestTimeoutMs: 60_000 })
+ const signal = config.getSignal()
+ assert.ok(signal)
+ assert.equal(signal!.aborted, false)
+})
+
+test('getSignal returns undefined when no timeout and no signal', () => {
+ const config = new ConnectionConfig({ requestTimeoutMs: 0 })
+ const signal = config.getSignal(0)
+ assert.equal(signal, undefined)
+})
+
+test('setupRequestController aborts when user signal aborts', () => {
+ const userController = new AbortController()
+ const { controller } = setupRequestController(0, userController.signal)
+
+ assert.equal(controller.signal.aborted, false)
+ userController.abort()
+ assert.equal(controller.signal.aborted, true)
+})
+
+test('setupRequestController is already aborted when user signal was pre-aborted', () => {
+ const userController = new AbortController()
+ userController.abort()
+
+ const { controller } = setupRequestController(0, userController.signal)
+ assert.equal(controller.signal.aborted, true)
+})
+
+test('setupRequestController cleanup removes the user-signal listener', () => {
+ const userController = new AbortController()
+ const { controller, cleanup } = setupRequestController(
+ 0,
+ userController.signal
+ )
+
+ cleanup()
+ // Internal controller is aborted by cleanup, so it stays aborted.
+ assert.equal(controller.signal.aborted, true)
+
+ // After cleanup the listener is detached — a subsequent abort on the
+ // user signal must not propagate (verified indirectly: cleanup is
+ // idempotent and no error is thrown).
+ userController.abort()
+ cleanup()
+})
+
+test('setupRequestController clearStartTimeout stops the handshake timer', async () => {
+ const { controller, clearStartTimeout } = setupRequestController(
+ 20,
+ undefined
+ )
+ clearStartTimeout()
+ await new Promise((resolve) => setTimeout(resolve, 40))
+ assert.equal(controller.signal.aborted, false)
+})
+
+test('setupRequestController handshake timer aborts when not cleared', async () => {
+ const { controller } = setupRequestController(20, undefined)
+ await new Promise((resolve) => setTimeout(resolve, 40))
+ assert.equal(controller.signal.aborted, true)
+})
+
+test('setupRequestController handshake timeout aborts with TimeoutError reason', async () => {
+ const { controller } = setupRequestController(20, undefined)
+ await new Promise((resolve) => setTimeout(resolve, 40))
+ assert.equal(controller.signal.aborted, true)
+ assert.ok(controller.signal.reason instanceof DOMException)
+ assert.equal((controller.signal.reason as DOMException).name, 'TimeoutError')
+})
+
+test('setupRequestController user signal still cancels after clearStartTimeout', () => {
+ const userController = new AbortController()
+ const { controller, clearStartTimeout } = setupRequestController(
+ 60_000,
+ userController.signal
+ )
+ clearStartTimeout()
+ assert.equal(controller.signal.aborted, false)
+ userController.abort()
+ assert.equal(controller.signal.aborted, true)
+})
diff --git a/packages/js-sdk/tests/sandbox/abortSignal.test.ts b/packages/js-sdk/tests/sandbox/abortSignal.test.ts
new file mode 100644
index 000000000..fda6e2636
--- /dev/null
+++ b/packages/js-sdk/tests/sandbox/abortSignal.test.ts
@@ -0,0 +1,114 @@
+import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'
+import { http, HttpResponse } from 'msw'
+import { setupServer } from 'msw/node'
+
+import { Sandbox } from '../../src'
+import { apiUrl } from '../setup'
+
+// Hold the request open until the caller aborts. If the signal is already
+// aborted by the time the handler runs, `addEventListener('abort', …)` would
+// never fire — so check `aborted` first to avoid hanging.
+function holdUntilAborted(signal: AbortSignal): Promise<never> {
+ return new Promise<never>((_, reject) => {
+ const abort = () => reject(new DOMException('aborted', 'AbortError'))
+ if (signal.aborted) {
+ abort()
+ return
+ }
+ signal.addEventListener('abort', abort, { once: true })
+ })
+}
+
+const restHandlers = [
+ http.post(apiUrl('/sandboxes'), async ({ request }) => {
+ await holdUntilAborted(request.signal)
+ return HttpResponse.json({})
+ }),
+ http.delete(apiUrl('/sandboxes/:sandboxID'), async ({ request }) => {
+ await holdUntilAborted(request.signal)
+ return HttpResponse.json({})
+ }),
+ http.get(apiUrl('/v2/sandboxes'), async ({ request }) => {
+ await holdUntilAborted(request.signal)
+ return HttpResponse.json([])
+ }),
+]
+
+const server = setupServer(...restHandlers)
+
+beforeAll(() =>
+ server.listen({
+ onUnhandledRequest: 'bypass',
+ })
+)
+
+afterAll(() => server.close())
+
+afterEach(() => server.resetHandlers())
+
+// Resolves once MSW has dispatched the next request, so tests can abort
+// deterministically instead of guessing with `setTimeout`.
+function nextRequestStart(): Promise<void> {
+ return new Promise<void>((resolve) => {
+ const listener = () => {
+ server.events.removeListener('request:start', listener)
+ resolve()
+ }
+ server.events.on('request:start', listener)
+ })
+}
+
+test('Sandbox.create rejects when AbortSignal is aborted', async () => {
+ const controller = new AbortController()
+ const requestStarted = nextRequestStart()
+
+ const promise = Sandbox.create('base', {
+ apiKey: 'test-key',
+ signal: controller.signal,
+ })
+
+ await requestStarted
+ controller.abort()
+
+ await expect(promise).rejects.toThrow()
+})
+
+test('Sandbox.create rejects immediately when signal is already aborted', async () => {
+ const controller = new AbortController()
+ controller.abort()
+
+ await expect(
+ Sandbox.create('base', {
+ apiKey: 'test-key',
+ signal: controller.signal,
+ })
+ ).rejects.toThrow()
+})
+
+test('Sandbox.kill rejects when AbortSignal is aborted', async () => {
+ const controller = new AbortController()
+ const requestStarted = nextRequestStart()
+
+ const promise = Sandbox.kill('some-sandbox', {
+ apiKey: 'test-key',
+ signal: controller.signal,
+ })
+
+ await requestStarted
+ controller.abort()
+
+ await expect(promise).rejects.toThrow()
+})
+
+test('SandboxPaginator.nextItems rejects when per-call AbortSignal is aborted', async () => {
+ const controller = new AbortController()
+ const requestStarted = nextRequestStart()
+
+ const paginator = Sandbox.list({ apiKey: 'test-key' })
+ const promise = paginator.nextItems({ signal: controller.signal })
+
+ await requestStarted
+ controller.abort()
+
+ await expect(promise).rejects.toThrow()
+})
diff --git a/packages/python-sdk/e2b/sandbox/sandbox_api.py b/packages/python-sdk/e2b/sandbox/sandbox_api.py
index 9c8c0ee34..fc8b47868 100644
--- a/packages/python-sdk/e2b/sandbox/sandbox_api.py
+++ b/packages/python-sdk/e2b/sandbox/sandbox_api.py
@@ -4,7 +4,6 @@ from typing import Any, Dict, List, Literal, Optional, TypedDict, Union, cast
from typing_extensions import NotRequired, Unpack
-from e2b import ConnectionConfig
from e2b.api.client.models import (
ListedSandbox,
SandboxDetail,
@@ -307,7 +306,7 @@ class PaginatorBase:
next_token: Optional[str] = None,
**opts: Unpack[ApiParams],
):
- self._config = ConnectionConfig(**opts)
+ self._opts: ApiParams = opts
self.limit = limit
self._has_next = True
self._next_token = next_token
diff --git a/packages/python-sdk/e2b/sandbox_async/paginator.py b/packages/python-sdk/e2b/sandbox_async/paginator.py
index 2533b5e29..451ff7e55 100644
--- a/packages/python-sdk/e2b/sandbox_async/paginator.py
+++ b/packages/python-sdk/e2b/sandbox_async/paginator.py
@@ -1,9 +1,12 @@
import urllib.parse
from typing import Optional, List
+from typing_extensions import Unpack
+
from e2b.api.client.api.sandboxes import get_v2_sandboxes
from e2b.api.client.api.snapshots import get_snapshots
from e2b.api.client.types import UNSET
+from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.exceptions import SandboxException
from e2b.sandbox.sandbox_api import (
SandboxPaginatorBase,
@@ -30,12 +33,16 @@ class AsyncSandboxPaginator(SandboxPaginatorBase):
```
"""
- async def next_items(self) -> List[SandboxInfo]:
+ async def next_items(self, **opts: Unpack[ApiParams]) -> List[SandboxInfo]:
"""
Returns the next page of sandboxes.
Call this method only if `has_next` is `True`, otherwise it will raise an exception.
+ :param opts: Per-call connection options (e.g. `api_key`, `domain`,
+ `headers`, `request_timeout`). When provided, this call uses these
+ options instead of the ones the paginator was constructed with.
+
:returns: List of sandboxes
"""
if not self.has_next:
@@ -50,7 +57,8 @@ class AsyncSandboxPaginator(SandboxPaginatorBase):
}
metadata = urllib.parse.urlencode(quoted_metadata)
- api_client = get_api_client(self._config)
+ config = ConnectionConfig(**{**self._opts, **opts})
+ api_client = get_api_client(config)
res = await get_v2_sandboxes.asyncio_detailed(
client=api_client,
metadata=metadata if metadata else UNSET,
@@ -89,18 +97,23 @@ class AsyncSnapshotPaginator(SnapshotPaginatorBase):
```
"""
- async def next_items(self) -> List[SnapshotInfo]:
+ async def next_items(self, **opts: Unpack[ApiParams]) -> List[SnapshotInfo]:
"""
Returns the next page of snapshots.
Call this method only if `has_next` is `True`, otherwise it will raise an exception.
+ :param opts: Per-call connection options (e.g. `api_key`, `domain`,
+ `headers`, `request_timeout`). When provided, this call uses these
+ options instead of the ones the paginator was constructed with.
+
:returns: List of snapshots
"""
if not self.has_next:
raise Exception("No more items to fetch")
- api_client = get_api_client(self._config)
+ config = ConnectionConfig(**{**self._opts, **opts})
+ api_client = get_api_client(config)
res = await get_snapshots.asyncio_detailed(
client=api_client,
sandbox_id=self.sandbox_id if self.sandbox_id else UNSET,
diff --git a/packages/python-sdk/e2b/sandbox_sync/paginator.py b/packages/python-sdk/e2b/sandbox_sync/paginator.py
index 4f0fb454c..464de6644 100644
--- a/packages/python-sdk/e2b/sandbox_sync/paginator.py
+++ b/packages/python-sdk/e2b/sandbox_sync/paginator.py
@@ -1,11 +1,14 @@
import urllib.parse
from typing import Optional, List
+from typing_extensions import Unpack
+
from e2b.api import handle_api_exception
from e2b.api.client.api.sandboxes import get_v2_sandboxes
from e2b.api.client.api.snapshots import get_snapshots
from e2b.api.client.models.error import Error
from e2b.api.client.types import UNSET
+from e2b.connection_config import ApiParams, ConnectionConfig
from e2b.exceptions import SandboxException
from e2b.sandbox.sandbox_api import (
SandboxPaginatorBase,
@@ -30,12 +33,16 @@ class SandboxPaginator(SandboxPaginatorBase):
```
"""
- def next_items(self) -> List[SandboxInfo]:
+ def next_items(self, **opts: Unpack[ApiParams]) -> List[SandboxInfo]:
"""
Returns the next page of sandboxes.
Call this method only if `has_next` is `True`, otherwise it will raise an exception.
+ :param opts: Per-call connection options (e.g. `api_key`, `domain`,
+ `headers`, `request_timeout`). When provided, this call uses these
+ options instead of the ones the paginator was constructed with.
+
:returns: List of sandboxes
"""
if not self.has_next:
@@ -50,7 +57,8 @@ class SandboxPaginator(SandboxPaginatorBase):
}
metadata = urllib.parse.urlencode(quoted_metadata)
- api_client = get_api_client(self._config)
+ config = ConnectionConfig(**{**self._opts, **opts})
+ api_client = get_api_client(config)
res = get_v2_sandboxes.sync_detailed(
client=api_client,
metadata=metadata if metadata else UNSET,
@@ -89,18 +97,23 @@ class SnapshotPaginator(SnapshotPaginatorBase):
```
"""
- def next_items(self) -> List[SnapshotInfo]:
+ def next_items(self, **opts: Unpack[ApiParams]) -> List[SnapshotInfo]:
"""
Returns the next page of snapshots.
Call this method only if `has_next` is `True`, otherwise it will raise an exception.
+ :param opts: Per-call connection options (e.g. `api_key`, `domain`,
+ `headers`, `request_timeout`). When provided, this call uses these
+ options instead of the ones the paginator was constructed with.
+
:returns: List of snapshots
"""
if not self.has_next:
raise Exception("No more items to fetch")
- api_client = get_api_client(self._config)
+ config = ConnectionConfig(**{**self._opts, **opts})
+ api_client = get_api_client(config)
res = get_snapshots.sync_detailed(
client=api_client,
sandbox_id=self.sandbox_id if self.sandbox_id else UNSET,
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index bab886b33..c87245e8a 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -135,16 +135,16 @@ importers:
version: 2.0.1
knip:
specifier: ^5.43.6
- version: 5.43.6(@types/[email protected])([email protected])
+ version: 5.43.6(@types/[email protected])([email protected])
tsup:
specifier: ^8.4.0
typescript:
- specifier: ^5.2.2
- version: 5.2.2
+ specifier: ^5.4.5
+ version: 5.5.3
vitest:
specifier: ^3.2.4
packages/js-sdk:
dependencies:
@@ -3412,11 +3412,6 @@ packages:
resolution: {integrity: sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==}
engines: {node: '>= 0.4'}
- resolution: {integrity: sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==}
- engines: {node: '>=14.17'}
- hasBin: true
-
resolution: {integrity: sha512-/hreyEujaB0w76zKo6717l3L0o/qEUtRgdvUBvlkhoWeOVMjMuHNHk0BRBzikzuGDqNmPQbg5ifMEqsHLiIUcQ==}
engines: {node: '>=14.17'}
@@ -4690,26 +4685,6 @@ snapshots:
transitivePeerDependencies:
- supports-color
- dependencies:
- '@testing-library/dom': 10.4.0
- '@testing-library/user-event': 14.6.1(@testing-library/[email protected])
- '@vitest/utils': 3.2.4
- magic-string: 0.30.17
- sirv: 3.0.1
- tinyrainbow: 2.0.0
- optionalDependencies:
- playwright: 1.55.1
- transitivePeerDependencies:
- - bufferutil
- - msw
- - utf-8-validate
- - vite
- optional: true
-
dependencies:
'@testing-library/dom': 10.4.0
@@ -4744,9 +4719,9 @@ snapshots:
std-env: 3.9.0
test-exclude: 7.0.1
tinyrainbow: 2.0.0
optionalDependencies:
transitivePeerDependencies:
- supports-color
@@ -4758,15 +4733,6 @@ snapshots:
chai: 5.2.0
tinyrainbow: 2.0.0
- dependencies:
- '@vitest/spy': 3.2.4
- estree-walker: 3.0.3
- magic-string: 0.30.17
- optionalDependencies:
- msw: 2.12.14(@types/[email protected])([email protected])
-
dependencies:
'@vitest/spy': 3.2.4
@@ -6037,27 +6003,6 @@ snapshots:
dependencies:
json-buffer: 3.0.1
- dependencies:
- '@nodelib/fs.walk': 3.0.1
- '@snyk/github-codeowners': 1.1.0
- '@types/node': 20.19.19
- easy-table: 1.2.0
- enhanced-resolve: 5.18.1
- fast-glob: 3.3.3
- jiti: 2.4.2
- js-yaml: 4.1.1
- minimist: 1.2.8
- picocolors: 1.1.1
- picomatch: 4.0.4
- pretty-ms: 9.1.0
- smol-toml: 1.6.1
- strip-json-comments: 5.0.1
- summary: 2.1.0
- typescript: 5.2.2
- zod: 3.22.4
- zod-validation-error: 3.4.0([email protected])
-
dependencies:
'@nodelib/fs.walk': 3.0.1
@@ -6188,32 +6133,6 @@ snapshots:
- dependencies:
- '@inquirer/confirm': 5.1.19(@types/[email protected])
- '@mswjs/interceptors': 0.41.3
- '@open-draft/deferred-promise': 2.2.0
- '@types/statuses': 2.0.6
- cookie: 1.1.1
- graphql: 16.12.0
- headers-polyfill: 4.0.3
- is-node-process: 1.2.0
- outvariant: 1.4.3
- path-to-regexp: 6.3.0
- picocolors: 1.1.1
- rettime: 0.10.1
- statuses: 2.0.2
- strict-event-emitter: 0.5.1
- tough-cookie: 6.0.0
- type-fest: 5.2.0
- until-async: 3.0.2
- yargs: 17.7.2
- optionalDependencies:
- typescript: 5.2.2
- transitivePeerDependencies:
- - '@types/node'
- optional: true
-
dependencies:
'@inquirer/confirm': 5.1.19(@types/[email protected])
@@ -7016,33 +6935,6 @@ snapshots:
- dependencies:
- bundle-require: 5.1.0([email protected])
- cac: 6.7.14
- chokidar: 4.0.3
- consola: 3.4.2
- debug: 4.4.0
- esbuild: 0.25.0
- joycon: 3.1.1
- picocolors: 1.1.1
- postcss-load-config: 6.0.1([email protected])([email protected])
- resolve-from: 5.0.0
- rollup: 4.60.0
- source-map: 0.8.0-beta.0
- sucrase: 3.35.0
- tinyexec: 0.3.2
- tinyglobby: 0.2.13
- tree-kill: 1.2.2
- optionalDependencies:
- postcss: 8.5.12
- typescript: 5.2.2
- transitivePeerDependencies:
- - jiti
- - supports-color
- - tsx
- - yaml
-
dependencies:
bundle-require: 5.1.0([email protected])
@@ -7117,8 +7009,6 @@ snapshots:
possible-typed-array-names: 1.1.0
reflect.getprototypeof: 1.0.10
-
@@ -7216,48 +7106,6 @@ snapshots:
'@types/react': 18.3.11
'@types/react-dom': 18.3.1
- dependencies:
- '@types/chai': 5.2.2
- '@vitest/expect': 3.2.4
- '@vitest/pretty-format': 3.2.4
- '@vitest/runner': 3.2.4
- '@vitest/snapshot': 3.2.4
- '@vitest/spy': 3.2.4
- '@vitest/utils': 3.2.4
- chai: 5.2.0
- debug: 4.4.3([email protected])
- expect-type: 1.2.1
- magic-string: 0.30.17
- pathe: 2.0.3
- picomatch: 4.0.4
- std-env: 3.9.0
- tinybench: 2.9.0
- tinyexec: 0.3.2
- tinyglobby: 0.2.15
- tinypool: 1.1.1
- tinyrainbow: 2.0.0
- why-is-node-running: 2.3.0
- optionalDependencies:
- '@types/node': 20.19.19
- transitivePeerDependencies:
- - jiti
- - less
- - lightningcss
- - msw
- - sass
- - sass-embedded
- - stylus
- - sugarss
- - supports-color
- - terser
- - tsx
- - yaml
-
dependencies:
'@types/chai': 5.2.2