Skip to content

Commit

Permalink
Emit timeout errors as soon as possible
Browse files Browse the repository at this point in the history
Fixes #997
  • Loading branch information
szmarczak committed Dec 14, 2019
1 parent 0569d45 commit 912c2e5
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 11 deletions.
11 changes: 1 addition & 10 deletions source/utils/timed-out.ts
Expand Up @@ -33,21 +33,12 @@ export default (request: ClientRequest, delays: Delays, options: TimedOutOptions
const {once, unhandleAll} = unhandler();

const addTimeout = <T extends any[]>(delay: number, callback: (delay: number, ...args: T) => void, ...args: T): (typeof noop) => {
// Event loop order is timers, poll, immediates.
// The timed event may emit during the current tick poll phase, so
// defer calling the handler until the poll phase completes.
let immediate: NodeJS.Immediate;
const timeout: NodeJS.Timeout = setTimeout(() => {
// @ts-ignore https://github.com/microsoft/TypeScript/issues/26113
immediate = setImmediate(callback, delay, ...args);
immediate.unref?.();
}, delay);
const timeout = setTimeout(callback, delay, ...args) as unknown as NodeJS.Timeout;

timeout.unref?.();

const cancel = (): void => {
clearTimeout(timeout);
clearImmediate(immediate);
};

cancelers.push(cancel);
Expand Down
14 changes: 13 additions & 1 deletion test/timeout.ts
Expand Up @@ -10,7 +10,7 @@ import delay = require('delay');
import CacheableLookup from 'cacheable-lookup';
import {Handler} from 'express';
import pEvent = require('p-event');
import got from '../source';
import got, {TimeoutError} from '../source';
import timedOut from '../source/utils/timed-out';
import slowDataStream from './helpers/slow-data-stream';
import {GlobalClock} from './helpers/types';
Expand Down Expand Up @@ -622,3 +622,15 @@ test.serial('cancelling the request removes timeouts', withServer, async (t, ser

await delay(1000);
});

test('timeouts are emitted ASAP', async t => {
const timeout = 500;
const marginOfError = 100;

const error: TimeoutError = await t.throwsAsync(got('http://192.0.2.1/test', {
retry: 0,
timeout
}), TimeoutError);

t.true(error.timings.phases.total! < (timeout + marginOfError));
});

2 comments on commit 912c2e5

@kibertoad
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@sindresorhus Any estimates on when version with this fix will be released?

@sindresorhus
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.