Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions lib/httpBlock.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ export interface DescriptHttpBlockDescription<
servername?: DescriptHttpBlockDescriptionCallback<DescriptRequestOptions['servername'], Params, Context>;
timeout?: DescriptHttpBlockDescriptionCallback<DescriptRequestOptions['timeout'], Params, Context>;

// Отдельный таймаут на чтение ответа. Если не указан, то используется общий таймаут.
// Если указан, то после получения первого байта из ответа общий таймаут сбрасывается и выставляется новый только на чтение.
readTimeout?: DescriptHttpBlockDescriptionCallback<DescriptRequestOptions['readTimeout'], Params, Context>;

query?: HttpQuery<Params, Context> | Array<HttpQuery<Params, Context>>;

headers?: HttpHeaders<Params, Context> | Array<HttpHeaders<Params, Context>>;
Expand Down Expand Up @@ -134,6 +138,7 @@ const EVALUABLE_PROPS: Array<keyof Pick<DescriptRequestOptions, 'agent' |
'pfx' |
'port' |
'protocol' |
'readTimeout' |
'rejectUnauthorized' |
'secureProtocol' |
'servername' |
Expand All @@ -154,6 +159,7 @@ const EVALUABLE_PROPS: Array<keyof Pick<DescriptRequestOptions, 'agent' |
'pfx',
'port',
'protocol',
'readTimeout',
'rejectUnauthorized',
'secureProtocol',
'servername',
Expand Down
19 changes: 15 additions & 4 deletions lib/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export interface DescriptRequestOptions {
name: string;
};

readTimeout?: number;
timeout?: number;

bodyCompress?: ZlibOptions;
Expand Down Expand Up @@ -135,6 +136,7 @@ export class RequestOptions {
isError: DescriptRequestOptions['isError'];
isRetryAllowed: DescriptRequestOptions['isRetryAllowed'];
maxRetries: number;
readTimeout: DescriptRequestOptions['readTimeout'];
retries: number;
retryTimeout: number;
timeout: DescriptRequestOptions['timeout'];
Expand All @@ -159,6 +161,7 @@ export class RequestOptions {
this.retries = options.retries || 0;

this.timeout = options.timeout;
this.readTimeout = options.readTimeout;
this.bodyCompress = options.bodyCompress;

this.httpOptions = {};
Expand Down Expand Up @@ -293,7 +296,7 @@ class DescriptRequest {
logger: LoggerInterface<LoggerEvent>;
cancel: Cancel;
timestamps: EventTimestamps;
hTimeout: number | null;
hTimeout: NodeJS.Timeout | null;
req?: http.ClientRequest;
isResolved: boolean;

Expand Down Expand Up @@ -466,8 +469,9 @@ class DescriptRequest {
this.doFail(error);
}

setTimeout() {
if ((this.options.timeout || 0) > 0) {
setTimeout(customTimeout?: number) {
const timeout = customTimeout || this.options.timeout || 0;
if (timeout > 0) {
this.hTimeout = setTimeout(() => {
let error;
if (!this.timestamps.tcpConnection) {
Expand All @@ -480,7 +484,7 @@ class DescriptRequest {

this.doCancel(error);

}, this.options.timeout) as unknown as number;
}, timeout);
}
}

Expand All @@ -500,6 +504,13 @@ class DescriptRequest {
async requestHandler(res: http.IncomingMessage): Promise<DescriptHttpResult> {
res.once('readable', () => {
this.timestamps.firstByte = Date.now();

// Если есть отдельный таймаут на чтение, то после получения первого байта,
// нужно сбросить общий таймаут и создать новый.
if (this.options.readTimeout) {
this.clearTimeout();
this.setTimeout(this.options.readTimeout);
}
});

const unzipped = decompressResponse(res);
Expand Down
42 changes: 42 additions & 0 deletions tests/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,48 @@ describe('request', () => {
}
});

it('200, timeout, readTimeout, slow response', async() => {
const path = getPath();

fake.add(path, async(req: http.IncomingMessage, res: http.ServerResponse) => {
res.statusCode = 200;
res.write('Привет!');
await waitForValue(null, 100);
res.end();
});

const result = await doRequest({
pathname: path,
timeout: 50,
readTimeout: 150,
});
expect(result.body?.toString()).toBe('Привет!');
});

it('200, timeout, readTimeout, incomplete response', async() => {
const path = getPath();

fake.add(path, async(req: http.IncomingMessage, res: http.ServerResponse) => {
res.statusCode = 200;
res.write('Привет!');
await waitForValue(null, 100);
res.end();
});

expect.assertions(2);
try {
await doRequest({
pathname: path,
timeout: 50,
readTimeout: 90,
});

} catch (error) {
expect(de.isError(error)).toBe(true);
expect(error.error.id).toBe(de.ERROR_ID.REQUEST_TIMEOUT);
}
});

});

describe('content-encoding', () => {
Expand Down
Loading