|
| 1 | +# Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +# Licensed under the MIT License. |
| 3 | + |
| 4 | +from azure.core.exceptions import ResourceExistsError |
| 5 | +from azure.storage.queue.aio import QueueClient |
| 6 | +from jsonpickle import encode |
| 7 | + |
| 8 | +from botbuilder.core import QueueStorage |
| 9 | +from botbuilder.schema import Activity |
| 10 | + |
| 11 | + |
| 12 | +class AzureQueueStorage(QueueStorage): |
| 13 | + def __init__(self, queues_storage_connection_string: str, queue_name: str): |
| 14 | + if not queues_storage_connection_string: |
| 15 | + raise Exception("queues_storage_connection_string cannot be empty.") |
| 16 | + if not queue_name: |
| 17 | + raise Exception("queue_name cannot be empty.") |
| 18 | + |
| 19 | + self.__queue_client = QueueClient.from_connection_string( |
| 20 | + queues_storage_connection_string, queue_name |
| 21 | + ) |
| 22 | + |
| 23 | + self.__initialized = False |
| 24 | + |
| 25 | + async def _initialize(self): |
| 26 | + if self.__initialized is False: |
| 27 | + # This should only happen once - assuming this is a singleton. |
| 28 | + # There is no `create_queue_if_exists` or `exists` method, so we need to catch the ResourceExistsError. |
| 29 | + try: |
| 30 | + await self.__queue_client.create_queue() |
| 31 | + except ResourceExistsError: |
| 32 | + pass |
| 33 | + self.__initialized = True |
| 34 | + return self.__initialized |
| 35 | + |
| 36 | + async def queue_activity( |
| 37 | + self, |
| 38 | + activity: Activity, |
| 39 | + visibility_timeout: int = None, |
| 40 | + time_to_live: int = None, |
| 41 | + ) -> str: |
| 42 | + """ |
| 43 | + Enqueues an Activity for later processing. The visibility timeout specifies how long the message should be |
| 44 | + visible to Dequeue and Peek operations. |
| 45 | +
|
| 46 | + :param activity: The activity to be queued for later processing. |
| 47 | + :type activity: :class:`botbuilder.schema.Activity` |
| 48 | + :param visibility_timeout: Visibility timeout in seconds. Optional with a default value of 0. |
| 49 | + Cannot be larger than 7 days. |
| 50 | + :type visibility_timeout: int |
| 51 | + :param time_to_live: Specifies the time-to-live interval for the message in seconds. |
| 52 | + :type time_to_live: int |
| 53 | +
|
| 54 | + :returns: QueueMessage as a JSON string. |
| 55 | + :rtype: :class:`azure.storage.queue.QueueMessage` |
| 56 | + """ |
| 57 | + await self._initialize() |
| 58 | + |
| 59 | + # Encode the activity as a JSON string. |
| 60 | + message = encode(activity) |
| 61 | + |
| 62 | + receipt = await self.__queue_client.send_message( |
| 63 | + message, visibility_timeout=visibility_timeout, time_to_live=time_to_live |
| 64 | + ) |
| 65 | + |
| 66 | + # Encode the QueueMessage receipt as a JSON string. |
| 67 | + return encode(receipt) |
0 commit comments