Skip to content

Commit

Permalink
perf: clean seens msgs
Browse files Browse the repository at this point in the history
  • Loading branch information
DIY0R committed Oct 23, 2024
1 parent f67a72e commit fc38af3
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 10 deletions.
1 change: 0 additions & 1 deletion lib/common/createData.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const createData = (type, data) => ({ type, data });

const createMessage = ({ type, to, message, messageId, ttl }) => ({
messageId,
...createData(type, message),
Expand Down
1 change: 0 additions & 1 deletion lib/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ class Connection extends EventEmitter {
socket.connect(targetNode, () => this.#handleConnection(socket));
}

/**@param {net.Socket} socket*/
#handleConnection(socket) {
const connectionId = uuid();
socket.setNoDelay(false);
Expand Down
10 changes: 6 additions & 4 deletions lib/constants.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
const HANDSHAKE = 'HANDSHAKE';
const DM = 'MESSAGE';
const CHECK_INTERVAL = 500;
const TIMEOUT_DURATION = 20000;
const TIMEOUT_DURATION = 2 * 60000;
const TIME_CLEAN_MSG = 30 * 60000;
const TTL = 300;
const HANDSHAKE = 'HANDSHAKE';
const DM = 'MESSAGE';
const TIMEOUT_ERROR_MESSAGE = `Neighbor check timed out after ${TIMEOUT_DURATION / 1000} seconds`;

module.exports = {
HANDSHAKE,
DM,
TIME_CLEAN_MSG,
CHECK_INTERVAL,
TIMEOUT_DURATION,
TIMEOUT_ERROR_MESSAGE,
TTL,
DM,
};
14 changes: 10 additions & 4 deletions lib/messaging.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,18 @@ const {
TIMEOUT_DURATION,
TIMEOUT_ERROR_MESSAGE,
TTL,
TIME_CLEAN_MSG,
} = require('./constants');

class Messaging extends Connection {
NODE_ID = uuid();
neighbors = new Map();
seenMessages = new Set();
seenMessages = new Set('sd', 'sd');

constructor(port, targetNode, nodeId) {
constructor(port, nodeId, targetNode) {
super(port, targetNode);
if (nodeId) this.NODE_ID = nodeId;
this.#cleanSeenMessages();
}

_newConnection(connectionId) {
Expand Down Expand Up @@ -83,10 +85,14 @@ class Messaging extends Connection {
[DM](_, messageObject) {
const { messageId, data, to, ttl } = messageObject;
if (to === this.NODE_ID) return void this.emit(DM, data);
const isProcessed = this.seenMessages.has(messageId);
if (ttl < 1 || isProcessed) return;
const isSeenMessage = this.seenMessages.has(messageId);
if (ttl < 1 || isSeenMessage) return;
this.#broadcast(to, data, { messageId, ttl: ttl - 1 });
}

#cleanSeenMessages() {
setTimeout(() => this.seenMessages.clear(), TIME_CLEAN_MSG);
}
}

module.exports = Messaging;

0 comments on commit fc38af3

Please sign in to comment.