Make disconnects graceful

This commit is contained in:
Starbeamrainbowlabs 2022-01-09 17:46:43 +00:00
parent 43fed309dc
commit a9a7320a1e
Signed by: sbrl
GPG key ID: 1BE5172E637709C2
2 changed files with 16 additions and 3 deletions

View file

@ -39,6 +39,10 @@ class Peer extends EventEmitter {
* @type {{address:string,port:number}[]} * @type {{address:string,port:number}[]}
*/ */
this.known_peers = []; this.known_peers = [];
// If a message with the event name "end" is received, close our side
// of the connection
this.once(`message-end`, this.destroy);
} }
/////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////
@ -90,9 +94,16 @@ class Peer extends EventEmitter {
l.warn(`Our id (${this.server.our_id}) is equal to that of the remote (${this.id}), killing connection`); l.warn(`Our id (${this.server.our_id}) is equal to that of the remote (${this.id}), killing connection`);
return false; return false;
} }
this.connection.on("message", this.__handle_message.bind(this));
return true; return true;
} }
__handle_message(event_name, msg) {
this.emit("message", event_name, msg);
this.emit(`message-${event_name}`, msg);
}
/** /**
* Sends a hello message to this peer. * Sends a hello message to this peer.
* @return {Promise} A Promise that resolves when the sending of the message is complete. * @return {Promise} A Promise that resolves when the sending of the message is complete.
@ -123,6 +134,8 @@ class Peer extends EventEmitter {
* @return {Promise} A Promise that resolves once the connection is closed. * @return {Promise} A Promise that resolves once the connection is closed.
*/ */
async destroy() { async destroy() {
// TODO: If this takes too long, we should just ignore it and move on
await this.send("end", "goodbye");
await this.connection.destroy(); await this.connection.destroy();
this.emit("destroy"); this.emit("destroy");
this.removeAllListeners(); this.removeAllListeners();

View file

@ -86,9 +86,9 @@ class PeerServer extends EventEmitter {
this.emit("peer", peer); this.emit("peer", peer);
} }
async handle_message(peer, message) { async handle_message(peer, event_name, msg) {
this.emit("message", peer, message); this.emit("message", peer, event_name, msg);
this.emit(`message-${message.event}`, peer, message.message); this.emit(`message-${event_name}`, peer, msg);
} }
async handle_destroy(peer) { async handle_destroy(peer) {