Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cancellation support #15

Merged
merged 6 commits into from
Nov 3, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
38 changes: 37 additions & 1 deletion api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface XHROptions {
data?: string;
strictSSL?: boolean;
followRedirects?: number;
token?: CancellationToken;
agent?: HttpProxyAgent | HttpsProxyAgent;
}

Expand All @@ -30,6 +31,41 @@ export interface XHRConfigure {
(proxyUrl: string | undefined, strictSSL: boolean): void;
}

export interface Disposable {
/**
* Dispose this object.
*/
dispose(): void;
}
/**
* Represents a typed event.
*/
export interface Event<T> {
/**
*
* @param listener The listener function will be call when the event happens.
* @param thisArgs The 'this' which will be used when calling the event listener.
* @param disposables An array to which a {{IDisposable}} will be added. The
* @return
*/
(listener: (e: T) => any, thisArgs?: any, disposables?: Disposable[]): Disposable;
}
/**
* Defines a CancellationToken. This interface is not
* intended to be implemented. A CancellationToken must
* be created via a CancellationTokenSource.
*/
export interface CancellationToken {
/**
* Is `true` when the token has been cancelled, `false` otherwise.
*/
readonly isCancellationRequested: boolean;
/**
* An [event](#Event) which fires upon cancellation.
*/
readonly onCancellationRequested: Event<any>;
}

export type HttpProxyAgent = import('http-proxy-agent').HttpProxyAgent;

export type HttpsProxyAgent = import('https-proxy-agent').HttpsProxyAgent;
Expand All @@ -39,4 +75,4 @@ export type Headers = { [header: string]: string | string[] | undefined };
export declare const configure: XHRConfigure;
export declare const xhr: XHRRequest;

export declare function getErrorStatusDescription(status: number): string;
export declare function getErrorStatusDescription(status: number): string;
8 changes: 7 additions & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "request-light",
"version": "0.5.8",
"version": "0.6.0",
"description": "Lightweight request library. Promise based, with proxy support.",
"main": "./lib/node/main.js",
"browser": {
Expand All @@ -20,6 +20,7 @@
"http-proxy-agent": "^5.0.0",
"https-proxy-agent": "^5.0.0",
"vscode-nls": "^5.0.0",
"vscode-jsonrpc": "^5.0.0",
Tarrowren marked this conversation as resolved.
Show resolved Hide resolved
"typescript": "^4.5.4",
"@types/node": "13.7.6",
"rimraf": "^3.0.2",
Expand Down
13 changes: 12 additions & 1 deletion src/browser/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,17 @@ export const xhr: XHRRequest = async (options: XHROptions): Promise<XHRResponse>
if (options.data) {
requestInit.body = options.data;
}
if (options.token) {
const controller = new AbortController();
if (options.token.isCancellationRequested) {
// see https://github.com/microsoft/TypeScript/issues/49609
(controller as any).abort();
}
options.token.onCancellationRequested(() => {
(controller as any).abort();
});
requestInit.signal = controller.signal;
}

const requestInfo = new Request(options.url, requestInit);
const response = await fetch(requestInfo);
Expand All @@ -51,4 +62,4 @@ export const xhr: XHRRequest = async (options: XHROptions): Promise<XHRResponse>

export function getErrorStatusDescription(status: number): string {
return String(status);
}
}
94 changes: 69 additions & 25 deletions src/node/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import { Url, parse as parseUrl, format } from 'url';
import * as https from 'https';
import * as http from 'http';
import * as zlib from 'zlib';
import * as https from 'https';
import { format, parse as parseUrl, Url } from 'url';
import * as nls from 'vscode-nls';
import * as zlib from 'zlib';

import * as createHttpsProxyAgent from 'https-proxy-agent';
import * as createHttpProxyAgent from 'http-proxy-agent';
import * as createHttpsProxyAgent from 'https-proxy-agent';

import { XHRRequest, XHRConfigure, XHROptions, XHRResponse, HttpProxyAgent, HttpsProxyAgent } from '../../api';
import { HttpProxyAgent, HttpsProxyAgent, XHRConfigure, XHROptions, XHRRequest, XHRResponse } from '../../api';

if (process.env.VSCODE_NLS_CONFIG) {
const VSCODE_NLS_CONFIG = process.env.VSCODE_NLS_CONFIG;
Expand Down Expand Up @@ -42,7 +42,7 @@ export const xhr: XHRRequest = (options: XHROptions): Promise<XHRResponse> => {

return request(options).then(result => new Promise<XHRResponse>((c, e) => {
const res = result.res;
let readable: NodeJS.ReadableStream = res;
let readable: import('stream').Readable = res;
let isCompleted = false;

const encoding = res.headers && res.headers['content-encoding'];
Expand Down Expand Up @@ -80,9 +80,9 @@ export const xhr: XHRRequest = (options: XHROptions): Promise<XHRResponse> => {
});
}
if (location) {
const newOptions = {
const newOptions: XHROptions = {
type: options.type, url: location, user: options.user, password: options.password, headers: options.headers,
timeout: options.timeout, followRedirects: options.followRedirects - 1, data: options.data
timeout: options.timeout, followRedirects: options.followRedirects - 1, data: options.data, token: options.token
};
xhr(newOptions).then(c, e);
return;
Expand All @@ -105,30 +105,51 @@ export const xhr: XHRRequest = (options: XHROptions): Promise<XHRResponse> => {
}
});
readable.on('error', (err) => {
const response: XHRResponse = {
responseText: localize('error', 'Unable to access {0}. Error: {1}', options.url, err.message),
body: Buffer.concat(data),
status: 500,
headers: {}
};
let response: XHRResponse | Error;
if (AbortError.is(err)) {
response = err;
} else {
response = {
responseText: localize('error', 'Unable to access {0}. Error: {1}', options.url, err.message),
body: Buffer.concat(data),
status: 500,
headers: {}
};
}
isCompleted = true;
e(response);
});
}), err => {
let message: string;

if (options.agent) {
message = localize('error.cannot.connect.proxy', 'Unable to connect to {0} through a proxy. Error: {1}', options.url, err.message);
if (options.token) {
if (options.token.isCancellationRequested) {
readable.destroy(new AbortError());
}
options.token.onCancellationRequested(() => {
readable.destroy(new AbortError());
});
}
}), err => {
let response: XHRResponse | Error;
if (AbortError.is(err)) {
response = err;
} else {
message = localize('error.cannot.connect', 'Unable to connect to {0}. Error: {1}', options.url, err.message);
let message: string;

if (options.agent) {
message = localize('error.cannot.connect.proxy', 'Unable to connect to {0} through a proxy. Error: {1}', options.url, err.message);
} else {
message = localize('error.cannot.connect', 'Unable to connect to {0}. Error: {1}', options.url, err.message);
}

response = {
responseText: message,
body: Buffer.concat([]),
status: 404,
headers: {}
};
}

return Promise.reject<XHRResponse>({
responseText: message,
body: Buffer.concat([]),
status: 404,
headers: {}
});
return Promise.reject(response);
});
}

Expand Down Expand Up @@ -201,6 +222,15 @@ function request(options: XHROptions): Promise<RequestResult> {
}

req.end();

if (options.token) {
if (options.token.isCancellationRequested) {
req.destroy(new AbortError());
}
options.token.onCancellationRequested(() => {
req.destroy(new AbortError());
});
}
});
}

Expand Down Expand Up @@ -272,3 +302,17 @@ function getProxyAgent(rawRequestURL: string, options: ProxyOptions = {}): HttpP

return requestURL.protocol === 'http:' ? createHttpProxyAgent(opts) : createHttpsProxyAgent(opts);
}

class AbortError extends Error {
constructor() {
super('The user aborted a request');
this.name = 'AbortError';

// see https://github.com/microsoft/TypeScript/issues/13965
Object.setPrototypeOf(this, AbortError.prototype);
}

static is(value: any): boolean {
return value instanceof AbortError;
}
}
22 changes: 22 additions & 0 deletions src/test/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { AddressInfo } from 'net';
import { promises as fs } from 'fs';
import { join } from 'path';
import { IncomingMessage, ServerResponse } from 'http';
import { CancellationTokenSource } from 'vscode-jsonrpc'

test('text content', async t => {
const testContent = JSON.stringify({ hello: 1, world: true })
Expand Down Expand Up @@ -149,3 +150,24 @@ test('relative redirect', async t => {

server.close();
});

test('cancellation token', async t => {
const server = await createServer();

server.on('request', (req, res) => {
res.writeHead(200, { 'Content-Encoding': 'gzip' });
res.end();
});

const serverAddress = server.address() as AddressInfo;
const cancellationTokenSource = new CancellationTokenSource();
cancellationTokenSource.cancel();
try {
await xhr({ url: `http://${serverAddress.address}:${serverAddress.port}`, token: cancellationTokenSource.token });
t.fail('not aborted')
} catch (e) {
t.is(e.name, 'AbortError');
}

server.close();
})