Skip to content

armgit / E2B

Public Imported from GitHub
0

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

fix(js-sdk): Fix timeout leak (#126)

Pavel 'Strajk' Dolecek08308fcf55e2
diff --git a/packages/js-sdk/src/utils/promise.ts b/packages/js-sdk/src/utils/promise.ts
index b8ec94919..2196fcecc 100644
--- a/packages/js-sdk/src/utils/promise.ts
+++ b/packages/js-sdk/src/utils/promise.ts
@@ -50,9 +50,9 @@ export function withTimeout<T extends (...args: any[]) => any>(
return fn
}
- // Throw an error if it takes too long
+ let timerId: NodeJS.Timeout;
const timer = new Promise((resolve, reject) => {
- setTimeout(
+ timerId = setTimeout(
() =>
reject(new TimeoutError(`Calling "${fn.name}" timeouted after ${timeout}ms.`)),
timeout,
@@ -61,6 +61,9 @@ export function withTimeout<T extends (...args: any[]) => any>(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return ((...args: T extends (...args: infer A) => any ? A : never) => {
- return Promise.race([timer, fn(...args)])
+ const result = Promise.race([timer, fn(...args)])
+ result.finally(() => clearTimeout(timerId));
+ return result;
}) as T
}
+
diff --git a/packages/js-sdk/test/timeout.test.mjs b/packages/js-sdk/test/timeout.test.mjs
index 163593507..eaead2cff 100644
--- a/packages/js-sdk/test/timeout.test.mjs
+++ b/packages/js-sdk/test/timeout.test.mjs
@@ -52,3 +52,18 @@ test('timeout process', async () => {
TimeoutError,
)
})
+
+// TODO: Waiting for https://github.com/vitest-dev/vitest/issues/3119
+test.skip('timeout longer than cmd should not leak', () => new Promise(async (resolve) => {
+ const session = await Session.create({ id: 'Nodejs', apiKey: E2B_API_KEY })
+ const start = Date.now();
+ const proc = await session.process.start({
+ cmd: "node -e 'setTimeout(() => {}, 1000)'", // should take around 1 second
+ onExit: () => {
+ // TODO: Verify that process finished after successful cmd, and not after timeout
+ resolve()
+ },
+ timeout: 10_000 // but we give it 10 seconds
+ })
+ await proc.finished
+}), {timeout: 12_000})