polkascan / py-substrate-interface

Python Substrate Interface
https://polkascan.github.io/py-substrate-interface/
Apache License 2.0
240 stars 114 forks source link

How to understand is websocket is alive? #183

Closed johnuopini closed 2 years ago

johnuopini commented 2 years ago

As pointed out in another issue i am being disconnected when idle using public endpoints, is there any way to check if connection is there without making a call? Catching broken pipe in the app logic doesn't work in my use case. An approach i will try is to use a decorator in API related methods so i will reconnect if needed but maybe this can be handled by the library.

arjanz commented 2 years ago

You could try to ping the websocket before you send a call and reconnect if an exception is raised:

try:
    substrate.websocket.ping()
except (WebSocketConnectionClosedException, ConnectionRefusedError,
        WebSocketBadStatusException, BrokenPipeError, SubstrateRequestException) as e:
    # reestablish connection
    substrate.connect_websocket()

Let me know if this works, then I can implement this in the library to automatically have this behaviour

johnuopini commented 2 years ago

I see now an auto_reconnect options is available so i assume this will fix it, anyway i also did fix it in my end by using an @apicall decorator that basically handles a broken pipe error and reconnects, i will still use it because it also allows me to change endpoint while I do so. Thanks for your support!