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
WebSocketProvider handle ws close and reconnect #1053
Comments
This is a very large feature... When I first (begrudgingly) added WebSocketProvider mentioned this would be something I would eventually get to, but that it won't be high priority any time soon. :) But I want to! :) It is still on the backlog, and I'll use this issue to track it, but there are other things I need to work on first. Keep in mind when you reconnect, you may have been disconnected for a long time, in which case you should find and trigger events that were missed; you may have also been down fo a short period of time, in which case you must dedup events you've already emitted. Also, earlier events should be emitted before later ones. Unless there was a re-org, exactly-once semantics should be adhered to. All subscriptions will need some custom logic, depending on the type of subscription to handle this. Also ethers providers guarantee consistent read-after-events. So, if a block number X has been emitted, a call to Also keep special note of Basically, it's a feature I really want too, but I know it's going to take considerable time to complete and properly test. I just wanted to give some background on the complexity. |
I think this is probably the best solution: const EXPECTED_PONG_BACK = 15000
const KEEP_ALIVE_CHECK_INTERVAL = 7500
export const startConnection = () => {
provider = new ethers.providers.WebSocketProvider(config.ETH_NODE_WSS)
let pingTimeout = null
let keepAliveInterval = null
provider._websocket.on('open', () => {
keepAliveInterval = setInterval(() => {
logger.debug('Checking if the connection is alive, sending a ping')
provider._websocket.ping()
// Use `WebSocket#terminate()`, which immediately destroys the connection,
// instead of `WebSocket#close()`, which waits for the close timer.
// Delay should be equal to the interval at which your server
// sends out pings plus a conservative assumption of the latency.
pingTimeout = setTimeout(() => {
provider._websocket.terminate()
}, EXPECTED_PONG_BACK)
}, KEEP_ALIVE_CHECK_INTERVAL)
// TODO: handle contract listeners setup + indexing
})
provider._websocket.on('close', () => {
logger.error('The websocket connection was closed')
clearInterval(keepAliveInterval)
clearTimeout(pingTimeout)
startConnection()
})
provider._websocket.on('pong', () => {
logger.debug('Received pong, so connection is alive, clearing the timeout')
clearInterval(pingTimeout)
})
} This send a ping every 15 seconds, when it sends a ping, it expects a pong back within 7.5 seconds otherwise it closes the connection and calls the main Where it says Fine tune these timing vars to taste, depending on who your Node provider is, this are the settings I use for QuikNode const EXPECTED_PONG_BACK = 15000
const KEEP_ALIVE_CHECK_INTERVAL = 7500 |
To elaborate on @mikevercoelen's answer, I extracted the logic to a function
Then in my code, i get:
|
We're two months in and the code mentioned before, has been running steadily on our node :) 0 downtime. |
Really cool ! Thanks again for sharing :) |
@mikevercoelen I'm using ethers 5.0.32 and the websocket provider doesn't have the 'on' method which really hampers implementing your solution ;). What version of ethers are you using? |
There should definitely be an |
Ok well I'm not sure what's going on. Its definitely not there, I'm seeing an interface for Is there typo in the code above? Perhaps instead of |
Oh! Sorry, yes. In general you should use It depends on your environment what your If your goal is to enable automatic reconnect, this is not something that is simple to do in a safe way, so make sure you test it thoroughly. :) |
We are actually using alchemy so was able to just use their web3 websocket provider and plugged it into our ethers ecosystem with ethers.provider.Web3Provider. they handle all the reconnects and even dropped calls very gracefully. |
@rrecuero I ran into the same problem and I'm still not sure how that code above works :P |
The solution of the @mikevercoelen didn't worked on me maybe because I'm using the browser version of WebSocket so for me the workaround was writing a custom class that reconnect's everytime the connection closes. const ethers = require("ethers");
class ReconnectableEthers {
/**
* Constructs the class
*/
constructor() {
this.provider = undefined;
this.wallet = undefined;
this.account = undefined;
this.config = undefined;
this.KEEP_ALIVE_CHECK_INTERVAL = 1000;
this.keepAliveInterval = undefined;
this.pingTimeout = undefined;
}
/**
* Load assets.
* @param {Object} config Config object.
*/
load(config) {
this.config = config;
this.provider = new ethers.providers.WebSocketProvider(this.config["BSC_PROVIDER_ADDRESS"])
this.wallet = new ethers.Wallet(this.config["PRIVATE_KEY"]);
this.account = this.wallet.connect(this.provider);
this.defWsOpen = this.provider._websocket.onopen;
this.defWsClose = this.provider._websocket.onclose;
this.provider._websocket.onopen = (event) => this.onWsOpen(event);
this.provider._websocket.onclose = (event) => this.onWsClose(event);
}
/**
* Check class is loaded.
* @returns Bool
*/
isLoaded() {
if (!this.provider) return false;
return true;
}
/**
* Triggered when provider's websocket is open.
*/
onWsOpen(event) {
console.log("Connected to the WS!");
this.keepAliveInterval = setInterval(() => {
if (
this.provider._websocket.readyState === WebSocket.OPEN ||
this.provider._websocket.readyState === WebSocket.OPENING
) return;
this.provider._websocket.close();
}, this.KEEP_ALIVE_CHECK_INTERVAL)
if (this.defWsOpen) this.defWsOpen(event);
}
/**
* Triggered on websocket termination.
* Tries to reconnect again.
*/
onWsClose(event) {
console.log("WS connection lost! Reconnecting...");
clearInterval(this.keepAliveInterval)
this.load(this.config);
if (this.defWsClose) this.defWsClose(event);
}
}
module.exports = ReconnectableEthers; |
@tarik0 i'm running WebSocket on browser too, that's exactly what I need, thank you |
I implemented @mikevercoelen's method and it works perfectly. Thank you! Question, though: Where is the |
@Dylan-Kerler thanks, it is definitely cleaner. I agree with your point for most use cases. But if you need certain consistency guarantees, have a read of @ricmoo's concerns on #1053 (comment). Which the web3 client won't handle. |
Hello all. Is there plans to implement his on a near future? Thanks! |
This is harder to implement then it looks on the surface if you want to include:
None of the solutions (including the web3-provider, which also as a lot of other downsides) posted in here cover this properly so far. There are resilient, generic websocket implementations out there already (not json-rpc specific) that this could be built around. The only thing that would have to be custom-built in ethers would be tracking of active subscriptions to re-establish those on reconnect. There's https://github.com/pladaria/reconnecting-websocket which could use some cleanup and modernization but is otherwise rather robust. Could make sense to fork / integrate that into ethers.js with the json-rpc specifics simply built around it . |
Thanks a lot, def. the answer i was looking for ! works like a charm. |
So I've tried this solution to mitigate connection hang using websocket provider. It indeed have worked out, BUT Im listening on 'block' method, and then calling eth_getBlockByNumber using other HTTP provider. Over 24 hours using InfuraWebsocket provider that may hang, my daily request count was 10k. What a surprise I had when my daily limit of 100k has been reached, after using this provider implementation. Havent dig why that happened yet |
Hey, did you manage to get this to work in node.js? Maybe this is because you used or code in React with TypeScript or something like that? |
I made a workaround like this: created a custom |
I also found a problem, when using wss nodes of some third-party nodes, when some limits are exceeded, non-standard json objects are returned, such as limit or xxxxx limit. So the |
I would like to add a error event handle to deal with like DNS error: Error: getaddrinfo ENOTFOUND
|
How to use this solution with nodejs and import? I have created a obviously importing a i don't know how to proceed, use babel? convert all app to ts? to use require instead of import? I'm looking for the best solution. |
Here is my take: import { WebSocketProvider } from '@ethersproject/providers'
const PING_INTERVAL = 20000
const PONG_EXPECTED = 10000
export class EthereumWebSocketConnection {
constructor(url, network, logger) {
this.provider = null
this.url = url
this.network = network
this.logger = logger
/** Timers for ping and expected pong */
this._pingTimeout = null
this._keepAliveInterval = null
/** Function that will be called when the WebSocket is connected */
this._connected = null
/** Function that when called will remove listeners from ws provider */
this._disconnected = null
/** Fix events binding for on/off correctly */
this.onError = this.onError.bind(this)
this.onPong = this.onPong.bind(this)
this.onOpen = this.onOpen.bind(this)
this.onClose = this.onClose.bind(this)
}
onError(err) {
this.logger.error({ err }, 'Ethereum error')
}
onPong() {
if (this._pingTimeout) {
clearTimeout(this._pingTimeout)
this._pingTimeout = null
}
}
onOpen() {
if (!this.provider) {
return
}
/** Initial ping before first interval */
this.provider._websocket.ping()
this._keepAliveInterval = setInterval(
() => {
this.provider._websocket.ping()
this._pingTimeout = setTimeout(
() => {
/** Use `WebSocket#terminate()`, which immediately destroys the
* connection, instead of `WebSocket#close()`, which waits for
* the close timer */
this.provider._websocket.terminate()
},
PONG_EXPECTED
)
},
PING_INTERVAL
)
if (this._connected) {
this._disconnected = this._connected(this.provider)
}
}
onClose() {
/** Re-connect automatically */
this.disconnect().then(() => this.connect()).catch((err) => {
this.logger.error({ err }, 'Ethereum re-connecting error')
})
}
async connect(connected) {
if (connected) {
this._connected = connected
}
if (!this.provider) {
try {
/** Connect to Web Socket provider */
this.provider = new WebSocketProvider(this.url, this.network)
this.provider.on('error', this.onError)
this.provider._websocket.on('pong', this.onPong)
this.provider._websocket.on('open', this.onOpen)
this.provider._websocket.on('close', this.onClose)
} catch (err) {
this.logger.error({ err }, 'Ethereum connecting error')
/** Try again when the connection failed the first time */
setTimeout(() => this.connect(), 100)
}
}
}
async disconnect() {
if (this._keepAliveInterval) {
clearInterval(this._keepAliveInterval)
this._keepAliveInterval = null
}
if (this._pingTimeout) {
clearTimeout(this._pingTimeout)
this._pingTimeout = null
}
if (this.provider) {
if (this._disconnected) {
this._disconnected(this.provider)
this._disconnected = null
}
this.provider.off('error', this.onError)
this.provider._websocket.off('pong', this.onPong)
this.provider._websocket.off('open', this.onOpen)
this.provider._websocket.off('close', this.onClose)
await this.provider.destroy()
this.provider = null
}
}
} Use it: await ethereum.connect((provider) => {
provider.on(filter, handler)
return (provider) => {
provider.off(filter, handler)
}
}) |
change index's extension from index.js to index.mjs |
Could you provide your code snippet here? Are you using the Alchemy SDK? We found we had dropped transactions if we decided to use the ethers websocket! |
It's pretty easy to use SturdyWebSocket. import SturdyWebSocket from "sturdy-websocket"
...
new ethers.providers.WebSocketProvider(
new SturdyWebSocket(this.appEnv$.wsRPCUrl),
{
name: this.appEnv$.chainName,
chainId: this.appEnv$.chainId
}
)
... and we have the reconnecting websocket |
Not sure if this helps - but to get @mikevercoelen solution to work, as well as listen for contract events, I needed to be sure that
... and not before. @tarik0 solution also looks very nice. |
Hi, I'm facing a similar issue, but not sure if its entirely related so I've created a SO post. Basically I have dynamic contract addresses and need to listen to their
The txn is logged when the app starts but after 5mins, it stops calling the callback. I cannot do as said by @58bits because my contract addresses are dynamic and I'm create websocket connection at server start, so cannot do it in the https://ethereum.stackexchange.com/questions/149750/cannot-listen-to-contract-events-with-ethers-js |
Thanks, this solution works indeed. If anyone's having trouble with setting up SturdyWebSocket on Node.js refer to this -> dphilipson/sturdy-websocket#25 (comment) |
how to update it with ethers v6? currently this code is deprecated
|
It looks like the main goal is to configure the WebSocket (including some extra WebSocket events). In v6, you can pass in a function like: const configWebSocket = () => {
const ws = new WebSocket(url);
// Do config…
ws.on(…);
return ws;
};
const provider = new WebSocketProvider(configWebSocket); That callback will be used whenever it need to reconnect, and in the next minor bump that will be used on disconnect to resubscribe to events. |
ricmoo does that mean that the new websocket provider will automatically reconnect and resubscribe to subscriptions? |
Hello, can you please add the reconnection functionality on the WebSocketProvider class to work by default or to have some option to enable/disable it. It is a must feature for every websocket connection. Thank you |
@ricmoo I think you may have missed the main goal of this thread. Above was a fix for ethers v5 to make WebsocketProvider reconnect on disconnect. This issue has reappeared in v6 (See code below. Onclose is commented out in main 5a56fc3) Do you have time to implement this or would it help to have it lifted off your plate?
|
It's not pretty. but I used
Then used ethers5 with the websocket.ts code @ubuntutest mentioned for my Websocket provider, and ethers 6.7.1 for everything else. |
For V6 with reconnection to WebSocket every 100ms ( Will throw when the failure reaches 5 times for a single reconnection attempt ) isomorphic-ws is used to initiate new WebSocket object since sharing socket listeners cause issue on Node.js with my previous experience ( The code works from the browser-side or react-native as well ) const WebSocket = require('isomorphic-ws');
const { WebSocketProvider, SocketBlockSubscriber } = require('ethers');
const sleep = ms => new Promise(r => setTimeout(r, ms));
// Testing WebSocket on connection / reconnection before initiating new provider to prevent deadlock
const testWS = async (url, reconnectDelay = 100) => {
const MAX_RETRY = 5;
let retry = 0;
let errorObject;
while (retry < MAX_RETRY + 1) {
try {
return await new Promise((resolve, reject) => {
const socket = new WebSocket(url);
socket.onopen = () => {
socket.send(JSON.stringify([
{
jsonrpc: '2.0',
method: 'eth_chainId',
params: [],
id: 1
},
{
jsonrpc: '2.0',
method: 'eth_getBlockByNumber',
params: ['latest', false],
id: 2
}
]));
};
socket.onmessage = (event) => {
const data = JSON.parse(event.data);
resolve({
chainId: Number(data[0]?.result),
block: data[1]?.result,
});
};
socket.onerror = (e) => {
reject(e);
};
});
} catch (e) {
console.log(`Connection to ${url} failed, attempt: (${retry} of ${MAX_RETRY})`);
await sleep(reconnectDelay);
errorObject = e;
retry++;
}
}
throw errorObject;
}
const connectWS = async (url, reconnectDelay = 100) => {
// Test websocket connection to prevent WebSocketProvider deadlock caused by await this._start();
const { chainId, block } = await testWS(url, reconnectDelay);
console.log(`WebSocket ${url} connected: Chain ${chainId} Block ${Number(block?.number)}`);
const provider = new WebSocketProvider(url);
const blockSub = new SocketBlockSubscriber(provider);
provider.websocket.onclose = (e) => {
console.log(`Socket ${url} is closed, reconnecting in ${reconnectDelay} ms`);
setTimeout(() => connectWS(url, reconnectDelay), reconnectDelay);
}
provider.websocket.onerror = (e) => {
console.error(`Socket ${url} encountered error, reconnecting it:\n${e.stack || e.message}`);
blockSub.stop();
provider.destroy();
}
blockSub._handleMessage = (result) => {
console.log(provider._wrapBlock({...result, transactions: []}));
};
blockSub.start();
provider.on('pending', (tx) => {
console.log(`New pending tx: ${tx}`)
});
}
connectWS('wss://ethereum.publicnode.com'); |
+1 v6 |
I've found a way to implement that old solution on import { Networkish, WebSocketProvider } from "ethers";
import WebSocket from "ws";
const EXPECTED_PONG_BACK = 15000;
const KEEP_ALIVE_CHECK_INTERVAL = 60 * 1000; //7500;
const debug = (message: string) => {
console.debug(new Date().toISOString(), message);
};
export const ResilientWebsocket = (
url: string,
network: Networkish,
task: (provider: WebSocketProvider) => void
) => {
let terminate = false;
let pingTimeout: NodeJS.Timeout | null = null;
let keepAliveInterval: NodeJS.Timeout | null = null;
let ws: WebSocket | null;
const sleep = (ms: number) =>
new Promise((resolve) => setTimeout(resolve, ms));
const startConnection = () => {
ws = new WebSocket(url);
ws.on("open", async () => {
keepAliveInterval = setInterval(() => {
if (!ws) {
debug("No websocket, exiting keep alive interval");
return;
}
debug("Checking if the connection is alive, sending a ping");
ws.ping();
// Use `WebSocket#terminate()`, which immediately destroys the connection,
// instead of `WebSocket#close()`, which waits for the close timer.
// Delay should be equal to the interval at which your server
// sends out pings plus a conservative assumption of the latency.
pingTimeout = setTimeout(() => {
if (ws) ws.terminate();
}, EXPECTED_PONG_BACK);
}, KEEP_ALIVE_CHECK_INTERVAL);
const wsp = new WebSocketProvider(() => ws!, network);
while (ws?.readyState !== WebSocket.OPEN) {
debug("Waiting for websocket to be open");
await sleep(1000);
}
wsp._start();
while (!wsp.ready) {
debug("Waiting for websocket provider to be ready");
await sleep(1000);
}
task(wsp);
});
ws.on("close", () => {
console.error("The websocket connection was closed");
if (keepAliveInterval) clearInterval(keepAliveInterval);
if (pingTimeout) clearTimeout(pingTimeout);
if (!terminate) startConnection();
});
ws.on("pong", () => {
debug("Received pong, so connection is alive, clearing the timeout");
if (pingTimeout) clearInterval(pingTimeout);
});
return ws;
};
startConnection();
return () => {
terminate = true;
if (keepAliveInterval) clearInterval(keepAliveInterval);
if (pingTimeout) clearTimeout(pingTimeout);
if (ws) {
ws.removeAllListeners();
ws.terminate();
}
};
}; Usage: terminate = ResilientWebsocket(
WEBSOCKET_URL,
Number(CHAIN_ID),
async (provider) => {
console.log("connected");
}
); So, you can terminate your process anytime using |
The solution is not working anymore as the onclose func of the websocket provider is commented out in the package |
Solution: #1053 (comment) |
Has there been further progress on this thread? |
As I can see, the ethers.js owner preferred to let users to implement himself the websocket reconnection strategy, |
Hi @ricmoo,
I'm using WebSocketProvider server-side to listen to blockchain events and performing calls to smart contracts.
Sometimes the websocket pipe got broken and I need to reconnect it.
I use this code to detect ws close and reconnect but it would be nice to not have to rely on
_websocket
to do it:I also noticed when the websocket is broken Promise call don't reject wich is not super intuitive.
The text was updated successfully, but these errors were encountered: