*Add a timeout for querying a relay with rejection

This commit is contained in:
Derrick Hammer 2022-07-23 11:41:58 -04:00
parent c7eede8435
commit 563173bd95
1 changed files with 14 additions and 5 deletions

View File

@ -3,7 +3,7 @@ import RpcNetwork from "./rpcNetwork.js";
import { pack, unpack } from "msgpackr"; import { pack, unpack } from "msgpackr";
import { RPCRequest, RPCResponse } from "./types"; import { RPCRequest, RPCResponse } from "./types";
import { Buffer } from "buffer"; import { Buffer } from "buffer";
import {blake2b} from "libskynet" import { blake2b } from "libskynet";
export default class RpcQuery { export default class RpcQuery {
private _network: RpcNetwork; private _network: RpcNetwork;
@ -76,7 +76,9 @@ export default class RpcQuery {
return; return;
} }
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let timer: NodeJS.Timeout;
socket.on("data", (res: Buffer) => { socket.on("data", (res: Buffer) => {
clearTimeout(timer);
socket.end(); socket.end();
const response = unpack(res); const response = unpack(res);
if (response && response.error) { if (response && response.error) {
@ -88,6 +90,9 @@ export default class RpcQuery {
socket.on("error", (error: any) => reject({ error })); socket.on("error", (error: any) => reject({ error }));
socket.write("rpc"); socket.write("rpc");
socket.write(pack(this._query)); socket.write(pack(this._query));
timer = setTimeout(() => {
reject("timeout");
}, this._network.relayTimeout * 1000);
}); });
} }
@ -99,13 +104,17 @@ export default class RpcQuery {
type ResponseGroup = { [response: string]: number }; type ResponseGroup = { [response: string]: number };
const responseObjects = responseStoreData.reduce((output: any, item) => { const responseObjects = responseStoreData.reduce((output: any, item) => {
const hash = Buffer.from(blake2b(Buffer.from(JSON.stringify(item?.data)))).toString("hex"); const hash = Buffer.from(
blake2b(Buffer.from(JSON.stringify(item?.data)))
).toString("hex");
output[hash] = item?.data; output[hash] = item?.data;
return output; return output;
}, {}); }, {});
const responses: ResponseGroup = responseStoreData.reduce( const responses: ResponseGroup = responseStoreData.reduce(
(output: ResponseGroup, item) => { (output: ResponseGroup, item) => {
const hash = Buffer.from(blake2b(Buffer.from(JSON.stringify(item?.data)))).toString("hex"); const hash = Buffer.from(
blake2b(Buffer.from(JSON.stringify(item?.data)))
).toString("hex");
output[hash] = output[hash] ?? 0; output[hash] = output[hash] ?? 0;
output[hash]++; output[hash]++;
return output; return output;