Search code examples
azure-storage-queues

How to check if a storage queue contains a specific message


I'm writing an integration test for an azure function triggered by a storage queue, and I'd like to be able to check if the function has successfully processed the message or moved the message to the poison queue.

Is there any way to search a queue for a specific message, without dequeuing the message?

My approach was to retrieve the messageId and popReceipt of the sent message, and then try to update the message, throwing an exception if not found.

public async Task<bool> IsMessageInQueue(string messageId, string popReceipt, string queueName)
{
    try
    {
        var client = new QueueClient(_storageConnectionString, queueName);
        _ = client.UpdateMessageAsync(messageId, popReceipt);
        return true; //exists in queue
    }
    catch (Exception)
    {
        return false; //doesn't exist in queue
    }
}

And then

var sendMessageResponse = await client.SendMessageAsync(queueMessage);
var messageId = sendMessageResponse.Value.MessageId;
var popReceipt = sendMessageResponse.Value.PopReceipt;

var isProcessing = IsMessageInQueue(messageId, popReceipt, "processing");
var isPoisoned = IsMessageInQueue(messageId, popReceipt, "processing-poison");

isProcessing does return true if the message hasn't yet been picked up by the function and is still in "processing", but the problem is that the messageId changes when the message is moved to the poison queue, so isPoisoned will always return false

Update:

Thanks to @gaurav-mantri's suggestion, i updated my method to use PeekMessagesAsync and added my answer below:


Solution

  • Is there any way to search a queue for a specific message, without dequeuing the message?

    It is only possible if the number of messages in your queue is less than 32. 32 is the maximum number of messages you can peek (or dequeue) at a time.

    If the number of messages are less than 32, you can use QueueClient.PeekMessagesAsync and compare the message id of your messages with the messages returned. If you find a matching message id, that would mean the message exists in the queue.