2019-05-14 18:25:46 -04:00
|
|
|
"use strict";
|
|
|
|
|
2021-10-31 00:53:49 -04:00
|
|
|
import { decode as base64Decode, encode as base64Encode } from "@ethersproject/base64";
|
2020-09-05 04:29:08 -04:00
|
|
|
import { hexlify, isBytesLike } from "@ethersproject/bytes";
|
2019-05-14 18:25:46 -04:00
|
|
|
import { shallowCopy } from "@ethersproject/properties";
|
2020-07-30 17:03:36 -04:00
|
|
|
import { toUtf8Bytes, toUtf8String } from "@ethersproject/strings";
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2019-08-01 18:04:06 -04:00
|
|
|
import { Logger } from "@ethersproject/logger";
|
|
|
|
import { version } from "./_version";
|
|
|
|
const logger = new Logger(version);
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2020-10-07 19:40:28 -04:00
|
|
|
import { getUrl, GetUrlResponse, Options } from "./geturl";
|
2020-04-18 02:46:52 -04:00
|
|
|
|
2020-07-14 02:26:45 -04:00
|
|
|
function staller(duration: number): Promise<void> {
|
|
|
|
return new Promise((resolve) => {
|
|
|
|
setTimeout(resolve, duration);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
2020-09-05 04:29:08 -04:00
|
|
|
function bodyify(value: any, type: string): string {
|
|
|
|
if (value == null) { return null; }
|
|
|
|
|
|
|
|
if (typeof(value) === "string") { return value; }
|
|
|
|
|
|
|
|
if (isBytesLike(value)) {
|
2020-09-15 22:12:56 -04:00
|
|
|
if (type && (type.split("/")[0] === "text" || type.split(";")[0].trim() === "application/json")) {
|
2020-09-05 04:29:08 -04:00
|
|
|
try {
|
|
|
|
return toUtf8String(value);
|
|
|
|
} catch (error) { };
|
|
|
|
}
|
|
|
|
return hexlify(value);
|
|
|
|
}
|
|
|
|
|
|
|
|
return value;
|
|
|
|
}
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
// Exported Types
|
|
|
|
export type ConnectionInfo = {
|
|
|
|
url: string,
|
2020-07-14 02:26:45 -04:00
|
|
|
headers?: { [key: string]: string | number }
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
user?: string,
|
|
|
|
password?: string,
|
2020-07-14 02:26:45 -04:00
|
|
|
|
2019-06-11 22:40:45 -04:00
|
|
|
allowInsecureAuthentication?: boolean,
|
2020-10-07 19:40:28 -04:00
|
|
|
allowGzip?: boolean,
|
2020-07-14 02:26:45 -04:00
|
|
|
|
2019-11-23 21:21:27 +09:00
|
|
|
throttleLimit?: number,
|
2020-07-14 22:50:05 -04:00
|
|
|
throttleSlotInterval?: number;
|
2020-07-14 02:26:45 -04:00
|
|
|
throttleCallback?: (attempt: number, url: string) => Promise<boolean>,
|
|
|
|
|
2022-02-19 01:31:03 -05:00
|
|
|
skipFetchSetup?: boolean;
|
2022-03-04 16:15:47 -05:00
|
|
|
errorPassThrough?: boolean;
|
2022-02-19 01:31:03 -05:00
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
timeout?: number,
|
|
|
|
};
|
|
|
|
|
|
|
|
export interface OnceBlockable {
|
|
|
|
once(eventName: "block", handler: () => void): void;
|
|
|
|
}
|
|
|
|
|
2020-05-04 22:43:44 -04:00
|
|
|
export interface OncePollable {
|
|
|
|
once(eventName: "poll", handler: () => void): void;
|
|
|
|
}
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
export type PollOptions = {
|
|
|
|
timeout?: number,
|
|
|
|
floor?: number,
|
|
|
|
ceiling?: number,
|
|
|
|
interval?: number,
|
|
|
|
retryLimit?: number,
|
|
|
|
onceBlock?: OnceBlockable
|
2020-05-04 22:43:44 -04:00
|
|
|
oncePoll?: OncePollable
|
2019-05-14 18:25:46 -04:00
|
|
|
};
|
|
|
|
|
2019-09-27 21:55:40 -04:00
|
|
|
export type FetchJsonResponse = {
|
|
|
|
statusCode: number;
|
|
|
|
headers: { [ header: string ]: string };
|
|
|
|
};
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
|
|
|
|
type Header = { key: string, value: string };
|
|
|
|
|
2020-07-31 01:15:22 -04:00
|
|
|
// This API is still a work in progress; the future changes will likely be:
|
|
|
|
// - ConnectionInfo => FetchDataRequest<T = any>
|
|
|
|
// - FetchDataRequest.body? = string | Uint8Array | { contentType: string, data: string | Uint8Array }
|
|
|
|
// - If string => text/plain, Uint8Array => application/octet-stream (if content-type unspecified)
|
|
|
|
// - FetchDataRequest.processFunc = (body: Uint8Array, response: FetchDataResponse) => T
|
|
|
|
// For this reason, it should be considered internal until the API is finalized
|
|
|
|
export function _fetchData<T = Uint8Array>(connection: string | ConnectionInfo, body?: Uint8Array, processFunc?: (value: Uint8Array, response: FetchJsonResponse) => T): Promise<T> {
|
2020-07-14 02:26:45 -04:00
|
|
|
|
|
|
|
// How many times to retry in the event of a throttle
|
|
|
|
const attemptLimit = (typeof(connection) === "object" && connection.throttleLimit != null) ? connection.throttleLimit: 12;
|
|
|
|
logger.assertArgument((attemptLimit > 0 && (attemptLimit % 1) === 0),
|
|
|
|
"invalid connection throttle limit", "connection.throttleLimit", attemptLimit);
|
|
|
|
|
|
|
|
const throttleCallback = ((typeof(connection) === "object") ? connection.throttleCallback: null);
|
2020-07-14 22:50:05 -04:00
|
|
|
const throttleSlotInterval = ((typeof(connection) === "object" && typeof(connection.throttleSlotInterval) === "number") ? connection.throttleSlotInterval: 100);
|
|
|
|
logger.assertArgument((throttleSlotInterval > 0 && (throttleSlotInterval % 1) === 0),
|
|
|
|
"invalid connection throttle slot interval", "connection.throttleSlotInterval", throttleSlotInterval);
|
2020-07-14 02:26:45 -04:00
|
|
|
|
2022-03-04 16:15:47 -05:00
|
|
|
const errorPassThrough = ((typeof(connection) === "object") ? !!(connection.errorPassThrough): false);
|
|
|
|
|
2019-11-01 23:33:51 +09:00
|
|
|
const headers: { [key: string]: Header } = { };
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
let url: string = null;
|
|
|
|
|
2019-06-11 22:40:45 -04:00
|
|
|
// @TODO: Allow ConnectionInfo to override some of these values
|
2020-10-07 19:40:28 -04:00
|
|
|
const options: Options = {
|
2019-06-11 22:40:45 -04:00
|
|
|
method: "GET",
|
|
|
|
};
|
|
|
|
|
2019-09-27 21:55:40 -04:00
|
|
|
let allow304 = false;
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
let timeout = 2 * 60 * 1000;
|
|
|
|
|
|
|
|
if (typeof(connection) === "string") {
|
|
|
|
url = connection;
|
|
|
|
|
|
|
|
} else if (typeof(connection) === "object") {
|
2019-06-11 22:40:45 -04:00
|
|
|
if (connection == null || connection.url == null) {
|
2019-08-01 18:04:06 -04:00
|
|
|
logger.throwArgumentError("missing URL", "connection.url", connection);
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
url = connection.url;
|
|
|
|
|
|
|
|
if (typeof(connection.timeout) === "number" && connection.timeout > 0) {
|
|
|
|
timeout = connection.timeout;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (connection.headers) {
|
2019-11-01 23:33:51 +09:00
|
|
|
for (const key in connection.headers) {
|
2019-05-14 18:25:46 -04:00
|
|
|
headers[key.toLowerCase()] = { key: key, value: String(connection.headers[key]) };
|
2019-09-27 21:55:40 -04:00
|
|
|
if (["if-none-match", "if-modified-since"].indexOf(key.toLowerCase()) >= 0) {
|
|
|
|
allow304 = true;
|
|
|
|
}
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-10-07 19:40:28 -04:00
|
|
|
options.allowGzip = !!connection.allowGzip;
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
if (connection.user != null && connection.password != null) {
|
2019-06-11 22:40:45 -04:00
|
|
|
if (url.substring(0, 6) !== "https:" && connection.allowInsecureAuthentication !== true) {
|
2019-08-01 18:04:06 -04:00
|
|
|
logger.throwError(
|
2019-05-14 18:25:46 -04:00
|
|
|
"basic authentication requires a secure https url",
|
2019-08-01 18:04:06 -04:00
|
|
|
Logger.errors.INVALID_ARGUMENT,
|
|
|
|
{ argument: "url", url: url, user: connection.user, password: "[REDACTED]" }
|
2019-05-14 18:25:46 -04:00
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2019-11-01 23:33:51 +09:00
|
|
|
const authorization = connection.user + ":" + connection.password;
|
2019-05-14 18:25:46 -04:00
|
|
|
headers["authorization"] = {
|
|
|
|
key: "Authorization",
|
|
|
|
value: "Basic " + base64Encode(toUtf8Bytes(authorization))
|
|
|
|
};
|
|
|
|
}
|
2022-02-19 01:31:03 -05:00
|
|
|
|
|
|
|
if (connection.skipFetchSetup != null) {
|
|
|
|
options.skipFetchSetup = !!connection.skipFetchSetup;
|
|
|
|
}
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
2021-10-31 00:53:49 -04:00
|
|
|
const reData = new RegExp("^data:([a-z0-9-]+/[a-z0-9-]+);base64,(.*)$", "i");
|
|
|
|
const dataMatch = ((url) ? url.match(reData): null);
|
|
|
|
if (dataMatch) {
|
|
|
|
try {
|
|
|
|
const response = {
|
|
|
|
statusCode: 200,
|
|
|
|
statusMessage: "OK",
|
|
|
|
headers: { "content-type": dataMatch[1] },
|
|
|
|
body: base64Decode(dataMatch[2])
|
|
|
|
};
|
|
|
|
|
|
|
|
let result: T = <T><unknown>response.body;
|
|
|
|
if (processFunc) {
|
|
|
|
result = processFunc(response.body, response);
|
|
|
|
}
|
|
|
|
return Promise.resolve(<T><unknown>result);
|
|
|
|
|
|
|
|
} catch (error) {
|
|
|
|
logger.throwError("processing response error", Logger.errors.SERVER_ERROR, {
|
|
|
|
body: bodyify(dataMatch[1], dataMatch[2]),
|
|
|
|
error: error,
|
|
|
|
requestBody: null,
|
|
|
|
requestMethod: "GET",
|
|
|
|
url: url
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2020-07-30 17:03:36 -04:00
|
|
|
if (body) {
|
2019-11-23 21:21:27 +09:00
|
|
|
options.method = "POST";
|
2020-07-30 17:03:36 -04:00
|
|
|
options.body = body;
|
|
|
|
if (headers["content-type"] == null) {
|
|
|
|
headers["content-type"] = { key: "Content-Type", value: "application/octet-stream" };
|
|
|
|
}
|
2020-09-11 01:10:53 -04:00
|
|
|
if (headers["content-length"] == null) {
|
|
|
|
headers["content-length"] = { key: "Content-Length", value: String(body.length) };
|
|
|
|
}
|
2019-11-23 21:21:27 +09:00
|
|
|
}
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2019-11-23 21:21:27 +09:00
|
|
|
const flatHeaders: { [ key: string ]: string } = { };
|
|
|
|
Object.keys(headers).forEach((key) => {
|
|
|
|
const header = headers[key];
|
|
|
|
flatHeaders[header.key] = header.value;
|
|
|
|
});
|
|
|
|
options.headers = flatHeaders;
|
2019-06-11 22:40:45 -04:00
|
|
|
|
2019-11-23 21:21:27 +09:00
|
|
|
const runningTimeout = (function() {
|
2020-02-04 00:50:27 -05:00
|
|
|
let timer: NodeJS.Timer = null;
|
2020-07-30 17:03:36 -04:00
|
|
|
const promise: Promise<never> = new Promise(function(resolve, reject) {
|
2019-11-23 21:21:27 +09:00
|
|
|
if (timeout) {
|
|
|
|
timer = setTimeout(() => {
|
|
|
|
if (timer == null) { return; }
|
|
|
|
timer = null;
|
|
|
|
|
2020-06-12 04:41:07 -04:00
|
|
|
reject(logger.makeError("timeout", Logger.errors.TIMEOUT, {
|
2020-09-05 04:29:08 -04:00
|
|
|
requestBody: bodyify(options.body, flatHeaders["content-type"]),
|
2020-06-12 04:41:07 -04:00
|
|
|
requestMethod: options.method,
|
|
|
|
timeout: timeout,
|
|
|
|
url: url
|
|
|
|
}));
|
2019-11-23 21:21:27 +09:00
|
|
|
}, timeout);
|
|
|
|
}
|
|
|
|
});
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2019-11-23 21:21:27 +09:00
|
|
|
const cancel = function() {
|
2019-05-14 18:25:46 -04:00
|
|
|
if (timer == null) { return; }
|
|
|
|
clearTimeout(timer);
|
|
|
|
timer = null;
|
|
|
|
}
|
|
|
|
|
2019-11-23 21:21:27 +09:00
|
|
|
return { promise, cancel };
|
|
|
|
})();
|
|
|
|
|
|
|
|
const runningFetch = (async function() {
|
|
|
|
|
2020-07-14 02:26:45 -04:00
|
|
|
for (let attempt = 0; attempt < attemptLimit; attempt++) {
|
|
|
|
let response: GetUrlResponse = null;
|
2019-11-23 21:21:27 +09:00
|
|
|
|
2020-07-14 02:26:45 -04:00
|
|
|
try {
|
|
|
|
response = await getUrl(url, options);
|
|
|
|
|
2021-11-30 19:11:03 -05:00
|
|
|
if (attempt < attemptLimit) {
|
|
|
|
if (response.statusCode === 301 || response.statusCode === 302) {
|
|
|
|
// Redirection; for now we only support absolute locataions
|
|
|
|
const location = response.headers.location || "";
|
|
|
|
if (options.method === "GET" && location.match(/^https:/)) {
|
|
|
|
url = response.headers.location;
|
|
|
|
continue;
|
|
|
|
}
|
2020-07-14 22:50:05 -04:00
|
|
|
|
2021-11-30 19:11:03 -05:00
|
|
|
} else if (response.statusCode === 429) {
|
|
|
|
// Exponential back-off throttling
|
|
|
|
let tryAgain = true;
|
|
|
|
if (throttleCallback) {
|
|
|
|
tryAgain = await throttleCallback(attempt, url);
|
2020-07-14 22:50:05 -04:00
|
|
|
}
|
|
|
|
|
2021-11-30 19:11:03 -05:00
|
|
|
if (tryAgain) {
|
|
|
|
let stall = 0;
|
|
|
|
|
|
|
|
const retryAfter = response.headers["retry-after"];
|
|
|
|
if (typeof(retryAfter) === "string" && retryAfter.match(/^[1-9][0-9]*$/)) {
|
|
|
|
stall = parseInt(retryAfter) * 1000;
|
|
|
|
} else {
|
|
|
|
stall = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
|
|
|
|
}
|
|
|
|
|
|
|
|
//console.log("Stalling 429");
|
|
|
|
await staller(stall);
|
|
|
|
continue;
|
|
|
|
}
|
2020-07-14 02:26:45 -04:00
|
|
|
}
|
|
|
|
}
|
2020-05-03 16:24:18 -04:00
|
|
|
|
2020-07-14 02:26:45 -04:00
|
|
|
} catch (error) {
|
|
|
|
response = (<any>error).response;
|
|
|
|
if (response == null) {
|
|
|
|
runningTimeout.cancel();
|
|
|
|
logger.throwError("missing response", Logger.errors.SERVER_ERROR, {
|
2020-09-05 04:29:08 -04:00
|
|
|
requestBody: bodyify(options.body, flatHeaders["content-type"]),
|
2020-07-14 02:26:45 -04:00
|
|
|
requestMethod: options.method,
|
|
|
|
serverError: error,
|
|
|
|
url: url
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
2019-11-23 21:21:27 +09:00
|
|
|
|
|
|
|
|
2020-07-14 02:26:45 -04:00
|
|
|
let body = response.body;
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2020-07-14 02:26:45 -04:00
|
|
|
if (allow304 && response.statusCode === 304) {
|
|
|
|
body = null;
|
2022-03-04 16:15:47 -05:00
|
|
|
} else if (!errorPassThrough && (response.statusCode < 200 || response.statusCode >= 300)) {
|
2020-07-14 02:26:45 -04:00
|
|
|
runningTimeout.cancel();
|
|
|
|
logger.throwError("bad response", Logger.errors.SERVER_ERROR, {
|
|
|
|
status: response.statusCode,
|
|
|
|
headers: response.headers,
|
2020-09-05 04:29:08 -04:00
|
|
|
body: bodyify(body, ((response.headers) ? response.headers["content-type"]: null)),
|
|
|
|
requestBody: bodyify(options.body, flatHeaders["content-type"]),
|
2020-06-12 04:41:07 -04:00
|
|
|
requestMethod: options.method,
|
2019-11-23 21:21:27 +09:00
|
|
|
url: url
|
|
|
|
});
|
|
|
|
}
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2020-07-30 17:03:36 -04:00
|
|
|
if (processFunc) {
|
2020-07-14 02:26:45 -04:00
|
|
|
try {
|
2020-07-30 17:03:36 -04:00
|
|
|
const result = await processFunc(body, response);
|
2020-07-14 02:26:45 -04:00
|
|
|
runningTimeout.cancel();
|
2020-07-30 17:03:36 -04:00
|
|
|
return result;
|
2019-05-14 18:25:46 -04:00
|
|
|
|
2020-07-14 02:26:45 -04:00
|
|
|
} catch (error) {
|
|
|
|
// Allow the processFunc to trigger a throttle
|
|
|
|
if (error.throttleRetry && attempt < attemptLimit) {
|
|
|
|
let tryAgain = true;
|
|
|
|
if (throttleCallback) {
|
|
|
|
tryAgain = await throttleCallback(attempt, url);
|
|
|
|
}
|
|
|
|
|
|
|
|
if (tryAgain) {
|
2020-07-14 22:50:05 -04:00
|
|
|
const timeout = throttleSlotInterval * parseInt(String(Math.random() * Math.pow(2, attempt)));
|
2020-07-30 17:03:36 -04:00
|
|
|
//console.log("Stalling callback");
|
2020-07-14 02:26:45 -04:00
|
|
|
await staller(timeout);
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
runningTimeout.cancel();
|
|
|
|
logger.throwError("processing response error", Logger.errors.SERVER_ERROR, {
|
2020-09-05 04:29:08 -04:00
|
|
|
body: bodyify(body, ((response.headers) ? response.headers["content-type"]: null)),
|
2020-07-14 02:26:45 -04:00
|
|
|
error: error,
|
2020-09-05 04:29:08 -04:00
|
|
|
requestBody: bodyify(options.body, flatHeaders["content-type"]),
|
2020-07-14 02:26:45 -04:00
|
|
|
requestMethod: options.method,
|
|
|
|
url: url
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
runningTimeout.cancel();
|
2020-07-30 17:03:36 -04:00
|
|
|
|
2021-10-04 11:46:24 -04:00
|
|
|
// If we had a processFunc, it either returned a T or threw above.
|
2020-07-30 17:03:36 -04:00
|
|
|
// The "body" is now a Uint8Array.
|
|
|
|
return <T>(<unknown>body);
|
2020-07-14 02:26:45 -04:00
|
|
|
}
|
2020-07-30 17:03:36 -04:00
|
|
|
|
|
|
|
return logger.throwError("failed response", Logger.errors.SERVER_ERROR, {
|
2020-09-05 04:29:08 -04:00
|
|
|
requestBody: bodyify(options.body, flatHeaders["content-type"]),
|
2020-07-30 17:03:36 -04:00
|
|
|
requestMethod: options.method,
|
|
|
|
url: url
|
|
|
|
});
|
2019-11-23 21:21:27 +09:00
|
|
|
})();
|
|
|
|
|
|
|
|
return Promise.race([ runningTimeout.promise, runningFetch ]);
|
2019-05-14 18:25:46 -04:00
|
|
|
}
|
|
|
|
|
2020-07-30 17:03:36 -04:00
|
|
|
export function fetchJson(connection: string | ConnectionInfo, json?: string, processFunc?: (value: any, response: FetchJsonResponse) => any): Promise<any> {
|
|
|
|
let processJsonFunc = (value: Uint8Array, response: FetchJsonResponse) => {
|
|
|
|
let result: any = null;
|
|
|
|
if (value != null) {
|
|
|
|
try {
|
|
|
|
result = JSON.parse(toUtf8String(value));
|
|
|
|
} catch (error) {
|
|
|
|
logger.throwError("invalid JSON", Logger.errors.SERVER_ERROR, {
|
|
|
|
body: value,
|
|
|
|
error: error
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (processFunc) {
|
|
|
|
result = processFunc(result, response);
|
|
|
|
}
|
|
|
|
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
|
|
|
|
// If we have json to send, we must
|
|
|
|
// - add content-type of application/json (unless already overridden)
|
|
|
|
// - convert the json to bytes
|
|
|
|
let body: Uint8Array = null;
|
|
|
|
if (json != null) {
|
|
|
|
body = toUtf8Bytes(json);
|
|
|
|
|
|
|
|
// Create a connection with the content-type set for JSON
|
2020-08-04 20:49:40 -04:00
|
|
|
const updated: ConnectionInfo = (typeof(connection) === "string") ? ({ url: connection }): shallowCopy(connection);
|
2020-07-30 17:03:36 -04:00
|
|
|
if (updated.headers) {
|
|
|
|
const hasContentType = (Object.keys(updated.headers).filter((k) => (k.toLowerCase() === "content-type")).length) !== 0;
|
|
|
|
if (!hasContentType) {
|
|
|
|
updated.headers = shallowCopy(updated.headers);
|
|
|
|
updated.headers["content-type"] = "application/json";
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
updated.headers = { "content-type": "application/json" };
|
|
|
|
}
|
|
|
|
connection = updated;
|
|
|
|
}
|
|
|
|
|
2020-07-31 01:15:22 -04:00
|
|
|
return _fetchData<any>(connection, body, processJsonFunc);
|
2020-07-30 17:03:36 -04:00
|
|
|
}
|
|
|
|
|
2020-05-20 23:42:08 -04:00
|
|
|
export function poll<T>(func: () => Promise<T>, options?: PollOptions): Promise<T> {
|
2019-05-14 18:25:46 -04:00
|
|
|
if (!options) { options = {}; }
|
|
|
|
options = shallowCopy(options);
|
|
|
|
if (options.floor == null) { options.floor = 0; }
|
|
|
|
if (options.ceiling == null) { options.ceiling = 10000; }
|
|
|
|
if (options.interval == null) { options.interval = 250; }
|
|
|
|
|
|
|
|
return new Promise(function(resolve, reject) {
|
|
|
|
|
2020-02-04 00:50:27 -05:00
|
|
|
let timer: NodeJS.Timer = null;
|
2019-05-14 18:25:46 -04:00
|
|
|
let done: boolean = false;
|
|
|
|
|
|
|
|
// Returns true if cancel was successful. Unsuccessful cancel means we're already done.
|
2019-11-01 23:33:51 +09:00
|
|
|
const cancel = (): boolean => {
|
2019-05-14 18:25:46 -04:00
|
|
|
if (done) { return false; }
|
|
|
|
done = true;
|
|
|
|
if (timer) { clearTimeout(timer); }
|
|
|
|
return true;
|
|
|
|
};
|
|
|
|
|
|
|
|
if (options.timeout) {
|
|
|
|
timer = setTimeout(() => {
|
|
|
|
if (cancel()) { reject(new Error("timeout")); }
|
|
|
|
}, options.timeout)
|
|
|
|
}
|
|
|
|
|
2019-11-01 23:33:51 +09:00
|
|
|
const retryLimit = options.retryLimit;
|
2019-05-14 18:25:46 -04:00
|
|
|
|
|
|
|
let attempt = 0;
|
|
|
|
function check() {
|
|
|
|
return func().then(function(result) {
|
|
|
|
|
|
|
|
// If we have a result, or are allowed null then we're done
|
|
|
|
if (result !== undefined) {
|
|
|
|
if (cancel()) { resolve(result); }
|
|
|
|
|
2020-05-04 22:43:44 -04:00
|
|
|
} else if (options.oncePoll) {
|
|
|
|
options.oncePoll.once("poll", check);
|
|
|
|
|
2019-05-14 18:25:46 -04:00
|
|
|
} else if (options.onceBlock) {
|
|
|
|
options.onceBlock.once("block", check);
|
|
|
|
|
|
|
|
// Otherwise, exponential back-off (up to 10s) our next request
|
|
|
|
} else if (!done) {
|
|
|
|
attempt++;
|
|
|
|
if (attempt > retryLimit) {
|
|
|
|
if (cancel()) { reject(new Error("retry limit reached")); }
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
let timeout = options.interval * parseInt(String(Math.random() * Math.pow(2, attempt)));
|
|
|
|
if (timeout < options.floor) { timeout = options.floor; }
|
|
|
|
if (timeout > options.ceiling) { timeout = options.ceiling; }
|
|
|
|
|
|
|
|
setTimeout(check, timeout);
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}, function(error) {
|
|
|
|
if (cancel()) { reject(error); }
|
|
|
|
});
|
|
|
|
}
|
|
|
|
check();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|