Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement an exponential-backoff to find echo message #747

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 49 additions & 9 deletions api/src/chat/services/chat.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,22 +223,62 @@ export class ChatService {
throw new Error(`Subscriber with foreign ID ${foreignId} not found`);
}

const sentMessage: MessageCreateDto = {
mid: event.getId(),
recipient: recipient.id,
message: event.getMessage(),
delivery: true,
read: false,
};

this.eventEmitter.emit('hook:chatbot:sent', sentMessage);
const mid = event.getId();
const message = await this.findMessageWithRetries(mid);
debugger;

if (!message) {
const sentMessage: MessageCreateDto = {
mid,
recipient: recipient.id,
message: event.getMessage(),
delivery: true,
read: false,
};

this.eventEmitter.emit('hook:chatbot:sent', sentMessage);
}
this.eventEmitter.emit('hook:stats:entry', 'echo', 'Echo');
} catch (err) {
this.logger.error('Unable to log echo message', err, event);
}
}
}

/**
* Retries finding a message by mid with exponential backoff.
*
* @param mid - The message ID.
* @param maxRetries - Max number of retries (default: 5).
* @param initialDelay - Initial delay in ms (default: 100).
* @returns True if the message is found, false otherwise.
*/
async findMessageWithRetries(
mid: string,
maxRetries = 5,
initialDelay = 100,
) {
let attempt = 0;
let delay = initialDelay;

while (attempt < maxRetries) {
const exists = await this.messageService.count({ mid });

if (exists > 0) {
return true; // Message exists
}

attempt++;
await new Promise((resolve) => setTimeout(resolve, delay));
delay *= 2; // Exponential backoff
}

this.logger.debug(
'Echo message not found after multiple attempts. Treating as an external echo.',
);
return false;
}

/**
* Handle new incoming messages
*
Expand Down