HTBox / allReady

This repo contains the code for allReady, an open-source solution focused on increasing awareness, efficiency and impact of preparedness campaigns as they are delivered by humanitarian and disaster response organizations in local communities.
http://www.htbox.org/projects/allready
MIT License
891 stars 624 forks source link

Idempotency Issue with SMS sending function: Add duplicate message detection #2386

Open NullPointer4096 opened 1 year ago

NullPointer4096 commented 1 year ago

Description: The current implementation of the ProcessSmsQueueMessage function sends SMS messages without checking for duplicate messages. This can lead to the same message being sent multiple times if the function is triggered more than once with the same message content. To avoid this issue, it's important to add a mechanism for detecting duplicate messages before sending them.

Proposed Solution: To address this issue, we can query the Twilio service for the messages sent to a specific number and then check if the new message is a duplicate of any of those messages. We can implement a IsDuplicateMessage function to perform this check and call it before sending the SMS message in ProcessSmsQueueMessage. This will prevent sending duplicate messages. An example implementation would be as follows:

public static bool IsDuplicateMessage(string body, string toPhoneNumber)
{
    var messages = MessageResource.Read(
        to: new Twilio.Types.PhoneNumber(toPhoneNumber),
        pageSize: 50
    );

    return messages.Any(message => message.Body == body);
}
public static void SendMessage(string toPhoneNumber, string fromPhoneNumber, string body)
{
    if (!IsDuplicateMessage(body, toPhoneNumber))
    {
        var message = MessageResource.Create(
            body: body,
            from: new Twilio.Types.PhoneNumber(fromPhoneNumber),
            to: new Twilio.Types.PhoneNumber(toPhoneNumber)
        );
        Console.WriteLine($"Sent message: {message.Sid}");
    }
    else
    {
        Console.WriteLine("Duplicate message not sent.");
    }
}