add timeout for chain request

This commit is contained in:
CounterFire2023 2024-01-15 19:01:42 +08:00
parent b97469fa21
commit eda5df70c0
2 changed files with 17 additions and 8 deletions

View File

@ -1,5 +1,15 @@
import fetch from "node-fetch"
import { retry } from 'utils/promise.util'
// AbortController was added in node v14.17.0 globally
const AbortController = globalThis.AbortController
const request = async (url: string, options: any) => {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), 30000)
const res = await fetch(url, { ...options, signal: controller.signal })
clearTimeout(timeout)
return res
}
const requestChain = async (rpc: string, method: string, params: any) => {
const data = {
@ -8,7 +18,7 @@ const requestChain = async (rpc: string, method: string, params: any) => {
method,
params
}
return fetch(rpc, {
return request(rpc, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
@ -48,8 +58,7 @@ export const _batchEthBlocks = async (rpc: string, blockNumber: number, amount:
id: blockNumber + i
})
}
return fetch(rpc, {
return request(rpc, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
@ -70,7 +79,7 @@ export const batchEthBlocks = async (rpc: string, blockNumbers: number[]) => {
})
}
return fetch(rpc, {
return request(rpc, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
@ -81,7 +90,7 @@ export const batchEthBlocks = async (rpc: string, blockNumbers: number[]) => {
}
export const batchEthLogs = async (rpc: string, params: any) => {
return fetch(rpc, {
return request(rpc, {
method: "POST",
headers: {
"Content-Type": "application/json; charset=utf-8"
@ -89,4 +98,4 @@ export const batchEthLogs = async (rpc: string, params: any) => {
body: JSON.stringify(params)
})
.then((res) => res.json())
}
}

View File

@ -58,7 +58,7 @@ export async function getPastBlocks({chainId, rpc, fromBlock, amount}
if (retryCount > 0) {
blocks.sort((a, b) => parseInt(a.number) - parseInt(b.number))
}
await new RedisClient().set(redisKey, blockNumber + realAmount + '')
await new RedisClient().set(redisKey, blockNumber + amount + '')
await new Promise(resolve => setTimeout(resolve, REQUEST_INTERVAL))
} catch (e) {
logger.log(e.message || e)
@ -168,4 +168,4 @@ export const buildScriptionFilters = (cfg: IScriptionCfg) => {
}
return new Function('event', `return ${body}`)
}
}
}