Skip to content

Commit

Permalink
refactor: simplify neighbor check with while loop
Browse files Browse the repository at this point in the history
  • Loading branch information
DIY0R committed Oct 19, 2024
1 parent ff2a1f4 commit 0374240
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 4 deletions.
14 changes: 12 additions & 2 deletions lib/constants.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
const HANDSHAKE = 'HANDSHAKE';
const DM = 'MESSAGE';
const DM = 'MES SAGE';
const CHECK_INTERVAL = 500;
const TIMEOUT_DURATION = 20000;

module.exports = { HANDSHAKE, DM };
const TIMEOUT_ERROR_MESSAGE = `Neighbor check timed out after ${TIMEOUT_DURATION / 1000} seconds`;

module.exports = {
HANDSHAKE,
DM,
CHECK_INTERVAL,
TIMEOUT_DURATION,
TIMEOUT_ERROR_MESSAGE,
};
23 changes: 21 additions & 2 deletions lib/messaging.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,13 @@
'use strict';
const { createData, uuid, createMessage } = require('./common');
const Connection = require('./connection');
const { HANDSHAKE, DM } = require('./constants');
const {
HANDSHAKE,
DM,
CHECK_INTERVAL,
TIMEOUT_DURATION,
TIMEOUT_ERROR_MESSAGE,
} = require('./constants');

class Messaging extends Connection {
NODE_ID = uuid();
Expand All @@ -27,7 +33,8 @@ class Messaging extends Connection {
if (nodeId) this.neighbors.delete(connectionId);
}

send(nodeId, message) {
async send(nodeId, message) {
await this.#neighborCheck();
const connectionId = this.neighbors.get(nodeId);
const targets = connectionId ? [connectionId] : this.neighbors;
targets.forEach(target =>
Expand All @@ -45,6 +52,18 @@ class Messaging extends Connection {
this.neighbors.set(neighbor, connectionId);
}

async #neighborCheck() {
const timeoutPromise = new Promise((_, reject) =>
setTimeout(() => reject(Error(TIMEOUT_ERROR_MESSAGE)), TIMEOUT_DURATION),
);
const checkNeighbors = async () => {
while (this.neighbors.size === 0) {
await new Promise(resolve => setTimeout(resolve, CHECK_INTERVAL));
}
};
await Promise.race([checkNeighbors(), timeoutPromise]);
}

[HANDSHAKE](connectionId, messageObject) {
const { data } = messageObject;
this.#addNeighbor(connectionId, data);
Expand Down

0 comments on commit 0374240

Please sign in to comment.