Skip to content

Commit

Permalink
feat: clear timeout to prevent rogue async tasks (#8)
Browse files Browse the repository at this point in the history
* feat: clear timeout to prevent rogue async tasks

* chore: add changeset
  • Loading branch information
jmike authored Oct 10, 2024
1 parent b698600 commit 5458919
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/rude-dolls-trade.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'fp-ts-timeout': patch
---

Clear the internal timeout to prevent rogue async operations.
20 changes: 18 additions & 2 deletions lib/withTaskEitherTimeout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,18 @@ export function withTaskEitherTimeout<LeftType, RightType>(
milliseconds: number
): TaskEitherWithTimeoutCurriedFunc<LeftType, RightType> {
return (taskEither) => {
// store the timeout id so that we can clear it later
let timeoutId: number | undefined;

const asyncTimeout = new Promise<Either.Either<TimeoutError, never>>(
(resolve) => {
setTimeout(
// We know or a fact that setTimeout() returns a positive integer.
// However typescript thinks it returns a NodeJS.Timeout,
// which is likely coming from a misconfiguration in the tsconfig.
// I do not have the time to look at this into detail,
// so I will just ignore the error for now.
// @ts-expect-error
timeoutId = setTimeout(
() =>
resolve(
Either.left(new TimeoutError(`Timed out after ${milliseconds}ms`))
Expand All @@ -23,6 +32,13 @@ export function withTaskEitherTimeout<LeftType, RightType>(
);
const asyncTask = taskEither();

return () => Promise.race([asyncTask, asyncTimeout]);
return () =>
Promise.race([asyncTask, asyncTimeout]).finally(() => {
// at this point there's two possibilities:
// 1. asyncTask has resolved, in which case asyncTimeout is still running
// 2. asyncTimeout has resolved, in which case asyncTask is still running
// we want to clear the timeout in both cases
clearTimeout(timeoutId);
});
};
}

0 comments on commit 5458919

Please sign in to comment.