nknorg / nkn-sdk-js

JavaScript Implementation of NKN Client and Wallet SDK
Apache License 2.0
43 stars 17 forks source link

sessions and memory #121

Open sce9sc opened 1 year ago

sce9sc commented 1 year ago

I have 2 multiclients created and the first one dials the second . When I switch off the wifi on my laptop and turn on again I get the below results: 1) I get connected but with errors " NotHandshakeError: first packet is not handshake packet" 2) I see that I have now 2 sessions "client.sessions" 3) memory is increased (from 40 to 50 ) and if a switch on and off several time I get more 200+ 4) if switching the wifi several times all the above are multiplied . 5) I do not get a websocket error or a disconnection error

Should the sessions be cleared when no websocket connection exists ? Even if I manually close the session . (await session.close()) the sessions Map still has the session.

What is the proper way to handle such scenarios where there is loss of connectivity ?

yilunzhang commented 1 year ago

Sessions will not disconnect or clear itself because the underlying nkn client will always try auto reconnect when it detects anything wrong. After reconnect success, the session should be able to send and receive data again. In your case (turn wifi off and on), it will take a long time for the websocket conn to know the connection is cut as it's waiting for browser/OS to send onclose signal. But eventually when it receives the signal from browser/OS it will reconnect.

In theory websocket has a ping/pong mechanism that could be used to detect network loss much faster, but browser websocket API doesn't expose that (it just responds to ping message automatically), so we can't use that like we do in nkn-sdk-go.

Even if I manually close the session . (await session.close()) the sessions Map still has the session.

client.sessions is not meant to be cleared even after sessions are closed to prevent old messages from creating duplicate sessions (network issue or attacks).

I see that I have now 2 sessions "client.sessions"

Do you mean you only dialed one session, but saw two objects in client.sessions?

memory is increased (from 40 to 50 ) and if a switch on and off several time I get more 200+

That's definitely something to look into. Will memory usage drop back to normal after you close the session?

What is the proper way to handle such scenarios where there is loss of connectivity ?

One common way to detect potential network loss without relying on browser/OS is to have an application layer ping message that sends regularly. Then you can use session.setReadTimeout to set a timeout before each read call. If you don't receive anything after, for example, 2-3 ping interval, then there is probably something wrong with the network.