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 Template operations (#1339)

Mish Ushakovba315c079573
diff --git a/.changeset/beige-parts-swim.md b/.changeset/beige-parts-swim.md
new file mode 100644
index 000000000..79361cdd3
--- /dev/null
+++ b/.changeset/beige-parts-swim.md
@@ -0,0 +1,5 @@
+---
+'e2b': patch
+---
+
+Add `signal: AbortSignal` option to `Template.build`, `Template.buildInBackground`, `Template.getBuildStatus`, `Template.exists`, `Template.aliasExists`, `Template.assignTags`, `Template.removeTags`, and `Template.getTags`. When the signal is aborted, the underlying request (and, for `Template.build`, the status polling loop) is cancelled and the returned promise rejects with an `AbortError`.
diff --git a/packages/js-sdk/src/template/buildApi.ts b/packages/js-sdk/src/template/buildApi.ts
index b070d2bbb..cd5d53f95 100644
--- a/packages/js-sdk/src/template/buildApi.ts
+++ b/packages/js-sdk/src/template/buildApi.ts
@@ -1,6 +1,8 @@
import { ApiClient, handleApiError, paths, components } from '../api'
+import { buildRequestSignal } from '../connectionConfig'
import { dynamicImport, stripAnsi } from '../utils'
import { BuildError, FileUploadError, TemplateError } from '../errors'
+import { FILE_UPLOAD_TIMEOUT_MS } from './consts'
import { LogEntry } from './logger'
import { getBuildStepIndex, tarFileStreamUpload } from './utils'
import {
@@ -47,7 +49,8 @@ export type TriggerBuildTemplate =
export async function requestBuild(
client: ApiClient,
- { name, tags, cpuCount, memoryMB }: RequestBuildInput
+ { name, tags, cpuCount, memoryMB }: RequestBuildInput,
+ signal?: AbortSignal
) {
const requestBuildRes = await client.api.POST('/v3/templates', {
body: {
@@ -56,6 +59,7 @@ export async function requestBuild(
cpuCount,
memoryMB,
},
+ signal,
})
const error = handleApiError(requestBuildRes, BuildError)
@@ -73,7 +77,8 @@ export async function requestBuild(
export async function getFileUploadLink(
client: ApiClient,
{ templateID, filesHash }: GetFileUploadLinkInput,
- stackTrace?: string
+ stackTrace?: string,
+ signal?: AbortSignal
) {
const fileUploadLinkRes = await client.api.GET(
'/templates/{templateID}/files/{hash}',
@@ -84,6 +89,7 @@ export async function getFileUploadLink(
hash: filesHash,
},
},
+ signal,
}
)
@@ -107,7 +113,13 @@ export async function uploadFile(
ignorePatterns: string[]
resolveSymlinks: boolean
},
- stackTrace: string | undefined
+ stackTrace: string | undefined,
+ // Uploads (PUT to S3 presigned URL) can take a long time for large
+ // archives — the 60s API default would break them, so we use a 1-hour
+ // upload default (`FILE_UPLOAD_TIMEOUT_MS`) when `requestTimeoutMs` is
+ // not supplied. Pass `requestTimeoutMs` (or an `AbortSignal.timeout(ms)`
+ // via `signal`) to override.
+ abortOpts?: { signal?: AbortSignal; requestTimeoutMs?: number }
) {
const { fileName, url, fileContextPath, ignorePatterns, resolveSymlinks } =
options
@@ -138,6 +150,10 @@ export async function uploadFile(
const res = await fetch(url, {
method: 'PUT',
body: uploadBody,
+ signal: buildRequestSignal(
+ abortOpts?.requestTimeoutMs ?? FILE_UPLOAD_TIMEOUT_MS,
+ abortOpts?.signal
+ ),
})
if (!res.ok) {
@@ -156,7 +172,8 @@ export async function uploadFile(
export async function triggerBuild(
client: ApiClient,
- { templateID, buildID, template }: TriggerBuildInput
+ { templateID, buildID, template }: TriggerBuildInput,
+ signal?: AbortSignal
) {
const triggerBuildRes = await client.api.POST(
'/v2/templates/{templateID}/builds/{buildID}',
@@ -168,6 +185,7 @@ export async function triggerBuild(
},
},
body: template,
+ signal,
}
)
@@ -198,7 +216,8 @@ function mapBuildStatusReason(
export async function getBuildStatus(
client: ApiClient,
- { templateID, buildID, logsOffset }: GetBuildStatusInput
+ { templateID, buildID, logsOffset }: GetBuildStatusInput,
+ signal?: AbortSignal
): Promise<TemplateBuildStatusResponse> {
const buildStatusRes = await client.api.GET(
'/templates/{templateID}/builds/{buildID}/status',
@@ -212,6 +231,7 @@ export async function getBuildStatus(
logsOffset,
},
},
+ signal,
}
)
@@ -236,7 +256,8 @@ export async function getBuildStatus(
export async function checkAliasExists(
client: ApiClient,
- { alias }: CheckAliasExistsInput
+ { alias }: CheckAliasExistsInput,
+ signal?: AbortSignal
): Promise<boolean> {
const aliasRes = await client.api.GET('/templates/aliases/{alias}', {
params: {
@@ -244,6 +265,7 @@ export async function checkAliasExists(
alias,
},
},
+ signal,
})
// If we get a NotFound, the alias doesn't exist
@@ -274,23 +296,33 @@ export async function waitForBuildFinish(
onBuildLogs,
logsRefreshFrequency,
stackTraces,
+ signal,
+ requestTimeoutMs,
}: {
templateID: string
buildID: string
onBuildLogs?: (logEntry: LogEntry) => void
logsRefreshFrequency: number
stackTraces: (string | undefined)[]
+ signal?: AbortSignal
+ requestTimeoutMs?: number
}
): Promise<void> {
let logsOffset = 0
let status: TemplateBuildStatus = 'building'
while (status === 'building' || status === 'waiting') {
- const buildStatus = await getBuildStatus(client, {
- templateID,
- buildID,
- logsOffset,
- })
+ signal?.throwIfAborted()
+
+ const buildStatus = await getBuildStatus(
+ client,
+ {
+ templateID,
+ buildID,
+ logsOffset,
+ },
+ buildRequestSignal(requestTimeoutMs, signal)
+ )
logsOffset += buildStatus.logEntries.length
@@ -329,7 +361,8 @@ export async function waitForBuildFinish(
}
}
- // Wait for a short period before checking the status again
+ // Wait for a short period before checking the status again. Abort is
+ // observed on the next iteration via `signal?.throwIfAborted()`.
await new Promise((resolve) => setTimeout(resolve, logsRefreshFrequency))
}
@@ -338,10 +371,12 @@ export async function waitForBuildFinish(
export async function assignTags(
client: ApiClient,
- { targetName, tags }: { targetName: string; tags: string[] }
+ { targetName, tags }: { targetName: string; tags: string[] },
+ signal?: AbortSignal
): Promise<TemplateTagInfo> {
const res = await client.api.POST('/templates/tags', {
body: { target: targetName, tags },
+ signal,
})
const error = handleApiError(res, TemplateError)
@@ -361,10 +396,12 @@ export async function assignTags(
export async function removeTags(
client: ApiClient,
- { name, tags }: { name: string; tags: string[] }
+ { name, tags }: { name: string; tags: string[] },
+ signal?: AbortSignal
): Promise<void> {
const res = await client.api.DELETE('/templates/tags', {
body: { name, tags },
+ signal,
})
const error = handleApiError(res, TemplateError)
@@ -375,7 +412,8 @@ export async function removeTags(
export async function getTemplateTags(
client: ApiClient,
- { templateID }: { templateID: string }
+ { templateID }: { templateID: string },
+ signal?: AbortSignal
): Promise<TemplateTag[]> {
const res = await client.api.GET('/templates/{templateID}/tags', {
params: {
@@ -383,6 +421,7 @@ export async function getTemplateTags(
templateID,
},
},
+ signal,
})
const error = handleApiError(res, TemplateError)
diff --git a/packages/js-sdk/src/template/consts.ts b/packages/js-sdk/src/template/consts.ts
index 007a63c6a..b27270e52 100644
--- a/packages/js-sdk/src/template/consts.ts
+++ b/packages/js-sdk/src/template/consts.ts
@@ -32,3 +32,12 @@ export const STACK_TRACE_DEPTH = 3
* @internal
*/
export const RESOLVE_SYMLINKS = false
+
+/**
+ * Default per-request timeout (in milliseconds) for the file-upload phase
+ * (PUT to S3 presigned URL) when the caller hasn't supplied
+ * `requestTimeoutMs`. Large archives can take well over the 60s API
+ * default, so we use a generous 1-hour bound here.
+ * @internal
+ */
+export const FILE_UPLOAD_TIMEOUT_MS = 3_600_000
diff --git a/packages/js-sdk/src/template/index.ts b/packages/js-sdk/src/template/index.ts
index 00284dc29..099e39eb1 100644
--- a/packages/js-sdk/src/template/index.ts
+++ b/packages/js-sdk/src/template/index.ts
@@ -166,7 +166,7 @@ export class TemplateBase
const config = new ConnectionConfig(buildOptions)
const client = new ApiClient(config)
- const data = await baseTemplate.build(client, name, buildOptions)
+ const data = await baseTemplate.build(client, config, name, buildOptions)
buildOptions.onBuildLogs?.(
new LogEntry(new Date(), 'info', 'Waiting for logs...')
@@ -178,6 +178,8 @@ export class TemplateBase
onBuildLogs: buildOptions.onBuildLogs,
logsRefreshFrequency: baseTemplate.logsRefreshFrequency,
stackTraces: baseTemplate.stackTraces,
+ signal: buildOptions.signal,
+ requestTimeoutMs: config.requestTimeoutMs,
})
return data
@@ -242,7 +244,7 @@ export class TemplateBase
const config = new ConnectionConfig(buildOptions)
const client = new ApiClient(config)
- return (template as TemplateBase).build(client, name, buildOptions)
+ return (template as TemplateBase).build(client, config, name, buildOptions)
}
/**
@@ -263,11 +265,15 @@ export class TemplateBase
const config = new ConnectionConfig(options)
const client = new ApiClient(config)
- return await getBuildStatus(client, {
- templateID: data.templateId,
- buildID: data.buildId,
- logsOffset: options?.logsOffset,
- })
+ return await getBuildStatus(
+ client,
+ {
+ templateID: data.templateId,
+ buildID: data.buildId,
+ logsOffset: options?.logsOffset,
+ },
+ config.getSignal(undefined, options?.signal)
+ )
}
/**
@@ -315,7 +321,11 @@ export class TemplateBase
const config = new ConnectionConfig(options)
const client = new ApiClient(config)
- return checkAliasExists(client, { alias })
+ return checkAliasExists(
+ client,
+ { alias },
+ config.getSignal(undefined, options?.signal)
+ )
}
/**
@@ -343,7 +353,11 @@ export class TemplateBase
const config = new ConnectionConfig(options)
const client = new ApiClient(config)
const normalizedTags = Array.isArray(tags) ? tags : [tags]
- return assignTags(client, { targetName, tags: normalizedTags })
+ return assignTags(
+ client,
+ { targetName, tags: normalizedTags },
+ config.getSignal(undefined, options?.signal)
+ )
}
/**
@@ -370,7 +384,11 @@ export class TemplateBase
const config = new ConnectionConfig(options)
const client = new ApiClient(config)
const normalizedTags = Array.isArray(tags) ? tags : [tags]
- return removeTags(client, { name, tags: normalizedTags })
+ return removeTags(
+ client,
+ { name, tags: normalizedTags },
+ config.getSignal(undefined, options?.signal)
+ )
}
/**
@@ -394,7 +412,11 @@ export class TemplateBase
): Promise<TemplateTag[]> {
const config = new ConnectionConfig(options)
const client = new ApiClient(config)
- return getTemplateTags(client, { templateID: templateId })
+ return getTemplateTags(
+ client,
+ { templateID: templateId },
+ config.getSignal(undefined, options?.signal)
+ )
}
fromDebianImage(variant: string = 'stable'): TemplateBuilder {
@@ -1066,6 +1088,7 @@ export class TemplateBase
*/
private async build(
client: ApiClient,
+ config: ConnectionConfig,
name: string,
options: Omit<BuildOptions, 'alias'>
): Promise<BuildInfo> {
@@ -1086,12 +1109,16 @@ export class TemplateBase
templateID,
buildID,
tags: responseTags,
- } = await requestBuild(client, {
- name,
- tags: options.tags,
- cpuCount: options.cpuCount ?? 2,
- memoryMB: options.memoryMB ?? 1024,
- })
+ } = await requestBuild(
+ client,
+ {
+ name,
+ tags: options.tags,
+ cpuCount: options.cpuCount ?? 2,
+ memoryMB: options.memoryMB ?? 1024,
+ },
+ config.getSignal(undefined, options.signal)
+ )
options.onBuildLogs?.(
new LogEntry(
@@ -1128,7 +1155,8 @@ export class TemplateBase
templateID,
filesHash,
},
- stackTrace
+ stackTrace,
+ config.getSignal(undefined, options.signal)
)
if (
@@ -1146,7 +1174,15 @@ export class TemplateBase
],
resolveSymlinks: instruction.resolveSymlinks ?? RESOLVE_SYMLINKS,
},
- stackTrace
+ stackTrace,
+ // Forward `requestTimeoutMs` only when the caller set it — we
+ // never want to slap the 60s default on a multi-hundred-MB S3
+ // upload, but a user-set per-build timeout should govern the
+ // whole operation, including uploads.
+ {
+ signal: options.signal,
+ requestTimeoutMs: options.requestTimeoutMs,
+ }
)
options.onBuildLogs?.(
new LogEntry(new Date(), 'info', `Uploaded '${src}'`)
@@ -1174,11 +1210,15 @@ export class TemplateBase
new LogEntry(new Date(), 'info', 'Starting building...')
)
- await triggerBuild(client, {
- templateID,
- buildID,
- template: this.serialize(instructionsWithHashes),
- })
+ await triggerBuild(
+ client,
+ {
+ templateID,
+ buildID,
+ template: this.serialize(instructionsWithHashes),
+ },
+ config.getSignal(undefined, options.signal)
+ )
return {
alias: name,
diff --git a/packages/js-sdk/src/volume/client.ts b/packages/js-sdk/src/volume/client.ts
index 22b04afcc..bbe527e15 100644
--- a/packages/js-sdk/src/volume/client.ts
+++ b/packages/js-sdk/src/volume/client.ts
@@ -65,6 +65,7 @@ export class VolumeConnectionConfig {
readonly headers?: Record<string, string>
readonly logger?: Logger
readonly requestTimeoutMs?: number
+ readonly signal?: AbortSignal
constructor(volume: Volume, opts?: VolumeApiOpts) {
this.domain = opts?.domain || volume.domain || VolumeConnectionConfig.domain
@@ -77,6 +78,7 @@ export class VolumeConnectionConfig {
this.headers = opts?.headers
this.logger = opts?.logger
this.requestTimeoutMs = opts?.requestTimeoutMs
+ this.signal = opts?.signal
}
private static get domain() {
@@ -92,7 +94,10 @@ export class VolumeConnectionConfig {
}
getSignal(requestTimeoutMs?: number, signal?: AbortSignal) {
- return buildRequestSignal(requestTimeoutMs ?? this.requestTimeoutMs, signal)
+ return buildRequestSignal(
+ requestTimeoutMs ?? this.requestTimeoutMs,
+ signal ?? this.signal
+ )
}
}
diff --git a/packages/js-sdk/src/volume/index.ts b/packages/js-sdk/src/volume/index.ts
index 0e8bcab00..747ce575d 100644
--- a/packages/js-sdk/src/volume/index.ts
+++ b/packages/js-sdk/src/volume/index.ts
@@ -268,7 +268,7 @@ export class Volume {
depth: opts?.depth,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(),
})
if (res.response.status === 404) {
@@ -312,7 +312,7 @@ export class Volume {
force: opts?.force,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(),
})
if (res.response.status === 404) {
@@ -354,7 +354,7 @@ export class Volume {
path,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(),
})
if (res.response.status === 404) {
@@ -429,7 +429,7 @@ export class Volume {
gid: metadata.gid,
mode: metadata.mode,
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(),
})
if (res.response.status === 404) {
@@ -517,7 +517,10 @@ export class Volume {
}
): Promise<unknown> {
const format = opts?.format ?? 'text'
- const config = new VolumeConnectionConfig(this, opts)
+ const config = new VolumeConnectionConfig(this, {
+ ...opts,
+ requestTimeoutMs: opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS,
+ })
const client = new VolumeApiClient(config)
const res = await client.api.GET('/volumecontent/{volumeID}/file', {
@@ -530,10 +533,7 @@ export class Volume {
},
},
parseAs: format === 'bytes' ? 'arrayBuffer' : format,
- signal: config.getSignal(
- opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS,
- opts?.signal
- ),
+ signal: config.getSignal(),
})
if (res.response.status === 404) {
@@ -579,7 +579,10 @@ export class Volume {
data: string | ArrayBuffer | Blob | ReadableStream<Uint8Array>,
opts?: VolumeWriteOptions & VolumeApiOpts
): Promise<VolumeEntryStat> {
- const config = new VolumeConnectionConfig(this, opts)
+ const config = new VolumeConnectionConfig(this, {
+ ...opts,
+ requestTimeoutMs: opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS,
+ })
const client = new VolumeApiClient(config)
const blob = await toBlob(data)
@@ -602,10 +605,7 @@ export class Volume {
headers: {
'Content-Type': 'application/octet-stream',
},
- signal: config.getSignal(
- opts?.requestTimeoutMs ?? FILE_TIMEOUT_MS,
- opts?.signal
- ),
+ signal: config.getSignal(),
})
if (res.response.status === 404) {
@@ -645,7 +645,7 @@ export class Volume {
path,
},
},
- signal: config.getSignal(opts?.requestTimeoutMs, opts?.signal),
+ signal: config.getSignal(),
})
if (res.response.status === 404) {
diff --git a/packages/js-sdk/tests/template/abortSignal.test.ts b/packages/js-sdk/tests/template/abortSignal.test.ts
new file mode 100644
index 000000000..4df5a5bb6
--- /dev/null
+++ b/packages/js-sdk/tests/template/abortSignal.test.ts
@@ -0,0 +1,197 @@
+import { afterAll, afterEach, beforeAll, expect, test } from 'vitest'
+import { http, HttpResponse } from 'msw'
+import { setupServer } from 'msw/node'
+
+import { Template } 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('/v3/templates'), async ({ request }) => {
+ await holdUntilAborted(request.signal)
+ return HttpResponse.json({})
+ }),
+ http.get(apiUrl('/templates/aliases/:alias'), async ({ request }) => {
+ await holdUntilAborted(request.signal)
+ return HttpResponse.json({})
+ }),
+ http.get(
+ apiUrl('/templates/:templateID/builds/:buildID/status'),
+ async ({ request }) => {
+ await holdUntilAborted(request.signal)
+ return HttpResponse.json({})
+ }
+ ),
+ http.post(apiUrl('/templates/tags'), async ({ request }) => {
+ await holdUntilAborted(request.signal)
+ return HttpResponse.json({})
+ }),
+ http.delete(apiUrl('/templates/tags'), async ({ request }) => {
+ await holdUntilAborted(request.signal)
+ return HttpResponse.json({})
+ }),
+ http.get(apiUrl('/templates/:templateID/tags'), 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('Template.build rejects when AbortSignal is aborted', async () => {
+ const controller = new AbortController()
+ const requestStarted = nextRequestStart()
+
+ const template = Template().fromBaseImage()
+ const promise = Template.build(template, 'test-template', {
+ apiKey: 'test-key',
+ signal: controller.signal,
+ })
+
+ await requestStarted
+ controller.abort()
+
+ await expect(promise).rejects.toThrow()
+})
+
+test('Template.build rejects immediately when signal is already aborted', async () => {
+ const controller = new AbortController()
+ controller.abort()
+
+ const template = Template().fromBaseImage()
+ await expect(
+ Template.build(template, 'test-template', {
+ apiKey: 'test-key',
+ signal: controller.signal,
+ })
+ ).rejects.toThrow()
+})
+
+test('Template.buildInBackground rejects when AbortSignal is aborted', async () => {
+ const controller = new AbortController()
+ const requestStarted = nextRequestStart()
+
+ const template = Template().fromBaseImage()
+ const promise = Template.buildInBackground(template, 'test-template', {
+ apiKey: 'test-key',
+ signal: controller.signal,
+ })
+
+ await requestStarted
+ controller.abort()
+
+ await expect(promise).rejects.toThrow()
+})
+
+test('Template.exists rejects when AbortSignal is aborted', async () => {
+ const controller = new AbortController()
+ const requestStarted = nextRequestStart()
+
+ const promise = Template.exists('some-template', {
+ apiKey: 'test-key',
+ signal: controller.signal,
+ })
+
+ await requestStarted
+ controller.abort()
+
+ await expect(promise).rejects.toThrow()
+})
+
+test('Template.getBuildStatus rejects when AbortSignal is aborted', async () => {
+ const controller = new AbortController()
+ const requestStarted = nextRequestStart()
+
+ const promise = Template.getBuildStatus(
+ { templateId: 'tpl-1', buildId: 'build-1' },
+ {
+ apiKey: 'test-key',
+ signal: controller.signal,
+ }
+ )
+
+ await requestStarted
+ controller.abort()
+
+ await expect(promise).rejects.toThrow()
+})
+
+test('Template.assignTags rejects when AbortSignal is aborted', async () => {
+ const controller = new AbortController()
+ const requestStarted = nextRequestStart()
+
+ const promise = Template.assignTags('some-template:v1', 'stable', {
+ apiKey: 'test-key',
+ signal: controller.signal,
+ })
+
+ await requestStarted
+ controller.abort()
+
+ await expect(promise).rejects.toThrow()
+})
+
+test('Template.removeTags rejects when AbortSignal is aborted', async () => {
+ const controller = new AbortController()
+ const requestStarted = nextRequestStart()
+
+ const promise = Template.removeTags('some-template', 'stable', {
+ apiKey: 'test-key',
+ signal: controller.signal,
+ })
+
+ await requestStarted
+ controller.abort()
+
+ await expect(promise).rejects.toThrow()
+})
+
+test('Template.getTags rejects when AbortSignal is aborted', async () => {
+ const controller = new AbortController()
+ const requestStarted = nextRequestStart()
+
+ const promise = Template.getTags('some-template', {
+ apiKey: 'test-key',
+ signal: controller.signal,
+ })
+
+ await requestStarted
+ controller.abort()
+
+ await expect(promise).rejects.toThrow()
+})