1
votes

I have created a solution based on Azure Functions and Azure Service Bus, where clients can retrieve information from multiple back-end systems using a single API. The API is implemented in Azure Functions, and based on the payload of the request it is relayed to a Service Bus Queue, picked up by a client application running somewhere on-premise, and the answer sent back by the client to another Service Bus Queue, the "reply-" queue. Meanwhile, the Azure Function is waiting for a message in the reply-queue, and when it finds the message that belongs to it, it sends the payload back to the caller.

The Azure Function Activity Root Id is attached to the Service Bus Message as the CorrelationId. This way each running function knows which message contains the response to the callers request.

My question is about the way I am currently retrieving the messages from the reply queue. Since multiple instances can be running at the same time, each Azure Function instance needs to get it's response from the client without blocking other instances. Besides that, a time out needs to be observed. The client is expected to respond within 20 seconds. While waiting, the Azure Function should not be blocking other instances.

This is the code I have so far:

internal static async Task<(string, bool)> WaitForMessageAsync(string queueName, string operationId, TimeSpan timeout, ILogger log)
{
  log.LogInformation("Connecting to service bus queue {QueueName} to wait for reply...", queueName);
  var receiver = new MessageReceiver(_connectionString, queueName, ReceiveMode.PeekLock);

  try
  {
    var sw = Stopwatch.StartNew();
    while (sw.Elapsed < timeout)
    {
      var message = await receiver.ReceiveAsync(timeout.Subtract(sw.Elapsed));
      if (message != null)
      {
        if (message.CorrelationId == operationId)
        {
          log.LogInformation("Reply received for operation {OperationId}", message.CorrelationId);

          var reply = Encoding.UTF8.GetString(message.Body);
          var error = message.UserProperties.ContainsKey("ErrorCode");

          await receiver.CompleteAsync(message.SystemProperties.LockToken);

          return (reply, error);
        }
        else
        {
          log.LogInformation("Ignoring message for operation {OperationId}", message.CorrelationId);
        }
      }
    }

    return (null, false);
  }
  finally
  {
    await receiver.CloseAsync();
  }
}

The code is based on a few assumptions. I am having a hard time trying to find any documentation to verify my assumptions are correct:

  • I expect subsequent calls to ReceiveAsync not to fetch messages I have previously fetched and not explicitly abandoned.
  • I expect new messages that arrive on the queue to be received by ReceiveAsync, even though they may have arrived after my first call to ReceiveAsync and even though there might still be other messages in the queue that I haven't received yet either. E.g. there are 10 messages in the queue, I start receiving the first few message, meanwhile new messages arrive, and after I have read the 10 pre-existing messages, I get the new messages too.
  • I expect that when I call ReceiveAsync for a second time, that the lock is released from the message I received with the first call, although I did not explicitly Abandon that first message. Could anyone tell me if my assumptions are correct?

Note: please don't suggest that Durable Functions where designed specifically for this, because they simply do not fill the requirements. Most notably, Durable Functions are invoked by a process that polls a queue with a sliding interval, so after not having any requests for a few minutes, the first new request can take a minute to start, which is not acceptable for my use case.

2
Update: it seems this wont work. What I need to use is PeekAsync, but then there is no way to process the message I am interested in. I have raised an issue to restore the ReceiveAsync(Int64 sequenceNumber) method that was present in the old WindowsAzure.ServiceBus library: GitHub linkMartin Watts

2 Answers

0
votes

It seems that the feature can not be achieved now.

You can give your voice here where if others have same demand, they will vote up your idea.

0
votes

I would consider session enabled topics or queues for this.

The Message sessions documentation explains this in detail but the essential bit is that a session receiver is created by a client accepting a session. When the session is accepted and held by a client, the client holds an exclusive lock on all messages with that session's session ID in the queue or subscription. It will also hold exclusive locks on all messages with the session ID that will arrive later.

This makes it perfect for facilitating the request/reply pattern.

When sending the message to the queue that the on-premises handlers receive messages on, set the ReplyToSessionId property on the message to your operationId.

Then, the on-premises handlers need to set the SessionId property of the messages they send to the reply queue to the value of the ReplyToSessionId property of the message they processed.

Then finally you can update your code to use a SessionClient and then use the 'AcceptMessageSessionAsync()' method on that to start listening for messages on that session.

Something like the following should work:

internal static async Task<(string?, bool)> WaitForMessageAsync(string queueName, string operationId, TimeSpan timeout, ILogger log)
{
    log.LogInformation("Connecting to service bus queue {QueueName} to wait for reply...", queueName);

    var sessionClient = new SessionClient(_connectionString, queueName, ReceiveMode.PeekLock);

    try
    {
        var receiver = await sessionClient.AcceptMessageSessionAsync(operationId);

        // message will be null if the timeout is reached
        var message = await receiver.ReceiveAsync(timeout);

        if (message != null)
        {
            log.LogInformation("Reply received for operation {OperationId}", message.CorrelationId);

            var reply = Encoding.UTF8.GetString(message.Body);
            var error = message.UserProperties.ContainsKey("ErrorCode");

            await receiver.CompleteAsync(message.SystemProperties.LockToken);
            return (reply, error);
        }
        
        return (null, false);
    }
    finally
    {
        await sessionClient.CloseAsync();
    }
}

Note: For all this to work, the reply queue will need Sessions enabled. This will require the Standard or Premium tier of Azure Service Bus.

Both queues and topic subscriptions support enabling sessions. The topic subscriptions allow you to mix and match session enabled scenarios as your needs arise. You could have some subscriptions with it enabled, and some without.

The queue used to send the message to the on-premises handlers does not need Sessions enabled.

Finally, when Sessions are enabled on a queue or a topic subscription, the client applications can no longer send or receive regular messages. All messages must be sent as part of a session (by setting the SessionId) and received by accepting the session.