diff --git a/sdk/communication/azure-communication-jobrouter/MANIFEST.in b/sdk/communication/azure-communication-jobrouter/MANIFEST.in index e7217bacd37a..5db9d92bca6b 100644 --- a/sdk/communication/azure-communication-jobrouter/MANIFEST.in +++ b/sdk/communication/azure-communication-jobrouter/MANIFEST.in @@ -4,4 +4,4 @@ include azure/communication/jobrouter/py.typed recursive-include tests *.py recursive-include samples *.py *.md include azure/__init__.py -include azure/communication/__init__.py \ No newline at end of file +include azure/communication/__init__.py diff --git a/sdk/communication/azure-communication-jobrouter/_meta.json b/sdk/communication/azure-communication-jobrouter/_meta.json new file mode 100644 index 000000000000..31bfdf9a978e --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "726419b7eba57b9b5888ca11e055c8f82dcaae58", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/communication/Communication.JobRouter", + "@azure-tools/typespec-python": "0.44.2" +} \ No newline at end of file diff --git a/sdk/communication/azure-communication-jobrouter/apiview-properties.json b/sdk/communication/azure-communication-jobrouter/apiview-properties.json new file mode 100644 index 000000000000..8ad213b23ebf --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/apiview-properties.json @@ -0,0 +1,142 @@ +{ + "CrossLanguagePackageId": "AzureCommunicationRoutingService", + "CrossLanguageDefinitionId": { + "azure.communication.jobrouter.models.AcceptJobOfferResult": "AzureCommunicationRoutingService.AcceptJobOfferResult", + "azure.communication.jobrouter.models.DistributionMode": "AzureCommunicationRoutingService.DistributionMode", + "azure.communication.jobrouter.models.BestWorkerMode": "AzureCommunicationRoutingService.BestWorkerMode", + "azure.communication.jobrouter.models.ExceptionAction": "AzureCommunicationRoutingService.ExceptionAction", + "azure.communication.jobrouter.models.CancelExceptionAction": "AzureCommunicationRoutingService.CancelExceptionAction", + "azure.communication.jobrouter.models.CancelJobOptions": "AzureCommunicationRoutingService.CancelJobOptions", + "azure.communication.jobrouter.models.CancelJobResult": "AzureCommunicationRoutingService.CancelJobResult", + "azure.communication.jobrouter.models.ClassificationPolicy": "AzureCommunicationRoutingService.ClassificationPolicy", + "azure.communication.jobrouter.models.CloseJobOptions": "AzureCommunicationRoutingService.CloseJobOptions", + "azure.communication.jobrouter.models.CloseJobResult": "AzureCommunicationRoutingService.CloseJobResult", + "azure.communication.jobrouter.models.CompleteJobOptions": "AzureCommunicationRoutingService.CompleteJobOptions", + "azure.communication.jobrouter.models.CompleteJobResult": "AzureCommunicationRoutingService.CompleteJobResult", + "azure.communication.jobrouter.models.QueueSelectorAttachment": "AzureCommunicationRoutingService.QueueSelectorAttachment", + "azure.communication.jobrouter.models.ConditionalQueueSelectorAttachment": "AzureCommunicationRoutingService.ConditionalQueueSelectorAttachment", + "azure.communication.jobrouter.models.WorkerSelectorAttachment": "AzureCommunicationRoutingService.WorkerSelectorAttachment", + "azure.communication.jobrouter.models.ConditionalWorkerSelectorAttachment": "AzureCommunicationRoutingService.ConditionalWorkerSelectorAttachment", + "azure.communication.jobrouter.models.DeclineJobOfferOptions": "AzureCommunicationRoutingService.DeclineJobOfferOptions", + "azure.communication.jobrouter.models.DeclineJobOfferResult": "AzureCommunicationRoutingService.DeclineJobOfferResult", + "azure.communication.jobrouter.models.RouterRule": "AzureCommunicationRoutingService.RouterRule", + "azure.communication.jobrouter.models.DirectMapRouterRule": "AzureCommunicationRoutingService.DirectMapRouterRule", + "azure.communication.jobrouter.models.DistributionPolicy": "AzureCommunicationRoutingService.DistributionPolicy", + "azure.communication.jobrouter.models.ExceptionPolicy": "AzureCommunicationRoutingService.ExceptionPolicy", + "azure.communication.jobrouter.models.ExceptionRule": "AzureCommunicationRoutingService.ExceptionRule", + "azure.communication.jobrouter.models.ExceptionTrigger": "AzureCommunicationRoutingService.ExceptionTrigger", + "azure.communication.jobrouter.models.ExpressionRouterRule": "AzureCommunicationRoutingService.ExpressionRouterRule", + "azure.communication.jobrouter.models.FunctionRouterRule": "AzureCommunicationRoutingService.FunctionRouterRule", + "azure.communication.jobrouter.models.FunctionRouterRuleCredential": "AzureCommunicationRoutingService.FunctionRouterRuleCredential", + "azure.communication.jobrouter.models.JobMatchingMode": "AzureCommunicationRoutingService.JobMatchingMode", + "azure.communication.jobrouter.models.LongestIdleMode": "AzureCommunicationRoutingService.LongestIdleMode", + "azure.communication.jobrouter.models.ManualReclassifyExceptionAction": "AzureCommunicationRoutingService.ManualReclassifyExceptionAction", + "azure.communication.jobrouter.models.OAuth2WebhookClientCredential": "AzureCommunicationRoutingService.OAuth2WebhookClientCredential", + "azure.communication.jobrouter.models.PassThroughQueueSelectorAttachment": "AzureCommunicationRoutingService.PassThroughQueueSelectorAttachment", + "azure.communication.jobrouter.models.PassThroughWorkerSelectorAttachment": "AzureCommunicationRoutingService.PassThroughWorkerSelectorAttachment", + "azure.communication.jobrouter.models.QueueAndMatchMode": "AzureCommunicationRoutingService.QueueAndMatchMode", + "azure.communication.jobrouter.models.QueueLengthExceptionTrigger": "AzureCommunicationRoutingService.QueueLengthExceptionTrigger", + "azure.communication.jobrouter.models.QueueWeightedAllocation": "AzureCommunicationRoutingService.QueueWeightedAllocation", + "azure.communication.jobrouter.models.ReclassifyExceptionAction": "AzureCommunicationRoutingService.ReclassifyExceptionAction", + "azure.communication.jobrouter.models.ReclassifyJobResult": "AzureCommunicationRoutingService.ReclassifyJobResult", + "azure.communication.jobrouter.models.RoundRobinMode": "AzureCommunicationRoutingService.RoundRobinMode", + "azure.communication.jobrouter.models.RouterChannel": "AzureCommunicationRoutingService.RouterChannel", + "azure.communication.jobrouter.models.RouterJob": "AzureCommunicationRoutingService.RouterJob", + "azure.communication.jobrouter.models.RouterJobAssignment": "AzureCommunicationRoutingService.RouterJobAssignment", + "azure.communication.jobrouter.models.RouterJobNote": "AzureCommunicationRoutingService.RouterJobNote", + "azure.communication.jobrouter.models.RouterJobOffer": "AzureCommunicationRoutingService.RouterJobOffer", + "azure.communication.jobrouter.models.RouterJobPositionDetails": "AzureCommunicationRoutingService.RouterJobPositionDetails", + "azure.communication.jobrouter.models.RouterQueue": "AzureCommunicationRoutingService.RouterQueue", + "azure.communication.jobrouter.models.RouterQueueSelector": "AzureCommunicationRoutingService.RouterQueueSelector", + "azure.communication.jobrouter.models.RouterQueueStatistics": "AzureCommunicationRoutingService.RouterQueueStatistics", + "azure.communication.jobrouter.models.RouterWorker": "AzureCommunicationRoutingService.RouterWorker", + "azure.communication.jobrouter.models.RouterWorkerAssignment": "AzureCommunicationRoutingService.RouterWorkerAssignment", + "azure.communication.jobrouter.models.RouterWorkerSelector": "AzureCommunicationRoutingService.RouterWorkerSelector", + "azure.communication.jobrouter.models.RuleEngineQueueSelectorAttachment": "AzureCommunicationRoutingService.RuleEngineQueueSelectorAttachment", + "azure.communication.jobrouter.models.RuleEngineWorkerSelectorAttachment": "AzureCommunicationRoutingService.RuleEngineWorkerSelectorAttachment", + "azure.communication.jobrouter.models.ScheduleAndSuspendMode": "AzureCommunicationRoutingService.ScheduleAndSuspendMode", + "azure.communication.jobrouter.models.ScoringRuleOptions": "AzureCommunicationRoutingService.ScoringRuleOptions", + "azure.communication.jobrouter.models.StaticQueueSelectorAttachment": "AzureCommunicationRoutingService.StaticQueueSelectorAttachment", + "azure.communication.jobrouter.models.StaticRouterRule": "AzureCommunicationRoutingService.StaticRouterRule", + "azure.communication.jobrouter.models.StaticWorkerSelectorAttachment": "AzureCommunicationRoutingService.StaticWorkerSelectorAttachment", + "azure.communication.jobrouter.models.SuspendMode": "AzureCommunicationRoutingService.SuspendMode", + "azure.communication.jobrouter.models.UnassignJobOptions": "AzureCommunicationRoutingService.UnassignJobOptions", + "azure.communication.jobrouter.models.UnassignJobResult": "AzureCommunicationRoutingService.UnassignJobResult", + "azure.communication.jobrouter.models.WaitTimeExceptionTrigger": "AzureCommunicationRoutingService.WaitTimeExceptionTrigger", + "azure.communication.jobrouter.models.WebhookRouterRule": "AzureCommunicationRoutingService.WebhookRouterRule", + "azure.communication.jobrouter.models.WeightedAllocationQueueSelectorAttachment": "AzureCommunicationRoutingService.WeightedAllocationQueueSelectorAttachment", + "azure.communication.jobrouter.models.WeightedAllocationWorkerSelectorAttachment": "AzureCommunicationRoutingService.WeightedAllocationWorkerSelectorAttachment", + "azure.communication.jobrouter.models.WorkerWeightedAllocation": "AzureCommunicationRoutingService.WorkerWeightedAllocation", + "azure.communication.jobrouter.models.DistributionModeKind": "AzureCommunicationRoutingService.DistributionModeKind", + "azure.communication.jobrouter.models.RouterRuleKind": "AzureCommunicationRoutingService.RouterRuleKind", + "azure.communication.jobrouter.models.ExpressionRouterRuleLanguage": "AzureCommunicationRoutingService.ExpressionRouterRuleLanguage", + "azure.communication.jobrouter.models.ScoringRuleParameterSelector": "AzureCommunicationRoutingService.ScoringRuleParameterSelector", + "azure.communication.jobrouter.models.QueueSelectorAttachmentKind": "AzureCommunicationRoutingService.QueueSelectorAttachmentKind", + "azure.communication.jobrouter.models.LabelOperator": "AzureCommunicationRoutingService.LabelOperator", + "azure.communication.jobrouter.models.WorkerSelectorAttachmentKind": "AzureCommunicationRoutingService.WorkerSelectorAttachmentKind", + "azure.communication.jobrouter.models.RouterWorkerSelectorStatus": "AzureCommunicationRoutingService.RouterWorkerSelectorStatus", + "azure.communication.jobrouter.models.ExceptionTriggerKind": "AzureCommunicationRoutingService.ExceptionTriggerKind", + "azure.communication.jobrouter.models.ExceptionActionKind": "AzureCommunicationRoutingService.ExceptionActionKind", + "azure.communication.jobrouter.models.RouterJobStatus": "AzureCommunicationRoutingService.RouterJobStatus", + "azure.communication.jobrouter.models.JobMatchingModeKind": "AzureCommunicationRoutingService.JobMatchingModeKind", + "azure.communication.jobrouter.models.RouterJobStatusSelector": "AzureCommunicationRoutingService.RouterJobStatusSelector", + "azure.communication.jobrouter.models.RouterWorkerState": "AzureCommunicationRoutingService.RouterWorkerState", + "azure.communication.jobrouter.models.RouterWorkerStateSelector": "AzureCommunicationRoutingService.RouterWorkerStateSelector", + "azure.communication.jobrouter.JobRouterAdministrationClient.upsert_distribution_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.upsertDistributionPolicy", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.upsert_distribution_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.upsertDistributionPolicy", + "azure.communication.jobrouter.JobRouterAdministrationClient.get_distribution_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.getDistributionPolicy", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.get_distribution_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.getDistributionPolicy", + "azure.communication.jobrouter.JobRouterAdministrationClient.list_distribution_policies": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.listDistributionPolicies", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.list_distribution_policies": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.listDistributionPolicies", + "azure.communication.jobrouter.JobRouterAdministrationClient.delete_distribution_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.deleteDistributionPolicy", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.delete_distribution_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.deleteDistributionPolicy", + "azure.communication.jobrouter.JobRouterAdministrationClient.upsert_classification_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.upsertClassificationPolicy", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.upsert_classification_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.upsertClassificationPolicy", + "azure.communication.jobrouter.JobRouterAdministrationClient.get_classification_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.getClassificationPolicy", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.get_classification_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.getClassificationPolicy", + "azure.communication.jobrouter.JobRouterAdministrationClient.list_classification_policies": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.listClassificationPolicies", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.list_classification_policies": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.listClassificationPolicies", + "azure.communication.jobrouter.JobRouterAdministrationClient.delete_classification_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.deleteClassificationPolicy", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.delete_classification_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.deleteClassificationPolicy", + "azure.communication.jobrouter.JobRouterAdministrationClient.upsert_exception_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.upsertExceptionPolicy", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.upsert_exception_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.upsertExceptionPolicy", + "azure.communication.jobrouter.JobRouterAdministrationClient.get_exception_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.getExceptionPolicy", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.get_exception_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.getExceptionPolicy", + "azure.communication.jobrouter.JobRouterAdministrationClient.list_exception_policies": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.listExceptionPolicies", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.list_exception_policies": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.listExceptionPolicies", + "azure.communication.jobrouter.JobRouterAdministrationClient.delete_exception_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.deleteExceptionPolicy", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.delete_exception_policy": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.deleteExceptionPolicy", + "azure.communication.jobrouter.JobRouterAdministrationClient.upsert_queue": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.upsertQueue", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.upsert_queue": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.upsertQueue", + "azure.communication.jobrouter.JobRouterAdministrationClient.get_queue": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.getQueue", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.get_queue": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.getQueue", + "azure.communication.jobrouter.JobRouterAdministrationClient.list_queues": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.listQueues", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.list_queues": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.listQueues", + "azure.communication.jobrouter.JobRouterAdministrationClient.delete_queue": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.deleteQueue", + "azure.communication.jobrouter.aio.JobRouterAdministrationClient.delete_queue": "ClientForAcsJobRouter.JobRouterAdministrationRestClient.deleteQueue", + "azure.communication.jobrouter.JobRouterClient.upsert_job": "ClientForAcsJobRouter.JobRouterRestClient.upsertJob", + "azure.communication.jobrouter.aio.JobRouterClient.upsert_job": "ClientForAcsJobRouter.JobRouterRestClient.upsertJob", + "azure.communication.jobrouter.JobRouterClient.get_job": "ClientForAcsJobRouter.JobRouterRestClient.getJob", + "azure.communication.jobrouter.aio.JobRouterClient.get_job": "ClientForAcsJobRouter.JobRouterRestClient.getJob", + "azure.communication.jobrouter.JobRouterClient.delete_job": "ClientForAcsJobRouter.JobRouterRestClient.deleteJob", + "azure.communication.jobrouter.aio.JobRouterClient.delete_job": "ClientForAcsJobRouter.JobRouterRestClient.deleteJob", + "azure.communication.jobrouter.JobRouterClient.list_jobs": "ClientForAcsJobRouter.JobRouterRestClient.listJobs", + "azure.communication.jobrouter.aio.JobRouterClient.list_jobs": "ClientForAcsJobRouter.JobRouterRestClient.listJobs", + "azure.communication.jobrouter.JobRouterClient.get_queue_position": "ClientForAcsJobRouter.JobRouterRestClient.getQueuePosition", + "azure.communication.jobrouter.aio.JobRouterClient.get_queue_position": "ClientForAcsJobRouter.JobRouterRestClient.getQueuePosition", + "azure.communication.jobrouter.JobRouterClient.unassign_job": "ClientForAcsJobRouter.JobRouterRestClient.unassign", + "azure.communication.jobrouter.aio.JobRouterClient.unassign_job": "ClientForAcsJobRouter.JobRouterRestClient.unassign", + "azure.communication.jobrouter.JobRouterClient.accept_job_offer": "ClientForAcsJobRouter.JobRouterRestClient.accept", + "azure.communication.jobrouter.aio.JobRouterClient.accept_job_offer": "ClientForAcsJobRouter.JobRouterRestClient.accept", + "azure.communication.jobrouter.JobRouterClient.get_queue_statistics": "ClientForAcsJobRouter.JobRouterRestClient.getQueueStatistics", + "azure.communication.jobrouter.aio.JobRouterClient.get_queue_statistics": "ClientForAcsJobRouter.JobRouterRestClient.getQueueStatistics", + "azure.communication.jobrouter.JobRouterClient.upsert_worker": "ClientForAcsJobRouter.JobRouterRestClient.upsertWorker", + "azure.communication.jobrouter.aio.JobRouterClient.upsert_worker": "ClientForAcsJobRouter.JobRouterRestClient.upsertWorker", + "azure.communication.jobrouter.JobRouterClient.get_worker": "ClientForAcsJobRouter.JobRouterRestClient.getWorker", + "azure.communication.jobrouter.aio.JobRouterClient.get_worker": "ClientForAcsJobRouter.JobRouterRestClient.getWorker", + "azure.communication.jobrouter.JobRouterClient.delete_worker": "ClientForAcsJobRouter.JobRouterRestClient.deleteWorker", + "azure.communication.jobrouter.aio.JobRouterClient.delete_worker": "ClientForAcsJobRouter.JobRouterRestClient.deleteWorker", + "azure.communication.jobrouter.JobRouterClient.list_workers": "ClientForAcsJobRouter.JobRouterRestClient.listWorkers", + "azure.communication.jobrouter.aio.JobRouterClient.list_workers": "ClientForAcsJobRouter.JobRouterRestClient.listWorkers" + } +} \ No newline at end of file diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/__init__.py index ba2b07fc1b38..b25a83281bd8 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/__init__.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/__init__.py @@ -5,16 +5,22 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._patch import JobRouterAdministrationClient -from ._patch import JobRouterClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import JobRouterAdministrationClient # type: ignore +from ._client import JobRouterClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -23,6 +29,6 @@ "JobRouterAdministrationClient", "JobRouterClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_api_versions.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_api_versions.py deleted file mode 100644 index 8f826623df34..000000000000 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_api_versions.py +++ /dev/null @@ -1,16 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ - -from enum import Enum -from azure.core import CaseInsensitiveEnumMeta - - -class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - V2022_07_18_PREVIEW = "2022-07-18-preview" - V2023_11_01 = "2023-11-01" - V2024_01_18_PREVIEW = "2024-01-18-preview" - - -DEFAULT_VERSION = ApiVersion.V2024_01_18_PREVIEW.value diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_client.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_client.py index 24fcd9ae2500..9f2f2023a508 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_client.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_client.py @@ -7,7 +7,8 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any +from typing import Any, TYPE_CHECKING +from typing_extensions import Self from azure.core import PipelineClient from azure.core.pipeline import policies @@ -15,27 +16,29 @@ from ._configuration import JobRouterAdministrationClientConfiguration, JobRouterClientConfiguration from ._operations import JobRouterAdministrationClientOperationsMixin, JobRouterClientOperationsMixin -from ._serialization import Deserializer, Serializer +from ._utils.serialization import Deserializer, Serializer +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential -class JobRouterAdministrationClient( - JobRouterAdministrationClientOperationsMixin -): # pylint: disable=client-accepts-api-version-keyword + +class JobRouterAdministrationClient(JobRouterAdministrationClientOperationsMixin): """JobRouterAdministrationClient. :param endpoint: Uri of your Communication resource. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential :keyword api_version: The API version to use for this operation. Default value is "2024-01-18-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, **kwargs: Any - ) -> None: + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: _endpoint = "{endpoint}" - self._config = JobRouterAdministrationClientConfiguration(endpoint=endpoint, **kwargs) + self._config = JobRouterAdministrationClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -79,7 +82,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: request_copy = deepcopy(request) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) @@ -88,7 +91,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: def close(self) -> None: self._client.close() - def __enter__(self) -> "JobRouterAdministrationClient": + def __enter__(self) -> Self: self._client.__enter__() return self @@ -96,22 +99,23 @@ def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) -class JobRouterClient(JobRouterClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword +class JobRouterClient(JobRouterClientOperationsMixin): """JobRouterClient. :param endpoint: Uri of your Communication resource. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential :keyword api_version: The API version to use for this operation. Default value is "2024-01-18-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, **kwargs: Any - ) -> None: + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: _endpoint = "{endpoint}" - self._config = JobRouterClientConfiguration(endpoint=endpoint, **kwargs) + self._config = JobRouterClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -155,7 +159,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: request_copy = deepcopy(request) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) @@ -164,7 +168,7 @@ def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: def close(self) -> None: self._client.close() - def __enter__(self) -> "JobRouterClient": + def __enter__(self) -> Self: self._client.__enter__() return self diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_configuration.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_configuration.py index 1e52a5a93939..0a94d7e1cf78 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_configuration.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_configuration.py @@ -6,12 +6,15 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any +from typing import Any, TYPE_CHECKING from azure.core.pipeline import policies from ._version import VERSION +if TYPE_CHECKING: + from azure.core.credentials import TokenCredential + class JobRouterAdministrationClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for JobRouterAdministrationClient. @@ -21,20 +24,26 @@ class JobRouterAdministrationClientConfiguration: # pylint: disable=too-many-in :param endpoint: Uri of your Communication resource. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential :keyword api_version: The API version to use for this operation. Default value is "2024-01-18-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, endpoint: str, **kwargs: Any) -> None: + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: api_version: str = kwargs.pop("api_version", "2024-01-18-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") self.endpoint = endpoint + self.credential = credential self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://communication.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "communication-jobrouter/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) @@ -49,9 +58,13 @@ def _configure(self, **kwargs: Any) -> None: self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) -class JobRouterClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class JobRouterClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for JobRouterClient. Note that all parameters used to create this instance are saved as instance @@ -59,20 +72,26 @@ class JobRouterClientConfiguration: # pylint: disable=too-many-instance-attribu :param endpoint: Uri of your Communication resource. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials.TokenCredential :keyword api_version: The API version to use for this operation. Default value is "2024-01-18-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, endpoint: str, **kwargs: Any) -> None: + def __init__(self, endpoint: str, credential: "TokenCredential", **kwargs: Any) -> None: api_version: str = kwargs.pop("api_version", "2024-01-18-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") self.endpoint = endpoint + self.credential = credential self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://communication.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "communication-jobrouter/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) @@ -87,3 +106,7 @@ def _configure(self, **kwargs: Any) -> None: self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/__init__.py index 06eb1614ceb7..462bfe7de7f9 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/__init__.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/__init__.py @@ -5,17 +5,23 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._patch import JobRouterAdministrationClientOperationsMixin -from ._patch import JobRouterClientOperationsMixin +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import JobRouterAdministrationClientOperationsMixin # type: ignore +from ._operations import JobRouterClientOperationsMixin # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "JobRouterAdministrationClientOperationsMixin", "JobRouterClientOperationsMixin", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py index cebc890fbfda..b18b399af965 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines,too-many-statements +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,14 +6,14 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping import datetime from io import IOBase import json -import sys -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload +from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, overload import urllib.parse -from azure.core import MatchConditions +from azure.core import MatchConditions, PipelineClient from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, @@ -21,6 +21,8 @@ ResourceModifiedError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.paging import ItemPaged @@ -30,15 +32,12 @@ from azure.core.utils import case_insensitive_dict from .. import models as _models -from .._model_base import SdkJSONEncoder, _deserialize -from .._serialization import Serializer -from .._vendor import JobRouterAdministrationClientMixinABC, JobRouterClientMixinABC, prep_if_match, prep_if_none_match - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object +from .._configuration import JobRouterAdministrationClientConfiguration, JobRouterClientConfiguration +from .._utils.model_base import SdkJSONEncoder, _deserialize +from .._utils.serialization import Serializer +from .._utils.utils import ClientMixinABC, prep_if_match, prep_if_none_match + +JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -140,9 +139,12 @@ def build_job_router_administration_list_distribution_policies_request( # pylin def build_job_router_administration_delete_distribution_policy_request( # pylint: disable=name-too-long distribution_policy_id: str, **kwargs: Any ) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview")) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = "/routing/distributionPolicies/{distributionPolicyId}" path_format_arguments = { @@ -154,7 +156,10 @@ def build_job_router_administration_delete_distribution_policy_request( # pylin # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_job_router_administration_upsert_classification_policy_request( # pylint: disable=name-too-long @@ -251,9 +256,12 @@ def build_job_router_administration_list_classification_policies_request( # pyl def build_job_router_administration_delete_classification_policy_request( # pylint: disable=name-too-long classification_policy_id: str, **kwargs: Any ) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview")) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = "/routing/classificationPolicies/{classificationPolicyId}" path_format_arguments = { @@ -265,7 +273,10 @@ def build_job_router_administration_delete_classification_policy_request( # pyl # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_job_router_administration_upsert_exception_policy_request( # pylint: disable=name-too-long @@ -362,9 +373,12 @@ def build_job_router_administration_list_exception_policies_request( # pylint: def build_job_router_administration_delete_exception_policy_request( # pylint: disable=name-too-long exception_policy_id: str, **kwargs: Any ) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview")) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = "/routing/exceptionPolicies/{exceptionPolicyId}" path_format_arguments = { @@ -376,7 +390,10 @@ def build_job_router_administration_delete_exception_policy_request( # pylint: # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_job_router_administration_upsert_queue_request( # pylint: disable=name-too-long @@ -473,9 +490,12 @@ def build_job_router_administration_list_queues_request( # pylint: disable=name def build_job_router_administration_delete_queue_request( # pylint: disable=name-too-long queue_id: str, **kwargs: Any ) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview")) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = "/routing/queues/{queueId}" path_format_arguments = { @@ -487,7 +507,10 @@ def build_job_router_administration_delete_queue_request( # pylint: disable=nam # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_job_router_upsert_job_request( @@ -557,9 +580,12 @@ def build_job_router_get_job_request(job_id: str, **kwargs: Any) -> HttpRequest: def build_job_router_delete_job_request(job_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview")) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = "/routing/jobs/{jobId}" path_format_arguments = { @@ -571,7 +597,10 @@ def build_job_router_delete_job_request(job_id: str, **kwargs: Any) -> HttpReque # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_job_router_reclassify_job_request(job_id: str, **kwargs: Any) -> HttpRequest: @@ -594,9 +623,9 @@ def build_job_router_reclassify_job_request(job_id: str, **kwargs: Any) -> HttpR _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -621,9 +650,9 @@ def build_job_router_cancel_job_request(job_id: str, **kwargs: Any) -> HttpReque _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -649,9 +678,9 @@ def build_job_router_complete_job_request(job_id: str, assignment_id: str, **kwa _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -677,9 +706,9 @@ def build_job_router_close_job_request(job_id: str, assignment_id: str, **kwargs _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -776,9 +805,9 @@ def build_job_router_unassign_job_request(job_id: str, assignment_id: str, **kwa _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -833,9 +862,9 @@ def build_job_router_decline_job_offer_request( # pylint: disable=name-too-long _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") if content_type is not None: _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) @@ -933,9 +962,12 @@ def build_job_router_get_worker_request(worker_id: str, **kwargs: Any) -> HttpRe def build_job_router_delete_worker_request(worker_id: str, **kwargs: Any) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-01-18-preview")) + accept = _headers.pop("Accept", "application/json") + # Construct URL _url = "/routing/workers/{workerId}" path_format_arguments = { @@ -947,7 +979,10 @@ def build_job_router_delete_worker_request(worker_id: str, **kwargs: Any) -> Htt # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) def build_job_router_list_workers_request( @@ -988,8 +1023,9 @@ def build_job_router_list_workers_request( class JobRouterAdministrationClientOperationsMixin( # pylint: disable=name-too-long - JobRouterAdministrationClientMixinABC + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], JobRouterAdministrationClientConfiguration] ): + @overload def upsert_distribution_policy( self, @@ -1002,7 +1038,6 @@ def upsert_distribution_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.DistributionPolicy: - # pylint: disable=line-too-long """Creates or updates a distribution policy. Creates or updates a distribution policy. @@ -1025,243 +1060,6 @@ def upsert_distribution_policy( :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DistributionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ @overload @@ -1276,7 +1074,6 @@ def upsert_distribution_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.DistributionPolicy: - # pylint: disable=line-too-long """Creates or updates a distribution policy. Creates or updates a distribution policy. @@ -1299,162 +1096,6 @@ def upsert_distribution_policy( :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DistributionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ @overload @@ -1469,7 +1110,6 @@ def upsert_distribution_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.DistributionPolicy: - # pylint: disable=line-too-long """Creates or updates a distribution policy. Creates or updates a distribution policy. @@ -1492,162 +1132,6 @@ def upsert_distribution_policy( :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DistributionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ @distributed_trace @@ -1661,7 +1145,6 @@ def upsert_distribution_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.DistributionPolicy: - # pylint: disable=line-too-long """Creates or updates a distribution policy. Creates or updates a distribution policy. @@ -1682,245 +1165,8 @@ def upsert_distribution_policy( :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DistributionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1959,7 +1205,7 @@ def upsert_distribution_policy( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -1972,28 +1218,21 @@ def upsert_distribution_policy( if response.status_code not in [200, 201]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.DistributionPolicy, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.DistributionPolicy, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.DistributionPolicy, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2002,7 +1241,6 @@ def upsert_distribution_policy( @distributed_trace def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) -> _models.DistributionPolicy: - # pylint: disable=line-too-long """Retrieves an existing distribution policy by Id. Retrieves an existing distribution policy by Id. @@ -2012,93 +1250,8 @@ def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) -> :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DistributionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2118,7 +1271,7 @@ def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) -> params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -2131,7 +1284,10 @@ def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) -> if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -2149,10 +1305,8 @@ def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) -> return deserialized # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace - def list_distribution_policies(self, **kwargs: Any) -> ItemPaged["_models.DistributionPolicy"]: - # pylint: disable=line-too-long + def list_distribution_policies(self, **kwargs: Any) -> Iterable["_models.DistributionPolicy"]: """Retrieves existing distribution policies. Retrieves existing distribution policies. @@ -2160,91 +1314,6 @@ def list_distribution_policies(self, **kwargs: Any) -> ItemPaged["_models.Distri :return: An iterator like instance of DistributionPolicy :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.DistributionPolicy] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -2252,7 +1321,7 @@ def list_distribution_policies(self, **kwargs: Any) -> ItemPaged["_models.Distri maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.DistributionPolicy]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2270,9 +1339,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -2290,9 +1357,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -2300,7 +1365,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DistributionPolicy], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DistributionPolicy], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -2315,8 +1380,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -2338,7 +1401,7 @@ def delete_distribution_policy( # pylint: disable=inconsistent-return-statement :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2358,7 +1421,7 @@ def delete_distribution_policy( # pylint: disable=inconsistent-return-statement params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -2370,8 +1433,6 @@ def delete_distribution_policy( # pylint: disable=inconsistent-return-statement response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -2390,7 +1451,6 @@ def upsert_classification_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.ClassificationPolicy: - # pylint: disable=line-too-long """Creates or updates a classification policy. Creates or updates a classification policy. @@ -2413,192 +1473,6 @@ def upsert_classification_policy( :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ @overload @@ -2613,7 +1487,6 @@ def upsert_classification_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.ClassificationPolicy: - # pylint: disable=line-too-long """Creates or updates a classification policy. Creates or updates a classification policy. @@ -2636,126 +1509,6 @@ def upsert_classification_policy( :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ @overload @@ -2770,7 +1523,6 @@ def upsert_classification_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.ClassificationPolicy: - # pylint: disable=line-too-long """Creates or updates a classification policy. Creates or updates a classification policy. @@ -2793,126 +1545,6 @@ def upsert_classification_policy( :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ @distributed_trace @@ -2926,7 +1558,6 @@ def upsert_classification_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.ClassificationPolicy: - # pylint: disable=line-too-long """Creates or updates a classification policy. Creates or updates a classification policy. @@ -2947,194 +1578,8 @@ def upsert_classification_policy( :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3173,7 +1618,7 @@ def upsert_classification_policy( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3186,28 +1631,21 @@ def upsert_classification_policy( if response.status_code not in [200, 201]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.ClassificationPolicy, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.ClassificationPolicy, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ClassificationPolicy, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -3216,7 +1654,6 @@ def upsert_classification_policy( @distributed_trace def get_classification_policy(self, classification_policy_id: str, **kwargs: Any) -> _models.ClassificationPolicy: - # pylint: disable=line-too-long """Retrieves an existing classification policy by Id. Retrieves an existing classification policy by Id. @@ -3226,78 +1663,8 @@ def get_classification_policy(self, classification_policy_id: str, **kwargs: Any :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3317,7 +1684,7 @@ def get_classification_policy(self, classification_policy_id: str, **kwargs: Any params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3330,7 +1697,10 @@ def get_classification_policy(self, classification_policy_id: str, **kwargs: Any if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3348,10 +1718,8 @@ def get_classification_policy(self, classification_policy_id: str, **kwargs: Any return deserialized # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace - def list_classification_policies(self, **kwargs: Any) -> ItemPaged["_models.ClassificationPolicy"]: - # pylint: disable=line-too-long + def list_classification_policies(self, **kwargs: Any) -> Iterable["_models.ClassificationPolicy"]: """Retrieves existing classification policies. Retrieves existing classification policies. @@ -3360,76 +1728,6 @@ def list_classification_policies(self, **kwargs: Any) -> ItemPaged["_models.Clas :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.ClassificationPolicy] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -3437,7 +1735,7 @@ def list_classification_policies(self, **kwargs: Any) -> ItemPaged["_models.Clas maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.ClassificationPolicy]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3455,9 +1753,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3475,9 +1771,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3485,7 +1779,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.ClassificationPolicy], deserialized["value"]) + list_of_elem = _deserialize(List[_models.ClassificationPolicy], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -3500,8 +1794,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3523,7 +1815,7 @@ def delete_classification_policy( # pylint: disable=inconsistent-return-stateme :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3543,7 +1835,7 @@ def delete_classification_policy( # pylint: disable=inconsistent-return-stateme params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3555,8 +1847,6 @@ def delete_classification_policy( # pylint: disable=inconsistent-return-stateme response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3597,41 +1887,6 @@ def upsert_exception_policy( :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ @overload @@ -3668,25 +1923,6 @@ def upsert_exception_policy( :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ @overload @@ -3723,25 +1959,6 @@ def upsert_exception_policy( :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ @distributed_trace @@ -3775,43 +1992,8 @@ def upsert_exception_policy( :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3850,7 +2032,7 @@ def upsert_exception_policy( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3863,28 +2045,21 @@ def upsert_exception_policy( if response.status_code not in [200, 201]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.ExceptionPolicy, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.ExceptionPolicy, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ExceptionPolicy, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -3902,27 +2077,8 @@ def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> _mode :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3942,7 +2098,7 @@ def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> _mode params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3955,7 +2111,10 @@ def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> _mode if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3973,9 +2132,8 @@ def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> _mode return deserialized # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace - def list_exception_policies(self, **kwargs: Any) -> ItemPaged["_models.ExceptionPolicy"]: + def list_exception_policies(self, **kwargs: Any) -> Iterable["_models.ExceptionPolicy"]: """Retrieves existing exception policies. Retrieves existing exception policies. @@ -3983,25 +2141,6 @@ def list_exception_policies(self, **kwargs: Any) -> ItemPaged["_models.Exception :return: An iterator like instance of ExceptionPolicy :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.ExceptionPolicy] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -4009,7 +2148,7 @@ def list_exception_policies(self, **kwargs: Any) -> ItemPaged["_models.Exception maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.ExceptionPolicy]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4027,9 +2166,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -4047,9 +2184,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -4057,7 +2192,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.ExceptionPolicy], deserialized["value"]) + list_of_elem = _deserialize(List[_models.ExceptionPolicy], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -4072,8 +2207,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4095,7 +2228,7 @@ def delete_exception_policy( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4115,7 +2248,7 @@ def delete_exception_policy( # pylint: disable=inconsistent-return-statements params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -4127,8 +2260,6 @@ def delete_exception_policy( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4147,7 +2278,6 @@ def upsert_queue( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterQueue: - # pylint: disable=line-too-long """Creates or updates a queue. Creates or updates a queue. @@ -4169,42 +2299,7 @@ def upsert_queue( :paramtype match_condition: ~azure.core.MatchConditions :return: RouterQueue. The RouterQueue is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } + :raises ~azure.core.exceptions.HttpResponseError: """ @overload @@ -4219,7 +2314,6 @@ def upsert_queue( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterQueue: - # pylint: disable=line-too-long """Creates or updates a queue. Creates or updates a queue. @@ -4242,25 +2336,6 @@ def upsert_queue( :return: RouterQueue. The RouterQueue is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueue :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } """ @overload @@ -4275,7 +2350,6 @@ def upsert_queue( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterQueue: - # pylint: disable=line-too-long """Creates or updates a queue. Creates or updates a queue. @@ -4298,25 +2372,6 @@ def upsert_queue( :return: RouterQueue. The RouterQueue is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueue :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } """ @distributed_trace @@ -4330,7 +2385,6 @@ def upsert_queue( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterQueue: - # pylint: disable=line-too-long """Creates or updates a queue. Creates or updates a queue. @@ -4351,43 +2405,8 @@ def upsert_queue( :return: RouterQueue. The RouterQueue is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueue :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4426,7 +2445,7 @@ def upsert_queue( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -4439,28 +2458,21 @@ def upsert_queue( if response.status_code not in [200, 201]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterQueue, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterQueue, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.RouterQueue, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -4469,7 +2481,6 @@ def upsert_queue( @distributed_trace def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue: - # pylint: disable=line-too-long """Retrieves an existing queue by Id. Retrieves an existing queue by Id. @@ -4479,27 +2490,8 @@ def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue: :return: RouterQueue. The RouterQueue is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueue :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4519,7 +2511,7 @@ def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue: params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -4532,7 +2524,10 @@ def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue: if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4550,10 +2545,8 @@ def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue: return deserialized # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace - def list_queues(self, **kwargs: Any) -> ItemPaged["_models.RouterQueue"]: - # pylint: disable=line-too-long + def list_queues(self, **kwargs: Any) -> Iterable["_models.RouterQueue"]: """Retrieves existing queues. Retrieves existing queues. @@ -4561,25 +2554,6 @@ def list_queues(self, **kwargs: Any) -> ItemPaged["_models.RouterQueue"]: :return: An iterator like instance of RouterQueue :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterQueue] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -4587,7 +2561,7 @@ def list_queues(self, **kwargs: Any) -> ItemPaged["_models.RouterQueue"]: maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.RouterQueue]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4605,9 +2579,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -4625,9 +2597,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -4635,7 +2605,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.RouterQueue], deserialized["value"]) + list_of_elem = _deserialize(List[_models.RouterQueue], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -4650,8 +2620,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4671,7 +2639,7 @@ def delete_queue(self, queue_id: str, **kwargs: Any) -> None: # pylint: disable :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4691,7 +2659,7 @@ def delete_queue(self, queue_id: str, **kwargs: Any) -> None: # pylint: disable params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -4703,8 +2671,6 @@ def delete_queue(self, queue_id: str, **kwargs: Any) -> None: # pylint: disable response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4712,7 +2678,10 @@ def delete_queue(self, queue_id: str, **kwargs: Any) -> None: # pylint: disable return cls(pipeline_response, None, {}) # type: ignore -class JobRouterClientOperationsMixin(JobRouterClientMixinABC): +class JobRouterClientOperationsMixin( + ClientMixinABC[PipelineClient[HttpRequest, HttpResponse], JobRouterClientConfiguration] +): + @overload def upsert_job( self, @@ -4725,7 +2694,6 @@ def upsert_job( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterJob: - # pylint: disable=line-too-long """Creates or updates a router job. Creates or updates a router job. @@ -4748,256 +2716,6 @@ def upsert_job( :return: RouterJob. The RouterJob is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJob :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ @overload @@ -5012,7 +2730,6 @@ def upsert_job( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterJob: - # pylint: disable=line-too-long """Creates or updates a router job. Creates or updates a router job. @@ -5035,142 +2752,6 @@ def upsert_job( :return: RouterJob. The RouterJob is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJob :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ @overload @@ -5185,7 +2766,6 @@ def upsert_job( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterJob: - # pylint: disable=line-too-long """Creates or updates a router job. Creates or updates a router job. @@ -5208,142 +2788,6 @@ def upsert_job( :return: RouterJob. The RouterJob is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJob :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ @distributed_trace @@ -5357,7 +2801,6 @@ def upsert_job( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterJob: - # pylint: disable=line-too-long """Creates or updates a router job. Creates or updates a router job. @@ -5378,258 +2821,8 @@ def upsert_job( :return: RouterJob. The RouterJob is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJob :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5668,7 +2861,7 @@ def upsert_job( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -5681,28 +2874,21 @@ def upsert_job( if response.status_code not in [200, 201]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterJob, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterJob, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.RouterJob, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -5711,7 +2897,6 @@ def upsert_job( @distributed_trace def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob: - # pylint: disable=line-too-long """Retrieves an existing job by Id. Retrieves an existing job by Id. @@ -5721,126 +2906,8 @@ def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob: :return: RouterJob. The RouterJob is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJob :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5860,7 +2927,7 @@ def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob: params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -5873,7 +2940,10 @@ def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob: if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -5903,7 +2973,7 @@ def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=inc :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5923,7 +2993,7 @@ def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=inc params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -5935,8 +3005,6 @@ def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=inc response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -5944,32 +3012,30 @@ def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=inc return cls(pipeline_response, None, {}) # type: ignore @overload - def _reclassify_job( # pylint: disable=protected-access + def _reclassify_job( self, job_id: str, options: Optional[_models._models.ReclassifyJobOptions] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: ... - + ) -> _models.ReclassifyJobResult: ... @overload - def _reclassify_job( # pylint: disable=protected-access + def _reclassify_job( self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: ... - + ) -> _models.ReclassifyJobResult: ... @overload - def _reclassify_job( # pylint: disable=protected-access + def _reclassify_job( self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: ... + ) -> _models.ReclassifyJobResult: ... @distributed_trace - def _reclassify_job( # pylint: disable=protected-access + def _reclassify_job( self, job_id: str, options: Optional[Union[_models._models.ReclassifyJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any - ) -> _models._models.ReclassifyJobResult: + ) -> _models.ReclassifyJobResult: """Reclassify a job. Reclassify a job. @@ -5978,18 +3044,13 @@ def _reclassify_job( # pylint: disable=protected-access :type job_id: str :param options: Request object for reclassifying a job. Is one of the following types: ReclassifyJobOptions, JSON, IO[bytes] Default value is None. - :type options: ~azure.communication.jobrouter.models.ReclassifyJobOptions or JSON or IO[bytes] + :type options: ~azure.communication.jobrouter.models._models.ReclassifyJobOptions or JSON or + IO[bytes] :return: ReclassifyJobResult. The ReclassifyJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ReclassifyJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = {} """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6001,7 +3062,7 @@ def _reclassify_job( # pylint: disable=protected-access _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models._models.ReclassifyJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[_models.ReclassifyJobResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -6022,7 +3083,7 @@ def _reclassify_job( # pylint: disable=protected-access params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6035,16 +3096,17 @@ def _reclassify_job( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.ReclassifyJobResult, response.json() # pylint: disable=protected-access - ) + deserialized = _deserialize(_models.ReclassifyJobResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -6052,30 +3114,27 @@ def _reclassify_job( # pylint: disable=protected-access return deserialized # type: ignore @overload - def _cancel_job( # pylint: disable=protected-access + def _cancel_job( self, job_id: str, options: Optional[_models.CancelJobOptions] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: ... - + ) -> _models.CancelJobResult: ... @overload - def _cancel_job( # pylint: disable=protected-access + def _cancel_job( self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: ... - + ) -> _models.CancelJobResult: ... @overload - def _cancel_job( # pylint: disable=protected-access + def _cancel_job( self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: ... + ) -> _models.CancelJobResult: ... @distributed_trace - def _cancel_job( # pylint: disable=protected-access + def _cancel_job( self, job_id: str, options: Optional[Union[_models.CancelJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any - ) -> _models._models.CancelJobResult: - # pylint: disable=line-too-long + ) -> _models.CancelJobResult: """Submits request to cancel an existing job by Id while supplying free-form cancellation reason. Submits request to cancel an existing job by Id while supplying free-form cancellation reason. @@ -6088,20 +3147,8 @@ def _cancel_job( # pylint: disable=protected-access :return: CancelJobResult. The CancelJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.CancelJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "dispositionCode": "str", # Optional. Indicates the outcome of a job, - populate this field with your own custom values. If not provided, default value - of "Cancelled" is set. - "note": "str" # Optional. A note that will be appended to a job's Notes - collection with the current timestamp. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6113,7 +3160,7 @@ def _cancel_job( # pylint: disable=protected-access _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models._models.CancelJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[_models.CancelJobResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -6134,7 +3181,7 @@ def _cancel_job( # pylint: disable=protected-access params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6147,16 +3194,17 @@ def _cancel_job( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.CancelJobResult, response.json() # pylint: disable=protected-access - ) + deserialized = _deserialize(_models.CancelJobResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -6164,7 +3212,7 @@ def _cancel_job( # pylint: disable=protected-access return deserialized # type: ignore @overload - def _complete_job( # pylint: disable=protected-access + def _complete_job( self, job_id: str, assignment_id: str, @@ -6172,10 +3220,9 @@ def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: ... - + ) -> _models.CompleteJobResult: ... @overload - def _complete_job( # pylint: disable=protected-access + def _complete_job( self, job_id: str, assignment_id: str, @@ -6183,10 +3230,9 @@ def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: ... - + ) -> _models.CompleteJobResult: ... @overload - def _complete_job( # pylint: disable=protected-access + def _complete_job( self, job_id: str, assignment_id: str, @@ -6194,16 +3240,16 @@ def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: ... + ) -> _models.CompleteJobResult: ... @distributed_trace - def _complete_job( # pylint: disable=protected-access + def _complete_job( self, job_id: str, assignment_id: str, options: Optional[Union[_models.CompleteJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any - ) -> _models._models.CompleteJobResult: + ) -> _models.CompleteJobResult: """Completes an assigned job. Completes an assigned job. @@ -6218,17 +3264,8 @@ def _complete_job( # pylint: disable=protected-access :return: CompleteJobResult. The CompleteJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.CompleteJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "note": "str" # Optional. A note that will be appended to a job's Notes - collection with the current timestamp. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6240,7 +3277,7 @@ def _complete_job( # pylint: disable=protected-access _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models._models.CompleteJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[_models.CompleteJobResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -6262,7 +3299,7 @@ def _complete_job( # pylint: disable=protected-access params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6275,16 +3312,17 @@ def _complete_job( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.CompleteJobResult, response.json() # pylint: disable=protected-access - ) + deserialized = _deserialize(_models.CompleteJobResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -6292,7 +3330,7 @@ def _complete_job( # pylint: disable=protected-access return deserialized # type: ignore @overload - def _close_job( # pylint: disable=protected-access + def _close_job( self, job_id: str, assignment_id: str, @@ -6300,10 +3338,9 @@ def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: ... - + ) -> _models.CloseJobResult: ... @overload - def _close_job( # pylint: disable=protected-access + def _close_job( self, job_id: str, assignment_id: str, @@ -6311,10 +3348,9 @@ def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: ... - + ) -> _models.CloseJobResult: ... @overload - def _close_job( # pylint: disable=protected-access + def _close_job( self, job_id: str, assignment_id: str, @@ -6322,17 +3358,16 @@ def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: ... + ) -> _models.CloseJobResult: ... @distributed_trace - def _close_job( # pylint: disable=protected-access + def _close_job( self, job_id: str, assignment_id: str, options: Optional[Union[_models.CloseJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any - ) -> _models._models.CloseJobResult: - # pylint: disable=line-too-long + ) -> _models.CloseJobResult: """Closes a completed job. Closes a completed job. @@ -6347,23 +3382,8 @@ def _close_job( # pylint: disable=protected-access :return: CloseJobResult. The CloseJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.CloseJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "closeAt": "2020-02-20 00:00:00", # Optional. If not provided, worker - capacity is released immediately along with a JobClosedEvent notification. If - provided, worker capacity is released along with a JobClosedEvent notification at - a future time in UTC. - "dispositionCode": "str", # Optional. Indicates the outcome of a job, - populate this field with your own custom values. - "note": "str" # Optional. A note that will be appended to a job's Notes - collection with the current timestamp. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6375,7 +3395,7 @@ def _close_job( # pylint: disable=protected-access _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models._models.CloseJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[_models.CloseJobResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -6397,7 +3417,7 @@ def _close_job( # pylint: disable=protected-access params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6410,23 +3430,23 @@ def _close_job( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.CloseJobResult, response.json() # pylint: disable=protected-access - ) + deserialized = _deserialize(_models.CloseJobResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace def list_jobs( self, @@ -6438,8 +3458,7 @@ def list_jobs( scheduled_before: Optional[datetime.datetime] = None, scheduled_after: Optional[datetime.datetime] = None, **kwargs: Any - ) -> ItemPaged["_models.RouterJob"]: - # pylint: disable=line-too-long + ) -> Iterable["_models.RouterJob"]: """Retrieves list of jobs based on filter parameters. Retrieves list of jobs based on filter parameters. @@ -6465,124 +3484,6 @@ def list_jobs( :return: An iterator like instance of RouterJob :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterJob] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -6590,7 +3491,7 @@ def list_jobs( maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.RouterJob]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6614,9 +3515,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6634,9 +3533,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6644,7 +3541,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.RouterJob], deserialized["value"]) + list_of_elem = _deserialize(List[_models.RouterJob], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -6659,8 +3556,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -6680,23 +3575,8 @@ def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.RouterJobPos MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJobPositionDetails :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "estimatedWaitTimeMinutes": 0.0, # Estimated wait time of the job rounded up - to the nearest minute. Required. - "jobId": "str", # Id of the job these details are about. Required. - "position": 0, # Position of the job in question within that queue. - Required. - "queueId": "str", # Id of the queue this job is enqueued in. Required. - "queueLength": 0 # Length of the queue: total number of enqueued jobs. - Required. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6716,7 +3596,7 @@ def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.RouterJobPos params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6729,7 +3609,10 @@ def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.RouterJobPos if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -6753,7 +3636,6 @@ def unassign_job( content_type: str = "application/json", **kwargs: Any ) -> _models.UnassignJobResult: - # pylint: disable=line-too-long """Unassign a job. Unassign a job. @@ -6770,22 +3652,6 @@ def unassign_job( :return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.UnassignJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "suspendMatching": bool # Optional. If SuspendMatching is true, then a job - is not queued for re-matching with a worker. - } - - # response body for status code(s): 200 - response == { - "jobId": "str", # Id of an unassigned job. Required. - "unassignmentCount": 0 # The number of times a job is unassigned. At a - maximum 3. Required. - } """ @overload @@ -6814,16 +3680,6 @@ def unassign_job( :return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.UnassignJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "jobId": "str", # Id of an unassigned job. Required. - "unassignmentCount": 0 # The number of times a job is unassigned. At a - maximum 3. Required. - } """ @overload @@ -6852,16 +3708,6 @@ def unassign_job( :return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.UnassignJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "jobId": "str", # Id of an unassigned job. Required. - "unassignmentCount": 0 # The number of times a job is unassigned. At a - maximum 3. Required. - } """ @distributed_trace @@ -6872,7 +3718,6 @@ def unassign_job( options: Optional[Union[_models.UnassignJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any ) -> _models.UnassignJobResult: - # pylint: disable=line-too-long """Unassign a job. Unassign a job. @@ -6887,24 +3732,8 @@ def unassign_job( :return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.UnassignJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "suspendMatching": bool # Optional. If SuspendMatching is true, then a job - is not queued for re-matching with a worker. - } - - # response body for status code(s): 200 - response == { - "jobId": "str", # Id of an unassigned job. Required. - "unassignmentCount": 0 # The number of times a job is unassigned. At a - maximum 3. Required. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6938,7 +3767,7 @@ def unassign_job( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6951,7 +3780,10 @@ def unassign_job( if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -6980,20 +3812,8 @@ def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -> _mod :return: AcceptJobOfferResult. The AcceptJobOfferResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.AcceptJobOfferResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "assignmentId": "str", # Id of job assignment that assigns a worker that has - accepted an offer to a job. Required. - "jobId": "str", # Id of the job assigned. Required. - "workerId": "str" # Id of the worker that has been assigned this job. - Required. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -7014,7 +3834,7 @@ def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -> _mod params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7027,7 +3847,10 @@ def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -> _mod if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -7042,7 +3865,7 @@ def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) -> _mod return deserialized # type: ignore @overload - def _decline_job_offer( # pylint: disable=protected-access + def _decline_job_offer( self, worker_id: str, offer_id: str, @@ -7050,10 +3873,9 @@ def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: ... - + ) -> _models.DeclineJobOfferResult: ... @overload - def _decline_job_offer( # pylint: disable=protected-access + def _decline_job_offer( self, worker_id: str, offer_id: str, @@ -7061,10 +3883,9 @@ def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: ... - + ) -> _models.DeclineJobOfferResult: ... @overload - def _decline_job_offer( # pylint: disable=protected-access + def _decline_job_offer( self, worker_id: str, offer_id: str, @@ -7072,17 +3893,16 @@ def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: ... + ) -> _models.DeclineJobOfferResult: ... @distributed_trace - def _decline_job_offer( # pylint: disable=protected-access + def _decline_job_offer( self, worker_id: str, offer_id: str, options: Optional[Union[_models.DeclineJobOfferOptions, JSON, IO[bytes]]] = None, **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: - # pylint: disable=line-too-long + ) -> _models.DeclineJobOfferResult: """Declines an offer to work on a job. Declines an offer to work on a job. @@ -7098,21 +3918,8 @@ def _decline_job_offer( # pylint: disable=protected-access :return: DeclineJobOfferResult. The DeclineJobOfferResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DeclineJobOfferResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "retryOfferAt": "2020-02-20 00:00:00" # Optional. If the RetryOfferAt is not - provided, then this job will not be offered again to the worker who declined this - job unless the worker is de-registered and re-registered. If a RetryOfferAt time - is provided, then the job will be re-matched to eligible workers at the retry - time in UTC. The worker that declined the job will also be eligible for the job - at that time. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -7124,9 +3931,7 @@ def _decline_job_offer( # pylint: disable=protected-access _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models._models.DeclineJobOfferResult] = kwargs.pop( # pylint: disable=protected-access - "cls", None - ) + cls: ClsType[_models.DeclineJobOfferResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -7148,7 +3953,7 @@ def _decline_job_offer( # pylint: disable=protected-access params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7161,16 +3966,17 @@ def _decline_job_offer( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.DeclineJobOfferResult, response.json() # pylint: disable=protected-access - ) + deserialized = _deserialize(_models.DeclineJobOfferResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -7179,7 +3985,6 @@ def _decline_job_offer( # pylint: disable=protected-access @distributed_trace def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.RouterQueueStatistics: - # pylint: disable=line-too-long """Retrieves a queue's statistics. Retrieves a queue's statistics. @@ -7189,23 +3994,8 @@ def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.RouterQu :return: RouterQueueStatistics. The RouterQueueStatistics is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueueStatistics :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "length": 0, # Length of the queue: total number of enqueued jobs. Required. - "queueId": "str", # Id of the queue these details are about. Required. - "estimatedWaitTimeMinutes": { - "str": 0.0 # Optional. The estimated wait time of this queue rounded - up to the nearest minute, grouped by job priority. - }, - "longestJobWaitTimeMinutes": 0.0 # Optional. The wait time of the job that - has been enqueued in this queue for the longest. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -7225,7 +4015,7 @@ def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.RouterQu params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7238,7 +4028,10 @@ def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.RouterQu if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -7264,7 +4057,6 @@ def upsert_worker( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterWorker: - # pylint: disable=line-too-long """Creates or updates a worker. Creates or updates a worker. @@ -7287,133 +4079,6 @@ def upsert_worker( :return: RouterWorker. The RouterWorker is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterWorker :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ @overload @@ -7428,7 +4093,6 @@ def upsert_worker( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterWorker: - # pylint: disable=line-too-long """Creates or updates a worker. Creates or updates a worker. @@ -7451,71 +4115,6 @@ def upsert_worker( :return: RouterWorker. The RouterWorker is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterWorker :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ @overload @@ -7530,7 +4129,6 @@ def upsert_worker( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterWorker: - # pylint: disable=line-too-long """Creates or updates a worker. Creates or updates a worker. @@ -7553,71 +4151,6 @@ def upsert_worker( :return: RouterWorker. The RouterWorker is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterWorker :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ @distributed_trace @@ -7631,7 +4164,6 @@ def upsert_worker( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterWorker: - # pylint: disable=line-too-long """Creates or updates a worker. Creates or updates a worker. @@ -7652,135 +4184,8 @@ def upsert_worker( :return: RouterWorker. The RouterWorker is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterWorker :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -7819,7 +4224,7 @@ def upsert_worker( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7832,28 +4237,21 @@ def upsert_worker( if response.status_code not in [200, 201]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterWorker, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterWorker, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.RouterWorker, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -7862,7 +4260,6 @@ def upsert_worker( @distributed_trace def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorker: - # pylint: disable=line-too-long """Retrieves an existing worker by Id. Retrieves an existing worker by Id. @@ -7872,73 +4269,8 @@ def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorker: :return: RouterWorker. The RouterWorker is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterWorker :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -7958,7 +4290,7 @@ def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorker: params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7971,7 +4303,10 @@ def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorker: if response.status_code not in [200]: if _stream: - response.read() # Load the body in memory and close the socket + try: + response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -8001,7 +4336,7 @@ def delete_worker(self, worker_id: str, **kwargs: Any) -> None: # pylint: disab :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -8021,7 +4356,7 @@ def delete_worker(self, worker_id: str, **kwargs: Any) -> None: # pylint: disab params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -8033,15 +4368,12 @@ def delete_worker(self, worker_id: str, **kwargs: Any) -> None: # pylint: disab response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if cls: return cls(pipeline_response, None, {}) # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace def list_workers( self, @@ -8051,8 +4383,7 @@ def list_workers( queue_id: Optional[str] = None, has_capacity: Optional[bool] = None, **kwargs: Any - ) -> ItemPaged["_models.RouterWorker"]: - # pylint: disable=line-too-long + ) -> Iterable["_models.RouterWorker"]: """Retrieves existing workers. Retrieves existing workers. @@ -8074,71 +4405,6 @@ def list_workers( :return: An iterator like instance of RouterWorker :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterWorker] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -8146,7 +4412,7 @@ def list_workers( maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.RouterWorker]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -8168,9 +4434,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -8188,9 +4452,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -8198,7 +4460,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.RouterWorker], deserialized["value"]) + list_of_elem = _deserialize(List[_models.RouterWorker], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, iter(list_of_elem) @@ -8213,8 +4475,6 @@ def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py index ba355e5a489f..8bcb627aa475 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_operations/_patch.py @@ -1,2132 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import sys -import datetime -from typing import ( - List, - Any, - Optional, - Dict, - Union, - overload, - IO, - Literal, -) -from azure.core import MatchConditions -from azure.core.paging import ItemPaged -from azure.core.tracing.decorator import distributed_trace -from .. import models as _models -from ._operations import ( - JobRouterClientOperationsMixin as JobRouterClientOperationsMixinGenerated, - JobRouterAdministrationClientOperationsMixin as JobRouterAdministrationClientOperationsMixinGenerated, -) -from .._model_base import _deserialize_datetime as _convert_str_to_datetime # pylint:disable=protected-access +from typing import List -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - - -class JobRouterAdministrationClientOperationsMixin( - JobRouterAdministrationClientOperationsMixinGenerated -): # pylint:disable=too-many-lines,line-too-long,name-too-long - # region ExceptionPolicy - @overload - def upsert_exception_policy( # pylint: disable=arguments-differ - self, - exception_policy_id: str, - *, - exception_rules: Optional[List[_models.ExceptionRule]], - name: Optional[str], - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ExceptionPolicy: - """Update an exception policy. - - :param str exception_policy_id: Id of the exception policy. - - :keyword exception_rules: (Optional) A dictionary collection of exception rules on the exception - policy. Key is the Id of each exception rule. - :paramtype exception_rules: Optional[Dict[str, ~azure.communication.jobrouter.models.ExceptionRule]] - - :keyword Optional[str] name: The name of this policy. - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of ExceptionPolicy - :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - - .. admonition:: Example: - - .. literalinclude:: ../samples/exception_policy_crud_ops.py - :start-after: [START update_exception_policy] - :end-before: [END update_exception_policy] - :language: python - :dedent: 8 - :caption: Using a JobRouterAdministrationClient to update an exception policy - """ - - @overload - def upsert_exception_policy( - self, - exception_policy_id: str, - resource: _models.ExceptionPolicy, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ExceptionPolicy: - """Creates or updates a exception policy. - - Creates or updates a exception policy. - - :param exception_policy_id: The Id of the exception policy. Required. - :type exception_policy_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.ExceptionPolicy - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_exception_policy( - self, - exception_policy_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ExceptionPolicy: - """Creates or updates a exception policy. - - Creates or updates a exception policy. - - :param exception_policy_id: The Id of the exception policy. Required. - :type exception_policy_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_exception_policy( - self, - exception_policy_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ExceptionPolicy: - """Creates or updates a exception policy. - - Creates or updates a exception policy. - - :param exception_policy_id: The Id of the exception policy. Required. - :type exception_policy_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def upsert_exception_policy( # pylint: disable=docstring-missing-param - self, exception_policy_id: str, *args: Union[_models.ExceptionPolicy, JSON, IO[bytes]], **kwargs: Any - ) -> _models.ExceptionPolicy: - """Update an exception policy. - - :param str exception_policy_id: Id of the exception policy. - - :keyword exception_rules: (Optional) A dictionary collection of exception rules on the exception - policy. Key is the Id of each exception rule. - :paramtype exception_rules: Optional[Dict[str, ~azure.communication.jobrouter.models.ExceptionRule]] - - :keyword Optional[str] name: The name of this policy. - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of ExceptionPolicy - :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - - .. admonition:: Example: - - .. literalinclude:: ../samples/exception_policy_crud_ops.py - :start-after: [START update_exception_policy] - :end-before: [END update_exception_policy] - :language: python - :dedent: 8 - :caption: Using a JobRouterAdministrationClient to update an exception policy - """ - if not exception_policy_id: - raise ValueError("exception_policy_id cannot be None.") - - exception_policy: Union[_models.ExceptionPolicy, JSON, IO[bytes]] = _models.ExceptionPolicy() - if len(args) == 1: - exception_policy = args[0] - - patch = exception_policy - if isinstance(exception_policy, _models.ExceptionPolicy): - patch = _models.ExceptionPolicy( - name=kwargs.pop("name", exception_policy.name), - exception_rules=kwargs.pop("exception_rules", exception_policy.exception_rules), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return super().upsert_exception_policy( - exception_policy_id=exception_policy_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_exception_policies( - self, *, results_per_page: Optional[int] = None, **kwargs: Any - ) -> ItemPaged[_models.ExceptionPolicy]: - """Retrieves existing exception policies. - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of ExceptionPolicy - :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.ExceptionPolicy] - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/exception_policy_crud_ops.py - :start-after: [START list_exception_policies] - :end-before: [END list_exception_policies] - :language: python - :dedent: 8 - :caption: Using a JobRouterAdministrationClient to list exception policies - - .. admonition:: Example: - - .. literalinclude:: ../samples/exception_policy_crud_ops.py - :start-after: [START list_exception_policies_batched] - :end-before: [END list_exception_policies_batched] - :language: python - :dedent: 8 - :caption: Using a JobRouterAdministrationClient to list exception policies in batches - """ - return super().list_exception_policies(maxpagesize=results_per_page, **kwargs) - - # endregion ExceptionPolicy - - # region DistributionPolicy - @overload - def upsert_distribution_policy( # pylint: disable=arguments-differ - self, - distribution_policy_id: str, - *, - name: Optional[str] = None, - offer_expires_after_seconds: Optional[float] = None, - mode: Optional[Union[_models.BestWorkerMode, _models.LongestIdleMode, _models.RoundRobinMode]] = None, - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.DistributionPolicy: - """Update a distribution policy. - - :param str distribution_policy_id: Id of the distribution policy. - - :keyword Optional[float] offer_expires_after_seconds: The expiry time of any offers created under this policy - will be governed by the offer time to live. - - :keyword mode: Specified distribution mode - :paramtype mode: Optional[Union[~azure.communication.jobrouter.models.BestWorkerMode, - ~azure.communication.jobrouter.models.LongestIdleMode, - ~azure.communication.jobrouter.models.RoundRobinMode]] - - :keyword Optional[str] name: The name of this policy. - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of DistributionPolicy - :rtype: ~azure.communication.jobrouter.models.DistributionPolicy - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/distribution_policy_crud_ops.py - :start-after: [START update_distribution_policy] - :end-before: [END update_distribution_policy] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a distribution policy - """ - - @overload - def upsert_distribution_policy( - self, - distribution_policy_id: str, - resource: _models.DistributionPolicy, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.DistributionPolicy: - """Creates or updates a distribution policy. - - Creates or updates a distribution policy. - - :param distribution_policy_id: The unique identifier of the policy. Required. - :type distribution_policy_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.DistributionPolicy - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.DistributionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_distribution_policy( - self, - distribution_policy_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.DistributionPolicy: - """Creates or updates a distribution policy. - - Creates or updates a distribution policy. - - :param distribution_policy_id: The unique identifier of the policy. Required. - :type distribution_policy_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.DistributionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_distribution_policy( - self, - distribution_policy_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.DistributionPolicy: - """Creates or updates a distribution policy. - - Creates or updates a distribution policy. - - :param distribution_policy_id: The unique identifier of the policy. Required. - :type distribution_policy_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.DistributionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def upsert_distribution_policy( # pylint: disable=docstring-missing-param,docstring-should-be-keyword - self, distribution_policy_id: str, *args: Union[_models.DistributionPolicy, JSON, IO[bytes]], **kwargs: Any - ) -> _models.DistributionPolicy: - """Update a distribution policy. - - :param str distribution_policy_id: Id of the distribution policy. - - :keyword Optional[float] offer_expires_after_seconds: The expiry time of any offers created under this policy - will be governed by the offer time to live. - - :keyword mode: Specified distribution mode - :paramtype mode: Optional[Union[~azure.communication.jobrouter.models.BestWorkerMode, - ~azure.communication.jobrouter.models.LongestIdleMode, - ~azure.communication.jobrouter.models.RoundRobinMode]] - - :keyword Optional[str] name: The name of this policy. - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of DistributionPolicy - :rtype: ~azure.communication.jobrouter.models.DistributionPolicy - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/distribution_policy_crud_ops.py - :start-after: [START update_distribution_policy] - :end-before: [END update_distribution_policy] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a distribution policy - """ - if not distribution_policy_id: - raise ValueError("distribution_policy_id cannot be None.") - - distribution_policy: Union[_models.DistributionPolicy, JSON, IO[bytes]] = _models.DistributionPolicy() - if len(args) == 1: - distribution_policy = args[0] - - patch = distribution_policy - if isinstance(distribution_policy, _models.DistributionPolicy): - patch = _models.DistributionPolicy( - name=kwargs.pop("name", distribution_policy.name), - offer_expires_after_seconds=kwargs.pop( - "offer_expires_after_seconds", distribution_policy.offer_expires_after_seconds - ), - mode=kwargs.pop("mode", distribution_policy.mode), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return super().upsert_distribution_policy( - distribution_policy_id=distribution_policy_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_distribution_policies( - self, *, results_per_page: Optional[int] = None, **kwargs: Any - ) -> ItemPaged[_models.DistributionPolicy]: - """Retrieves existing distribution policies. - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of DistributionPolicy - :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.DistributionPolicy] - :raises: ~azure.core.exceptions.HttpResponseError - - .. admonition:: Example: - - .. literalinclude:: ../samples/distribution_policy_crud_ops.py - :start-after: [START list_distribution_policies] - :end-before: [END list_distribution_policies] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list distribution policies - - .. admonition:: Example: - - .. literalinclude:: ../samples/distribution_policy_crud_ops.py - :start-after: [START list_distribution_policies_batched] - :end-before: [END list_distribution_policies_batched] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list distribution policies in batches - """ - return super().list_distribution_policies(maxpagesize=results_per_page, **kwargs) - - # endregion DistributionPolicy - - # region Queue - @overload - def upsert_queue( # pylint: disable=arguments-differ - self, - queue_id: str, - *, - distribution_policy_id: Optional[str], - name: Optional[str], - labels: Optional[Dict[str, Union[int, float, str, bool]]], - exception_policy_id: Optional[str], - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterQueue: - """Update a job queue - - :param str queue_id: Id of the queue. - - :keyword Optional[str] distribution_policy_id: The ID of the distribution policy that will determine - how a job is distributed to workers. - - :keyword Optional[str] name: The name of this queue. - - :keyword labels: A set of key/value pairs that are - identifying attributes used by the rules engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool]]] - - :keyword Optional[str] exception_policy_id: The ID of the exception policy that determines various - job escalation rules. - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterQueue - :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/job_queue_crud_ops.py - :start-after: [START update_queue] - :end-before: [END update_queue] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a queue - """ - - @overload - def upsert_queue( - self, - queue_id: str, - resource: _models.RouterQueue, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterQueue: - """Creates or updates a queue. - - Creates or updates a queue. - - :param queue_id: The Id of this queue. Required. - :type queue_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.RouterQueue - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterQueue. The RouterQueue is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_queue( - self, - queue_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterQueue: - """Creates or updates a queue. - - Creates or updates a queue. - - :param queue_id: The Id of this queue. Required. - :type queue_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterQueue. The RouterQueue is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_queue( - self, - queue_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterQueue: - """Creates or updates a queue. - - Creates or updates a queue. - - :param queue_id: The Id of this queue. Required. - :type queue_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterQueue. The RouterQueue is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def upsert_queue( # pylint: disable=docstring-missing-param - self, queue_id: str, *args: Union[_models.RouterQueue, JSON, IO[bytes]], **kwargs: Any - ) -> _models.RouterQueue: - """Update a job queue - - :param str queue_id: Id of the queue. - - :keyword Optional[str] distribution_policy_id: The ID of the distribution policy that will determine - how a job is distributed to workers. - - :keyword Optional[str] name: The name of this queue. - - :keyword labels: A set of key/value pairs that are - identifying attributes used by the rules engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool]]] - - :keyword Optional[str] exception_policy_id: The ID of the exception policy that determines various - job escalation rules. - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterQueue - :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/job_queue_crud_ops.py - :start-after: [START update_queue] - :end-before: [END update_queue] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a queue - """ - if not queue_id: - raise ValueError("queue_id cannot be None.") - - queue: Union[_models.RouterQueue, JSON, IO[bytes]] = _models.RouterQueue() - if len(args) == 1: - queue = args[0] - - patch = queue - if isinstance(queue, _models.RouterQueue): - patch = _models.RouterQueue( - name=kwargs.pop("name", queue.name), - distribution_policy_id=kwargs.pop("distribution_policy_id", queue.distribution_policy_id), - labels=kwargs.pop("labels", queue.labels), - exception_policy_id=kwargs.pop("exception_policy_id", queue.exception_policy_id), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return super().upsert_queue( - queue_id=queue_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_queues(self, *, results_per_page: Optional[int] = None, **kwargs: Any) -> ItemPaged[_models.RouterQueue]: - """Retrieves existing queues. - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of RouterQueueItem - :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterQueueItem] - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/job_queue_crud_ops.py - :start-after: [START list_queues] - :end-before: [END list_queues] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list queues - - .. admonition:: Example: - - .. literalinclude:: ../samples/job_queue_crud_ops.py - :start-after: [START list_queues_batched] - :end-before: [END list_queues_batched] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list queues in batches - """ - return super().list_queues(maxpagesize=results_per_page, **kwargs) - - # endregion Queue - - # region ClassificationPolicy - @overload - def upsert_classification_policy( # pylint: disable=arguments-differ - self, - classification_policy_id: str, - *, - name: Optional[str], - fallback_queue_id: Optional[str], - queue_selectors: Optional[ - List[ - Union[ - _models.StaticQueueSelectorAttachment, - _models.ConditionalQueueSelectorAttachment, - _models.RuleEngineQueueSelectorAttachment, - _models.PassThroughQueueSelectorAttachment, - _models.WeightedAllocationQueueSelectorAttachment, - ] - ] - ], # pylint: disable=line-too-long - prioritization_rule: Optional[ - Union[ - _models.StaticRouterRule, - _models.ExpressionRouterRule, - _models.FunctionRouterRule, - _models.WebhookRouterRule, - ] - ], # pylint: disable=line-too-long - worker_selectors: Optional[ - List[ - Union[ - _models.StaticWorkerSelectorAttachment, - _models.ConditionalWorkerSelectorAttachment, - _models.RuleEngineWorkerSelectorAttachment, - _models.PassThroughWorkerSelectorAttachment, - _models.WeightedAllocationWorkerSelectorAttachment, - ] - ] - ], # pylint: disable=line-too-long - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ClassificationPolicy: - """Update a classification policy - - :param str classification_policy_id: Id of the classification policy. - - :keyword Optional[str] name: Friendly name of this policy. - - :keyword fallback_queue_id: The fallback queue to select if the queue selector doesn't find a match. - :paramtype fallback_queue_id: Optional[str] - - :keyword queue_selector_attachments: The queue selectors to resolve a queue for a given job. - :paramtype queue_selector_attachments: Optional[List[Union - ~azure.communication.jobrouter.models.StaticQueueSelectorAttachment, - ~azure.communication.jobrouter.models.ConditionalQueueSelectorAttachment, - ~azure.communication.jobrouter.models.RuleEngineQueueSelectorAttachment, - ~azure.communication.jobrouter.models.PassThroughQueueSelectorAttachment, - ~azure.communication.jobrouter.models.WeightedAllocationQueueSelectorAttachment]]] - - :keyword prioritization_rule: The rule to determine a priority score for a given job. - :paramtype prioritization_rule: Optional[Union[~azure.communication.jobrouter.models.StaticRouterRule, - ~azure.communication.jobrouter.models.ExpressionRouterRule, - ~azure.communication.jobrouter.models.FunctionRouterRule, - ~azure.communication.jobrouter.models.WebhookRouterRule]] - - :keyword worker_selector_attachments: The worker label selectors to attach to a given job. - :paramtype worker_selector_attachments: Optional[List[Union[ - ~azure.communication.jobrouter.models.StaticWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.ConditionalWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.RuleEngineWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.PassThroughWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.WeightedAllocationWorkerSelectorAttachment]]] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of ClassificationPolicy - :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/classification_policy_crud_ops.py - :start-after: [START update_classification_policy] - :end-before: [END update_classification_policy] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a classification policy - """ - - @overload - def upsert_classification_policy( - self, - classification_policy_id: str, - resource: _models.ClassificationPolicy, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ClassificationPolicy: - """Creates or updates a classification policy. - - Creates or updates a classification policy. - - :param classification_policy_id: Unique identifier of this policy. Required. - :type classification_policy_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.ClassificationPolicy - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_classification_policy( - self, - classification_policy_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ClassificationPolicy: - """Creates or updates a classification policy. - - Creates or updates a classification policy. - - :param classification_policy_id: Unique identifier of this policy. Required. - :type classification_policy_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_classification_policy( - self, - classification_policy_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ClassificationPolicy: - """Creates or updates a classification policy. - - Creates or updates a classification policy. - - :param classification_policy_id: Unique identifier of this policy. Required. - :type classification_policy_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def upsert_classification_policy( # pylint: disable=docstring-missing-param - self, classification_policy_id: str, *args: Union[_models.ClassificationPolicy, JSON, IO[bytes]], **kwargs: Any - ) -> _models.ClassificationPolicy: - """Update a classification policy - - :param str classification_policy_id: Id of the classification policy. - - :keyword Optional[str] name: Friendly name of this policy. - - :keyword fallback_queue_id: The fallback queue to select if the queue selector doesn't find a match. - :paramtype fallback_queue_id: Optional[str] - - :keyword queue_selector_attachments: The queue selectors to resolve a queue for a given job. - :paramtype queue_selector_attachments: Optional[List[Union - ~azure.communication.jobrouter.models.StaticQueueSelectorAttachment, - ~azure.communication.jobrouter.models.ConditionalQueueSelectorAttachment, - ~azure.communication.jobrouter.models.RuleEngineQueueSelectorAttachment, - ~azure.communication.jobrouter.models.PassThroughQueueSelectorAttachment, - ~azure.communication.jobrouter.models.WeightedAllocationQueueSelectorAttachment]]] - - :keyword prioritization_rule: The rule to determine a priority score for a given job. - :paramtype prioritization_rule: Optional[Union[~azure.communication.jobrouter.models.StaticRouterRule, - ~azure.communication.jobrouter.models.ExpressionRouterRule, - ~azure.communication.jobrouter.models.FunctionRouterRule, - ~azure.communication.jobrouter.models.WebhookRouterRule]] - - :keyword worker_selector_attachments: The worker label selectors to attach to a given job. - :paramtype worker_selector_attachments: Optional[List[Union[ - ~azure.communication.jobrouter.models.StaticWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.ConditionalWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.RuleEngineWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.PassThroughWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.WeightedAllocationWorkerSelectorAttachment]]] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of ClassificationPolicy - :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/classification_policy_crud_ops.py - :start-after: [START update_classification_policy] - :end-before: [END update_classification_policy] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a classification policy - """ - if not classification_policy_id: - raise ValueError("classification_policy_id cannot be None.") - - classification_policy: Union[_models.ClassificationPolicy, JSON, IO[bytes]] = _models.ClassificationPolicy() - if len(args) == 1: - classification_policy = args[0] - - patch = classification_policy - if isinstance(classification_policy, _models.ClassificationPolicy): - patch = _models.ClassificationPolicy( - name=kwargs.pop("name", classification_policy.name), - fallback_queue_id=kwargs.pop("fallback_queue_id", classification_policy.fallback_queue_id), - queue_selector_attachments=kwargs.pop( - "queue_selector_attachments", classification_policy.queue_selector_attachments - ), - prioritization_rule=kwargs.pop("prioritization_rule", classification_policy.prioritization_rule), - worker_selector_attachments=kwargs.pop( - "worker_selector_attachments", classification_policy.worker_selector_attachments - ), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return super().upsert_classification_policy( - classification_policy_id=classification_policy_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_classification_policies( - self, *, results_per_page: Optional[int] = None, **kwargs: Any - ) -> ItemPaged[_models.ClassificationPolicy]: - """Retrieves existing classification policies. - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of ClassificationPolicy - :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.ClassificationPolicy] - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/classification_policy_crud_ops.py - :start-after: [START list_classification_policies] - :end-before: [END list_classification_policies] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list classification policies - - .. admonition:: Example: - - .. literalinclude:: ../samples/classification_policy_crud_ops.py - :start-after: [START list_classification_policies_batched] - :end-before: [END list_classification_policies_batched] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list classification policies in batches - """ - return super().list_classification_policies(maxpagesize=results_per_page, **kwargs) - - # endregion ClassificationPolicy - - -class JobRouterClientOperationsMixin(JobRouterClientOperationsMixinGenerated): - # region Worker - @overload - def upsert_worker( # pylint: disable=arguments-differ - self, - worker_id: str, - *, - queues: Optional[List[str]], - capacity: Optional[int], - labels: Optional[Dict[str, Union[int, float, str, bool]]], - tags: Optional[Dict[str, Union[int, float, str, bool]]], - channels: Optional[List[_models.RouterChannel]], - available_for_offers: Optional[bool], - max_concurrent_offers: Optional[int], - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterWorker: - """Update a router worker. - - :param str worker_id: Id of the worker. - - :keyword queue_assignments: The queue(s) that this worker can receive work from. - :paramtype queue_assignments: Optional[Dict[str, Union[~collections.abc.MutableMapping[str, Any], None]]] - - :keyword total_capacity: The total capacity score this worker has to manage multiple concurrent - jobs. - :paramtype total_capacity: Optional[int] - - :keyword labels: A set of key/value pairs that are identifying attributes used by the rules - engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword tags: A set of tags. A set of non-identifying attributes attached to this worker. - :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword channel_configurations: The channel(s) this worker can handle and their impact on the - workers capacity. - :paramtype channel_configurations: Optional[Dict[str, - ~azure.communication.jobrouter.models.ChannelConfiguration]] - - :keyword available_for_offers: A flag indicating this worker is open to receive offers or not. - :paramtype available_for_offers: Optional[bool] - - :keyword max_concurrent_offers: If this is set, the worker will only receive up to this many new - offers at a time. - :paramtype max_concurrent_offers: Optional[int] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterWorker - :rtype: ~azure.communication.jobrouter.models.RouterWorker - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops.py - :start-after: [START update_worker] - :end-before: [END update_worker] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to update a worker - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops.py - :start-after: [START register_worker] - :end-before: [END register_worker] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to register a worker - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops.py - :start-after: [START deregister_worker] - :end-before: [END deregister_worker] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to de-register a worker - """ - - @overload - def upsert_worker( - self, - worker_id: str, - resource: _models.RouterWorker, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterWorker: - """Creates or updates a worker. - - Creates or updates a worker. - - :param worker_id: Id of the worker. Required. - :type worker_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.RouterWorker - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterWorker. The RouterWorker is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterWorker - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_worker( - self, - worker_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterWorker: - """Creates or updates a worker. - - Creates or updates a worker. - - :param worker_id: Id of the worker. Required. - :type worker_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterWorker. The RouterWorker is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterWorker - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_worker( - self, - worker_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterWorker: - """Creates or updates a worker. - - Creates or updates a worker. - - :param worker_id: Id of the worker. Required. - :type worker_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterWorker. The RouterWorker is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterWorker - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def upsert_worker( # pylint: disable=docstring-missing-param - self, worker_id: str, *args: Union[_models.RouterWorker, JSON, IO[bytes]], **kwargs: Any - ) -> _models.RouterWorker: - """Update a router worker. - - :param str worker_id: Id of the worker. - - :keyword queue_assignments: The queue(s) that this worker can receive work from. - :paramtype queue_assignments: Optional[Dict[str, Union[~collections.abc.MutableMapping[str, Any], None]]] - - :keyword total_capacity: The total capacity score this worker has to manage multiple concurrent - jobs. - :paramtype total_capacity: Optional[int] - - :keyword labels: A set of key/value pairs that are identifying attributes used by the rules - engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword tags: A set of tags. A set of non-identifying attributes attached to this worker. - :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword channel_configurations: The channel(s) this worker can handle and their impact on the - workers capacity. - :paramtype channel_configurations: Optional[Dict[str, - ~azure.communication.jobrouter.models.ChannelConfiguration]] - - :keyword available_for_offers: A flag indicating this worker is open to receive offers or not. - :paramtype available_for_offers: Optional[bool] - - :keyword max_concurrent_offers: If this is set, the worker will only receive up to this many new - offers at a time. - :paramtype max_concurrent_offers: Optional[int] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterWorker - :rtype: ~azure.communication.jobrouter.models.RouterWorker - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops.py - :start-after: [START update_worker] - :end-before: [END update_worker] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to update a worker - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops.py - :start-after: [START register_worker] - :end-before: [END register_worker] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to register a worker - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops.py - :start-after: [START deregister_worker] - :end-before: [END deregister_worker] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to de-register a worker - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops.py - :start-after: [START create_worker_w_limit_concurrent_offers] - :end-before: [END create_worker_w_limit_concurrent_offers] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to create a worker with concurrent offer limit - """ - if not worker_id: - raise ValueError("worker_id cannot be None.") - - router_worker: Union[_models.RouterWorker, JSON, IO[bytes]] = _models.RouterWorker() - if len(args) == 1: - router_worker = args[0] - - patch = router_worker - if isinstance(router_worker, _models.RouterWorker): - patch = _models.RouterWorker( - queues=kwargs.pop("queues", router_worker.queues), - capacity=kwargs.pop("capacity", router_worker.capacity), - labels=kwargs.pop("labels", router_worker.labels), - tags=kwargs.pop("tags", router_worker.tags), - channels=kwargs.pop("channels", router_worker.channels), - available_for_offers=kwargs.pop("available_for_offers", router_worker.available_for_offers), - max_concurrent_offers=kwargs.pop("max_concurrent_offers", router_worker.max_concurrent_offers), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return super().upsert_worker( - worker_id=worker_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_workers( - self, - *, - state: Optional[Union[str, _models.RouterWorkerState, Literal["all"]]] = "all", - channel_id: Optional[str] = None, - queue_id: Optional[str] = None, - has_capacity: Optional[bool] = None, - results_per_page: Optional[int] = None, - **kwargs: Any - ) -> ItemPaged[_models.RouterWorker]: - """Retrieves existing workers. - - :keyword state: If specified, select workers by worker status. Default value is "all". - Accepted value(s): active, draining, inactive, all - :paramtype state: Optional[Union[str, ~azure.communication.jobrouter.models.RouterWorkerState, Literal["all"]]] - - :keyword channel_id: If specified, select workers who have a channel configuration - with this channel. Default value is None. - :paramtype channel_id: Optional[str] - - :keyword queue_id: If specified, select workers who are assigned to this queue. - Default value is None. - :paramtype queue_id: Optional[str] - - :keyword has_capacity: If set to true, select only workers who have capacity for the - channel specified by ``channelId`` or for any channel - :paramtype has_capacity: Optional[bool] - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of RouterWorkerItem - :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterWorkerItem] - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops.py - :start-after: [START list_workers] - :end-before: [END list_workers] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to retrieve workers - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops.py - :start-after: [START list_workers_batched] - :end-before: [END list_workers_batched] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to retrieve workers in batches - """ - return super().list_workers( - maxpagesize=results_per_page, - state=state, - channel_id=channel_id, - queue_id=queue_id, - has_capacity=has_capacity, - **kwargs - ) - - # endregion Worker - - # region Job - @overload - def upsert_job( # pylint: disable=arguments-differ - self, - job_id: str, - *, - channel_reference: Optional[str], - channel_id: Optional[str], - classification_policy_id: Optional[str], - queue_id: Optional[str], - priority: Optional[int], - disposition_code: Optional[str], - requested_worker_selectors: Optional[List[_models.RouterWorkerSelector]], - labels: Optional[Dict[str, Union[int, float, str, bool, None]]], - tags: Optional[Dict[str, Union[int, float, str, bool, None]]], - notes: Optional[Dict[datetime.datetime, str]], - matching_mode: Optional[_models.JobMatchingMode], - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterJob: - """Update a job. - - :param str job_id: Id of the job. - - :keyword channel_reference: Reference to an external parent context, eg. call ID. - :paramtype channel_reference: Optional[str] - - :keyword channel_id: The channel identifier. eg. voice, chat, etc. - :paramtype channel_id: Optional[str] - - :keyword classification_policy_id: The Id of the Classification policy used for classifying a - job. - :paramtype classification_policy_id: Optional[str] - - :keyword queue_id: The Id of the Queue that this job is queued to. - :paramtype queue_id: Optional[str] - - :keyword priority: The priority of this job. - :paramtype priority: Optional[int] - - :keyword disposition_code: Reason code for cancelled or closed jobs. - :paramtype disposition_code: Optional[str] - - :keyword requested_worker_selectors: A collection of manually specified label selectors, which - a worker must satisfy in order to process this job. - :paramtype requested_worker_selectors: Optional[List[ - ~azure.communication.jobrouter.models.RouterWorkerSelector]] - - :keyword labels: A set of key/value pairs that are identifying attributes used by the rules - engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword tags: A set of tags. A set of non-identifying attributes attached to this job. - :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword notes: Notes attached to a job, sorted by timestamp. - :paramtype notes: Optional[Dict[~datetime.datetime, str]] - - :keyword matching_mode: If set, determines how a job will be matched - :paramtype matching_mode: Optional[~azure.communication.jobrouter.models.JobMatchingMode] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterJob - :rtype: ~azure.communication.jobrouter.models.RouterJob - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops.py - :start-after: [START update_job] - :end-before: [END update_job] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to update a job - """ - - @overload - def upsert_job( - self, - job_id: str, - resource: _models.RouterJob, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterJob: - """Creates or updates a router job. - - Creates or updates a router job. - - :param job_id: The id of the job. Required. - :type job_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.RouterJob - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterJob. The RouterJob is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterJob - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_job( - self, - job_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterJob: - """Creates or updates a router job. - - Creates or updates a router job. - - :param job_id: The id of the job. Required. - :type job_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterJob. The RouterJob is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterJob - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - def upsert_job( - self, - job_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterJob: - """Creates or updates a router job. - - Creates or updates a router job. - - :param job_id: The id of the job. Required. - :type job_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterJob. The RouterJob is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterJob - :raises ~azure.core.exceptions.HttpResponseError: - """ - - def upsert_job( # pylint: disable=docstring-missing-param - self, job_id: str, *args: Union[_models.RouterJob, JSON, IO[bytes]], **kwargs: Any - ) -> _models.RouterJob: - """Update a job. - - :param str job_id: Id of the job. - - :keyword channel_reference: Reference to an external parent context, eg. call ID. - :paramtype channel_reference: Optional[str] - - :keyword channel_id: The channel identifier. eg. voice, chat, etc. - :paramtype channel_id: Optional[str] - - :keyword classification_policy_id: The Id of the Classification policy used for classifying a - job. - :paramtype classification_policy_id: Optional[str] - - :keyword queue_id: The Id of the Queue that this job is queued to. - :paramtype queue_id: Optional[str] - - :keyword priority: The priority of this job. - :paramtype priority: Optional[int] - - :keyword disposition_code: Reason code for cancelled or closed jobs. - :paramtype disposition_code: Optional[str] - - :keyword requested_worker_selectors: A collection of manually specified label selectors, which - a worker must satisfy in order to process this job. - :paramtype requested_worker_selectors: Optional[List[ - ~azure.communication.jobrouter.models.RouterWorkerSelector]] - - :keyword labels: A set of key/value pairs that are identifying attributes used by the rules - engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword tags: A set of tags. A set of non-identifying attributes attached to this job. - :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword notes: Notes attached to a job, sorted by timestamp. - :paramtype notes: Optional[Dict[~datetime.datetime, str]] - - :keyword matching_mode: If set, determines how a job will be matched - :paramtype matching_mode: Optional[~azure.communication.jobrouter.models.JobMatchingMode] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterJob - :rtype: ~azure.communication.jobrouter.models.RouterJob - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops.py - :start-after: [START update_job] - :end-before: [END update_job] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to update a job - """ - if not job_id: - raise ValueError("job_id cannot be None.") - - router_job: Union[_models.RouterJob, JSON, IO[bytes]] = _models.RouterJob() - if len(args) == 1: - router_job = args[0] - - patch = router_job - if isinstance(router_job, _models.RouterJob): - patch = _models.RouterJob( - channel_reference=kwargs.pop("channel_reference", router_job.channel_reference), - channel_id=kwargs.pop("channel_id", router_job.channel_id), - classification_policy_id=kwargs.pop("classification_policy_id", router_job.classification_policy_id), - queue_id=kwargs.pop("queue_id", router_job.queue_id), - priority=kwargs.pop("priority", router_job.priority), - disposition_code=kwargs.pop("disposition_code", router_job.disposition_code), - requested_worker_selectors=kwargs.pop( - "requested_worker_selectors", router_job.requested_worker_selectors - ), - labels=kwargs.pop("labels", router_job.labels), - tags=kwargs.pop("tags", router_job.tags), - notes=kwargs.pop("notes", router_job.notes), - matching_mode=kwargs.pop("matching_mode", router_job.matching_mode), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return super().upsert_job( - job_id=job_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_jobs( - self, - *, - status: Optional[Union[str, _models.RouterJobStatus, Literal["all", "active"]]] = "all", - channel_id: Optional[str] = None, - queue_id: Optional[str] = None, - classification_policy_id: Optional[str] = None, - scheduled_before: Optional[Union[str, datetime.datetime]] = None, - scheduled_after: Optional[Union[str, datetime.datetime]] = None, - results_per_page: Optional[int] = None, - **kwargs: Any - ) -> ItemPaged[_models.RouterJob]: - """Retrieves list of jobs based on filter parameters. - - :keyword status: If specified, filter jobs by status. Default value is "all". - Accepted value(s): pendingClassification, queued, assigned, completed, closed, cancelled, - classificationFailed, active, all - :paramtype status: Optional[Union[str, - ~azure.communication.jobrouter.models.RouterJobStatus, Literal["all","active"]]] - - :keyword channel_id: If specified, filter jobs by channel. Default value is None. - :paramtype channel_id: Optional[str] - - :keyword queue_id: If specified, filter jobs by queue. Default value is None. - :paramtype queue_id: Optional[str] - - :keyword classification_policy_id: If specified, filter jobs by classificationPolicy. Default value is None. - :paramtype classification_policy_id: Optional[str] - - :keyword scheduled_before: If specified, filter on jobs that was scheduled before or - at given timestamp. Range: (-Inf, scheduledBefore]. Default value is None. - :paramtype scheduled_before: Optional[Union[str, ~datetime.datetime]] - - :keyword scheduled_after: If specified, filter on jobs that was scheduled at or - after given value. Range: [scheduledAfter, +Inf). Default value is None. - :paramtype scheduled_after: Optional[Union[str, ~datetime.datetime]] - - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of RouterJobItem - :rtype: ~azure.core.paging.ItemPaged[~azure.communication.jobrouter.models.RouterJobItem] - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops.py - :start-after: [START list_jobs] - :end-before: [END list_jobs] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to retrieve jobs - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops.py - :start-after: [START list_jobs_batched] - :end-before: [END list_jobs_batched] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to retrieve jobs in batches - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops.py - :start-after: [START list_scheduled_jobs] - :end-before: [END list_scheduled_jobs] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to retrieve scheduled jobs - """ - if scheduled_before is not None and isinstance(scheduled_before, str): - scheduled_before = _convert_str_to_datetime(scheduled_before) - - if scheduled_after is not None and isinstance(scheduled_after, str): - scheduled_after = _convert_str_to_datetime(scheduled_after) - - return super().list_jobs( - maxpagesize=results_per_page, - status=status, - channel_id=channel_id, - queue_id=queue_id, - classification_policy_id=classification_policy_id, - scheduled_before=scheduled_before, - scheduled_after=scheduled_after, - **kwargs - ) - - @distributed_trace - def reclassify_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=arguments-differ,arguments-renamed - """Reclassify a job. - - :param str job_id: Id of the job. - - :return: None - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops.py - :start-after: [START reclassify_job] - :end-before: [END reclassify_job] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to re-classify a job - """ - if not job_id: - raise ValueError("job_id cannot be None.") - - super()._reclassify_job(job_id=job_id, options={}, **kwargs) - - @distributed_trace - def cancel_job( - self, job_id: str, options: Optional[Union[_models._models.CancelJobOptions, JSON, IO]] = None, **kwargs: Any - ) -> None: # pylint: disable=arguments-differ - """Closes a completed job. - - :param str job_id: Id of the job. - - :param options: Request model for cancelling job. Is one of the following types: - CancelJobOptions, JSON, IO Default value is None. - :type options: ~azure.communication.jobrouter.models.CancelJobOptions or JSON or IO - - :return: None - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops.py - :start-after: [START cancel_job] - :end-before: [END cancel_job] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to cancel a job - """ - if not job_id: - raise ValueError("job_id cannot be None.") - - super()._cancel_job(job_id=job_id, options=options, **kwargs) - - @distributed_trace - def complete_job( - self, - job_id: str, - assignment_id: str, - options: Optional[Union[_models._models.CompleteJobOptions, JSON, IO]] = None, - **kwargs: Any - ) -> None: # pylint: disable=arguments-differ - """Completes an assigned job. - - :param str job_id: Id of the job. - - :param assignment_id: The Id of the job assignment. Required. - :type assignment_id: str - - :param options: Request model for completing job. Is one of the following types: - CompleteJobOptions, JSON, IO Default value is None. - :type options: ~azure.communication.jobrouter.models.CompleteJobOptions or JSON or IO - - :return: None - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops.py - :start-after: [START complete_job] - :end-before: [END complete_job] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to complete a job - """ - if not job_id: - raise ValueError("job_id cannot be None.") - - if not assignment_id: - raise ValueError("assignment_id cannot be None.") - - super()._complete_job(job_id=job_id, assignment_id=assignment_id, options=options, **kwargs) - - @distributed_trace - def close_job( - self, - job_id: str, - assignment_id: str, - options: Optional[Union[_models._models.CloseJobOptions, JSON, IO]] = None, - **kwargs: Any - ) -> None: # pylint: disable=arguments-differ - """Closes a completed job. - - :param str job_id: Id of the job. - - :param assignment_id: The Id of the job assignment. Required. - :type assignment_id: str - :param options: Request model for closing job. Is one of the following types: CloseJobOptions, - JSON, IO Default value is None. - :type options: ~azure.communication.jobrouter.models.CloseJobOptions or JSON or IO - - :return: None - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops.py - :start-after: [START close_job] - :end-before: [END close_job] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to close a job - """ - if not job_id: - raise ValueError("job_id cannot be None.") - - if not assignment_id: - raise ValueError("assignment_id cannot be None.") - - super()._close_job(job_id=job_id, assignment_id=assignment_id, options=options, **kwargs) - - # endregion Job - - # region Offer - @distributed_trace - def decline_job_offer( - self, - worker_id: str, - offer_id: str, - options: Optional[Union[_models._models.DeclineJobOfferOptions, JSON, IO]] = None, - **kwargs: Any - ) -> None: # pylint: disable=arguments-differ - """Declines an offer to work on a job. - - :param worker_id: Id of the worker. Required. - :type worker_id: str - :param offer_id: Id of the offer. Required. - :type offer_id: str - :param options: Request model for declining offer. Is one of the following types: - DeclineJobOfferOptions, JSON, IO Default value is None. - :type options: ~azure.communication.jobrouter.models.DeclineJobOfferOptions or JSON or IO - - :return: None - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops.py - :start-after: [START close_job] - :end-before: [END close_job] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to close a job - """ - if not worker_id: - raise ValueError("worker_id cannot be None.") - - if not offer_id: - raise ValueError("offer_id cannot be None.") - - super()._decline_job_offer(worker_id=worker_id, offer_id=offer_id, options=options, **kwargs) - - # endregion Offer - - -__all__: List[str] = [ - "JobRouterClientOperationsMixin", - "JobRouterAdministrationClientOperationsMixin", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_patch.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_patch.py index 9f503d53e0d6..8bcb627aa475 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_patch.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_patch.py @@ -1,161 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import ( - List, - Any, -) -from urllib.parse import urlparse -from azure.core.credentials import AzureKeyCredential -from ._shared.utils import parse_connection_str -from ._shared.policy import HMACCredentialsPolicy -from ._client import ( - JobRouterClient as JobRouterClientGenerated, - JobRouterAdministrationClient as JobRouterAdministrationClientGenerated, -) -from ._api_versions import DEFAULT_VERSION +from typing import List - -class JobRouterClient(JobRouterClientGenerated): - """A client to interact with the AzureCommunicationService JobRouter service. - - This client provides operations to create and update jobs, policies and workers. - - :param str endpoint: - The endpoint of the Azure Communication resource. - :param ~azure.core.credentials.AzureKeyCredential credential: - The credentials with which to authenticate - - :keyword api_version: Azure Communication Job Router API version. - Default value is "2023-11-01". - Note that overriding this default value may result in unsupported behavior. - """ - - def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None: - if not credential: - raise ValueError("credential can not be None") - - # TokenCredential not supported at the moment - if hasattr(credential, "get_token"): - raise TypeError( - "Unsupported credential: {}. Use an AzureKeyCredential to use HMACCredentialsPolicy" - " for authentication".format(type(credential)) - ) - - try: - if not endpoint.lower().startswith("http"): - endpoint = "https://" + endpoint - except AttributeError: - raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from - - parsed_url = urlparse(endpoint.rstrip("/")) - if not parsed_url.netloc: - raise ValueError("Invalid URL: {}".format(endpoint)) - - self._endpoint = endpoint - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._authentication_policy = HMACCredentialsPolicy(endpoint, credential.key) - super().__init__( - self._endpoint, authentication_policy=self._authentication_policy, api_version=self._api_version, **kwargs - ) - - @classmethod - def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "JobRouterClient": - """Create JobRouterClient from a Connection String. - - :param str conn_str: - A connection string to an Azure Communication Service resource. - :return: Instance of JobRouterClient. - :rtype: ~azure.communication.jobrouter.JobRouterClient - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_authentication.py - :start-after: [START auth_from_connection_string] - :end-before: [END auth_from_connection_string] - :language: python - :dedent: 8 - :caption: Authenticating a JobRouterClient from a connection_string - """ - endpoint, access_key = parse_connection_str(conn_str) - return cls(endpoint, AzureKeyCredential(access_key), **kwargs) - - -class JobRouterAdministrationClient(JobRouterAdministrationClientGenerated): - """A client to interact with the AzureCommunicationService JobRouter service. - - This client provides operations to create, update, list and delete the following entities: classification policy, - exception policy, distribution policy and queue. - - :param str endpoint: - The endpoint of the Azure Communication resource. - :param ~azure.core.credentials.AzureKeyCredential credential: - The credentials with which to authenticate - - :keyword api_version: Azure Communication Job Router API version. Default value is "2023-11-01". - Note that overriding this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> "None": - if not credential: - raise ValueError("credential can not be None") - - # TokenCredential not supported at the moment - if hasattr(credential, "get_token"): - raise TypeError( - "Unsupported credential: {}. Use an AzureKeyCredential to use HMACCredentialsPolicy" - " for authentication".format(type(credential)) - ) - - try: - if not endpoint.lower().startswith("http"): - endpoint = "https://" + endpoint - except AttributeError: - raise ValueError("Host URL must be a string") # pylint: disable=raise-missing-from - - parsed_url = urlparse(endpoint.rstrip("/")) - if not parsed_url.netloc: - raise ValueError("Invalid URL: {}".format(endpoint)) - - self._endpoint = endpoint - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._authentication_policy = HMACCredentialsPolicy(endpoint, credential.key) - super().__init__( - self._endpoint, authentication_policy=self._authentication_policy, api_version=self._api_version, **kwargs - ) - - @classmethod - def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "JobRouterAdministrationClient": - """Create JobRouterClient from a Connection String. - - :param str conn_str: - A connection string to an Azure Communication Service resource. - :return: Instance of JobRouterAdministrationClient. - :rtype: ~azure.communication.jobrouter.JobRouterAdministrationClient - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_authentication.py - :start-after: [START admin_auth_from_connection_string] - :end-before: [END admin_auth_from_connection_string] - :language: python - :dedent: 8 - :caption: Authenticating a JobRouterAdministrationClient from a connection_string - """ - endpoint, access_key = parse_connection_str(conn_str) - return cls(endpoint, AzureKeyCredential(access_key), **kwargs) - - -__all__: List[str] = [ - "JobRouterClient", - "JobRouterAdministrationClient", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/auth_policy_utils.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/auth_policy_utils.py deleted file mode 100644 index d0c4713176c2..000000000000 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/auth_policy_utils.py +++ /dev/null @@ -1,52 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- - -from typing import Union -from azure.core.credentials import TokenCredential, AzureKeyCredential -from azure.core.credentials_async import AsyncTokenCredential -from azure.core.pipeline.policies import ( - AsyncBearerTokenCredentialPolicy, - BearerTokenCredentialPolicy, -) -from .._shared.policy import HMACCredentialsPolicy - - -def get_authentication_policy( - endpoint: str, - credential: Union[TokenCredential, AsyncTokenCredential, AzureKeyCredential, str], - decode_url: bool = False, - is_async: bool = False, -) -> Union[AsyncBearerTokenCredentialPolicy, BearerTokenCredentialPolicy, HMACCredentialsPolicy]: - """Returns the correct authentication policy based on which credential is being passed. - - :param endpoint: The endpoint to which we are authenticating to. - :type endpoint: str - :param credential: The credential we use to authenticate to the service - :type credential: Union[TokenCredential, AsyncTokenCredential, AzureKeyCredential, str] - :param bool decode_url: `True` if there is a need to decode the url. Default value is `False` - :param bool is_async: For async clients there is a need to decode the url - - :return: Either AsyncBearerTokenCredentialPolicy or BearerTokenCredentialPolicy or HMACCredentialsPolicy - :rtype: ~azure.core.pipeline.policies.AsyncBearerTokenCredentialPolicy or - ~azure.core.pipeline.policies.BearerTokenCredentialPolicy or - ~azure.communication.jobrouter.shared.policy.HMACCredentialsPolicy - """ - - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - if hasattr(credential, "get_token"): - if is_async: - return AsyncBearerTokenCredentialPolicy( - credential, "https://communication.azure.com//.default" # type: ignore - ) - return BearerTokenCredentialPolicy(credential, "https://communication.azure.com//.default") # type: ignore - if isinstance(credential, (AzureKeyCredential, str)): - return HMACCredentialsPolicy(endpoint, credential, decode_url=decode_url) - - raise TypeError( - f"Unsupported credential: {format(type(credential))}. Use an access token string to use HMACCredentialsPolicy" - "or a token credential from azure.identity" - ) diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/models.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/models.py deleted file mode 100644 index 43875e1197e5..000000000000 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/models.py +++ /dev/null @@ -1,417 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -from enum import Enum -import warnings -from typing import Mapping, Optional, Union, Any, cast -from typing_extensions import Literal, TypedDict, Protocol, runtime_checkable - -from azure.core import CaseInsensitiveEnumMeta - - -class DeprecatedEnumMeta(CaseInsensitiveEnumMeta): - - def __getattribute__(cls, item): - if item.upper() == "MICROSOFT_BOT": - warnings.warn( - "MICROSOFT_BOT is deprecated and has been replaced by \ - MICROSOFT_TEAMS_APP identifier.", - DeprecationWarning, - ) - item = "MICROSOFT_TEAMS_APP" - return super().__getattribute__(item) - - -class CommunicationIdentifierKind(str, Enum, metaclass=DeprecatedEnumMeta): - """Communication Identifier Kind. - - For checking yet unknown identifiers it is better to rely on the presence of the `raw_id` property, - as new or existing distinct type identifiers always contain the `raw_id` property. - It is not advisable to rely on the `kind` property with a value `unknown`, - as it could become a new or existing distinct type in the future. - """ - - UNKNOWN = "unknown" - COMMUNICATION_USER = "communication_user" - PHONE_NUMBER = "phone_number" - MICROSOFT_TEAMS_USER = "microsoft_teams_user" - MICROSOFT_TEAMS_APP = "microsoft_teams_app" - - -class CommunicationCloudEnvironment(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """The cloud environment that the identifier belongs to""" - - PUBLIC = "PUBLIC" - DOD = "DOD" - GCCH = "GCCH" - - -@runtime_checkable -class CommunicationIdentifier(Protocol): - """Communication Identifier.""" - - @property - def raw_id(self) -> str: - """The raw ID of the identifier.""" - ... - - @property - def kind(self) -> CommunicationIdentifierKind: - """The type of identifier.""" - ... - - @property - def properties(self) -> Mapping[str, Any]: - """The properties of the identifier.""" - ... - - -PHONE_NUMBER_PREFIX = "4:" -BOT_PREFIX = "28:" -BOT_PUBLIC_CLOUD_PREFIX = "28:orgid:" -BOT_DOD_CLOUD_PREFIX = "28:dod:" -BOT_DOD_CLOUD_GLOBAL_PREFIX = "28:dod-global:" -BOT_GCCH_CLOUD_PREFIX = "28:gcch:" -BOT_GCCH_CLOUD_GLOBAL_PREFIX = "28:gcch-global:" -TEAMS_APP_PUBLIC_CLOUD_PREFIX = "28:orgid:" -TEAMS_APP_DOD_CLOUD_PREFIX = "28:dod:" -TEAMS_APP_GCCH_CLOUD_PREFIX = "28:gcch:" -TEAMS_USER_ANONYMOUS_PREFIX = "8:teamsvisitor:" -TEAMS_USER_PUBLIC_CLOUD_PREFIX = "8:orgid:" -TEAMS_USER_DOD_CLOUD_PREFIX = "8:dod:" -TEAMS_USER_GCCH_CLOUD_PREFIX = "8:gcch:" -ACS_USER_PREFIX = "8:acs:" -ACS_USER_DOD_CLOUD_PREFIX = "8:dod-acs:" -ACS_USER_GCCH_CLOUD_PREFIX = "8:gcch-acs:" -SPOOL_USER_PREFIX = "8:spool:" - - -class CommunicationUserProperties(TypedDict): - """Dictionary of properties for a CommunicationUserIdentifier.""" - - id: str - """ID of the Communication user as returned from Azure Communication Identity.""" - - -class CommunicationUserIdentifier: - """Represents a user in Azure Communication Service.""" - - kind: Literal[CommunicationIdentifierKind.COMMUNICATION_USER] = CommunicationIdentifierKind.COMMUNICATION_USER - """The type of identifier.""" - properties: CommunicationUserProperties - """The properties of the identifier.""" - raw_id: str - """The raw ID of the identifier.""" - - def __init__(self, id: str, **kwargs: Any) -> None: - """ - :param str id: ID of the Communication user as returned from Azure Communication Identity. - :keyword str raw_id: The raw ID of the identifier. If not specified, the 'id' value will be used. - """ - self.properties = CommunicationUserProperties(id=id) - raw_id: Optional[str] = kwargs.get("raw_id") - self.raw_id = raw_id if raw_id is not None else id - - def __eq__(self, other): - try: - if other.raw_id: - return self.raw_id == other.raw_id - return self.raw_id == other.properties["id"] - except Exception: # pylint: disable=broad-except - return False - - -class PhoneNumberProperties(TypedDict): - """Dictionary of properties for a PhoneNumberIdentifier.""" - - value: str - """The phone number in E.164 format.""" - - -class PhoneNumberIdentifier: - """Represents a phone number.""" - - kind: Literal[CommunicationIdentifierKind.PHONE_NUMBER] = CommunicationIdentifierKind.PHONE_NUMBER - """The type of identifier.""" - properties: PhoneNumberProperties - """The properties of the identifier.""" - raw_id: str - """The raw ID of the identifier.""" - - def __init__(self, value: str, **kwargs: Any) -> None: - """ - :param str value: The phone number. - :keyword str raw_id: The raw ID of the identifier. If not specified, this will be constructed from - the 'value' parameter. - """ - self.properties = PhoneNumberProperties(value=value) - raw_id: Optional[str] = kwargs.get("raw_id") - self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties) - - def __eq__(self, other): - try: - if other.raw_id: - return self.raw_id == other.raw_id - return self.raw_id == self._format_raw_id(other.properties) - except Exception: # pylint:disable=broad-except - return False - - def _format_raw_id(self, properties: PhoneNumberProperties) -> str: - # We just assume correct E.164 format here because - # validation should only happen server-side, not client-side. - value = properties["value"] - return f"{PHONE_NUMBER_PREFIX}{value}" - - -class UnknownIdentifier: - """Represents an identifier of an unknown type. - - It will be encountered in communications with endpoints that are not - identifiable by this version of the SDK. - - For checking yet unknown identifiers it is better to rely on the presence of the `raw_id` property, - as new or existing distinct type identifiers always contain the `raw_id` property. - It is not advisable to rely on the `kind` property with a value `unknown`, - as it could become a new or existing distinct type in the future. - """ - - kind: Literal[CommunicationIdentifierKind.UNKNOWN] = CommunicationIdentifierKind.UNKNOWN - """The type of identifier.""" - properties: Mapping[str, Any] - """The properties of the identifier.""" - raw_id: str - """The raw ID of the identifier.""" - - def __init__(self, identifier: str) -> None: - """ - :param str identifier: The ID of the identifier. - """ - self.raw_id = identifier - self.properties = {} - - def __eq__(self, other): - try: - return self.raw_id == other.raw_id - except AttributeError: - return False - - -class MicrosoftTeamsUserProperties(TypedDict): - """Dictionary of properties for a MicrosoftTeamsUserIdentifier.""" - - user_id: str - """The id of the Microsoft Teams user. If the user isn't anonymous, the id is the AAD object id of the user.""" - is_anonymous: bool - """Set this to true if the user is anonymous for example when joining a meeting with a share link.""" - cloud: Union[CommunicationCloudEnvironment, str] - """Cloud environment that this identifier belongs to.""" - - -class MicrosoftTeamsUserIdentifier: - """Represents an identifier for a Microsoft Teams user.""" - - kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_USER] = CommunicationIdentifierKind.MICROSOFT_TEAMS_USER - """The type of identifier.""" - properties: MicrosoftTeamsUserProperties - """The properties of the identifier.""" - raw_id: str - """The raw ID of the identifier.""" - - def __init__(self, user_id: str, **kwargs: Any) -> None: - """ - :param str user_id: Microsoft Teams user id. - :keyword bool is_anonymous: `True` if the identifier is anonymous. Default value is `False`. - :keyword cloud: Cloud environment that the user belongs to. Default value is `PUBLIC`. - :paramtype cloud: str or ~azure.communication.chat.CommunicationCloudEnvironment - :keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed from - the other properties. - """ - self.properties = MicrosoftTeamsUserProperties( - user_id=user_id, - is_anonymous=kwargs.get("is_anonymous", False), - cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, - ) - raw_id: Optional[str] = kwargs.get("raw_id") - self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties) - - def __eq__(self, other): - try: - if other.raw_id: - return self.raw_id == other.raw_id - return self.raw_id == self._format_raw_id(other.properties) - except Exception: # pylint: disable=broad-except - return False - - def _format_raw_id(self, properties: MicrosoftTeamsUserProperties) -> str: - user_id = properties["user_id"] - if properties["is_anonymous"]: - return f"{TEAMS_USER_ANONYMOUS_PREFIX}{user_id}" - cloud = properties["cloud"] - if cloud == CommunicationCloudEnvironment.DOD: - return f"{TEAMS_USER_DOD_CLOUD_PREFIX}{user_id}" - if cloud == CommunicationCloudEnvironment.GCCH: - return f"{TEAMS_USER_GCCH_CLOUD_PREFIX}{user_id}" - if cloud == CommunicationCloudEnvironment.PUBLIC: - return f"{TEAMS_USER_PUBLIC_CLOUD_PREFIX}{user_id}" - return f"{TEAMS_USER_PUBLIC_CLOUD_PREFIX}{user_id}" - - -class MicrosoftTeamsAppProperties(TypedDict): - """Dictionary of properties for a MicrosoftTeamsAppIdentifier.""" - - app_id: str - """The id of the Microsoft Teams application.""" - cloud: Union[CommunicationCloudEnvironment, str] - """Cloud environment that this identifier belongs to.""" - - -class _botbackcompatdict(dict): - """Backwards compatible properties.""" - - def __getitem__(self, __key: Any) -> Any: - try: - return super().__getitem__(__key) - except KeyError: - if __key == "bot_id": - return super().__getitem__("app_id") - if __key == "is_resource_account_configured": - return True - raise - - -class MicrosoftTeamsAppIdentifier: - """Represents an identifier for a Microsoft Teams application.""" - - kind: Literal[CommunicationIdentifierKind.MICROSOFT_TEAMS_APP] = CommunicationIdentifierKind.MICROSOFT_TEAMS_APP - """The type of identifier.""" - properties: MicrosoftTeamsAppProperties - """The properties of the identifier.""" - raw_id: str - """The raw ID of the identifier.""" - - def __init__(self, app_id: str, **kwargs: Any) -> None: - """ - :param str app_id: Microsoft Teams application id. - :keyword cloud: Cloud environment that the application belongs to. Default value is `PUBLIC`. - :paramtype cloud: str or ~azure.communication.chat.CommunicationCloudEnvironment - :keyword str raw_id: The raw ID of the identifier. If not specified, this value will be constructed - from the other properties. - """ - self.properties = cast( - MicrosoftTeamsAppProperties, - _botbackcompatdict( - app_id=app_id, - cloud=kwargs.get("cloud") or CommunicationCloudEnvironment.PUBLIC, - ), - ) - raw_id: Optional[str] = kwargs.get("raw_id") - self.raw_id = raw_id if raw_id is not None else self._format_raw_id(self.properties) - - def __eq__(self, other): - try: - if other.raw_id: - return self.raw_id == other.raw_id - return self.raw_id == self._format_raw_id(other.properties) - except Exception: # pylint: disable=broad-except - return False - - def _format_raw_id(self, properties: MicrosoftTeamsAppProperties) -> str: - app_id = properties["app_id"] - cloud = properties["cloud"] - if cloud == CommunicationCloudEnvironment.DOD: - return f"{TEAMS_APP_DOD_CLOUD_PREFIX}{app_id}" - if cloud == CommunicationCloudEnvironment.GCCH: - return f"{TEAMS_APP_GCCH_CLOUD_PREFIX}{app_id}" - return f"{TEAMS_APP_PUBLIC_CLOUD_PREFIX}{app_id}" - - -class _MicrosoftBotIdentifier(MicrosoftTeamsAppIdentifier): - """Represents an identifier for a Microsoft bot. - - DEPRECATED. Only used in cases of backwards compatibility. - """ - - def __init__(self, bot_id, **kwargs): - """ - :param str bot_id: Microsoft bot id. - :keyword bool is_resource_account_configured: `False` if the identifier is global. - Default value is `True` for tennantzed bots. - :keyword cloud: Cloud environment that the bot belongs to. Default value is `PUBLIC`. - :paramtype cloud: str or ~azure.communication.chat.CommunicationCloudEnvironment - """ - warnings.warn( - "The MicrosoftBotIdentifier is deprecated and has been replaced by MicrosoftTeamsAppIdentifier.", - DeprecationWarning, - ) - super().__init__(bot_id, **kwargs) - - -def identifier_from_raw_id(raw_id: str) -> CommunicationIdentifier: # pylint: disable=too-many-return-statements - """ - Creates a CommunicationIdentifier from a given raw ID. - - When storing raw IDs use this function to restore the identifier that was encoded in the raw ID. - - :param str raw_id: A raw ID to construct the CommunicationIdentifier from. - :return: The CommunicationIdentifier parsed from the raw_id. - :rtype: CommunicationIdentifier - """ - if raw_id.startswith(PHONE_NUMBER_PREFIX): - return PhoneNumberIdentifier(value=raw_id[len(PHONE_NUMBER_PREFIX) :], raw_id=raw_id) - - segments = raw_id.split(":", maxsplit=2) - if len(segments) < 3: - return UnknownIdentifier(identifier=raw_id) - - prefix = f"{segments[0]}:{segments[1]}:" - suffix = segments[2] - if prefix == TEAMS_USER_ANONYMOUS_PREFIX: - return MicrosoftTeamsUserIdentifier(user_id=suffix, is_anonymous=True, raw_id=raw_id) - if prefix == TEAMS_USER_PUBLIC_CLOUD_PREFIX: - return MicrosoftTeamsUserIdentifier( - user_id=suffix, - is_anonymous=False, - cloud=CommunicationCloudEnvironment.PUBLIC, - raw_id=raw_id, - ) - if prefix == TEAMS_USER_DOD_CLOUD_PREFIX: - return MicrosoftTeamsUserIdentifier( - user_id=suffix, - is_anonymous=False, - cloud=CommunicationCloudEnvironment.DOD, - raw_id=raw_id, - ) - if prefix == TEAMS_USER_GCCH_CLOUD_PREFIX: - return MicrosoftTeamsUserIdentifier( - user_id=suffix, - is_anonymous=False, - cloud=CommunicationCloudEnvironment.GCCH, - raw_id=raw_id, - ) - if prefix == TEAMS_APP_PUBLIC_CLOUD_PREFIX: - return MicrosoftTeamsAppIdentifier( - app_id=suffix, - cloud=CommunicationCloudEnvironment.PUBLIC, - raw_id=raw_id, - ) - if prefix == TEAMS_APP_DOD_CLOUD_PREFIX: - return MicrosoftTeamsAppIdentifier( - app_id=suffix, - cloud=CommunicationCloudEnvironment.DOD, - raw_id=raw_id, - ) - if prefix == TEAMS_APP_GCCH_CLOUD_PREFIX: - return MicrosoftTeamsAppIdentifier( - app_id=suffix, - cloud=CommunicationCloudEnvironment.GCCH, - raw_id=raw_id, - ) - if prefix in [ - ACS_USER_PREFIX, - ACS_USER_DOD_CLOUD_PREFIX, - ACS_USER_GCCH_CLOUD_PREFIX, - SPOOL_USER_PREFIX, - ]: - return CommunicationUserIdentifier(id=raw_id, raw_id=raw_id) - return UnknownIdentifier(identifier=raw_id) diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/policy.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/policy.py deleted file mode 100644 index 1843d22e83a2..000000000000 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/policy.py +++ /dev/null @@ -1,120 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- - -import hashlib -import urllib -import base64 -import hmac -from urllib.parse import ParseResult, urlparse -from typing import Union -from azure.core.credentials import AzureKeyCredential -from azure.core.pipeline.policies import SansIOHTTPPolicy -from .utils import get_current_utc_time - - -class HMACCredentialsPolicy(SansIOHTTPPolicy): - """Implementation of HMAC authentication policy. - - :param str host: The host of the endpoint url for Azure Communication Service resource - :param access_key: The access key we use to authenticate to the service - :type access_key: str or AzureKeyCredential - :param bool decode_url: `True` if there is a need to decode the url. Default value is `False` - """ - - def __init__( - self, - host: str, - access_key: Union[str, AzureKeyCredential], - decode_url: bool = False, - ) -> None: - super(HMACCredentialsPolicy, self).__init__() - - if host.startswith("https://"): - self._host = host.replace("https://", "") - - if host.startswith("http://"): - self._host = host.replace("http://", "") - - self._access_key = access_key - self._decode_url = decode_url - - def _compute_hmac( - self, value # type: str - ): - if isinstance(self._access_key, AzureKeyCredential): - decoded_secret = base64.b64decode(self._access_key.key) - else: - decoded_secret = base64.b64decode(self._access_key) - - digest = hmac.new(decoded_secret, value.encode("utf-8"), hashlib.sha256).digest() - - return base64.b64encode(digest).decode("utf-8") - - def _sign_request(self, request): - verb = request.http_request.method.upper() - - # Get the path and query from url, which looks like https://host/path/query - parsed_url: ParseResult = urlparse(request.http_request.url) - query_url = parsed_url.path - - if parsed_url.query: - query_url += "?" + parsed_url.query - - # Need URL() to get a correct encoded key value, from "%3A" to ":", when transport is in type AioHttpTransport. - # There's a similar scenario in azure-storage-blob and azure-appconfiguration, the check logic is from there. - try: - from yarl import URL - from azure.core.pipeline.transport import ( # pylint:disable=non-abstract-transport-import - AioHttpTransport, - ) - - if ( - isinstance(request.context.transport, AioHttpTransport) - or isinstance( - getattr(request.context.transport, "_transport", None), - AioHttpTransport, - ) - or isinstance( - getattr( - getattr(request.context.transport, "_transport", None), - "_transport", - None, - ), - AioHttpTransport, - ) - ): - query_url = str(URL(query_url)) - except (ImportError, TypeError): - pass - - if self._decode_url: - query_url = urllib.parse.unquote(query_url) - - signed_headers = "x-ms-date;host;x-ms-content-sha256" - - utc_now = get_current_utc_time() - if request.http_request.body is None: - request.http_request.body = "" - content_digest = hashlib.sha256((request.http_request.body.encode("utf-8"))).digest() - content_hash = base64.b64encode(content_digest).decode("utf-8") - - string_to_sign = verb + "\n" + query_url + "\n" + utc_now + ";" + self._host + ";" + content_hash - - signature = self._compute_hmac(string_to_sign) - - signature_header = { - "x-ms-date": utc_now, - "x-ms-content-sha256": content_hash, - "x-ms-return-client-request-id": "true", - "Authorization": "HMAC-SHA256 SignedHeaders=" + signed_headers + "&Signature=" + signature, - } - - request.http_request.headers.update(signature_header) - - return request - - def on_request(self, request): - self._sign_request(request) diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential.py deleted file mode 100644 index 54603e7b32ce..000000000000 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential.py +++ /dev/null @@ -1,143 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- - -from threading import Lock, Condition, Timer, TIMEOUT_MAX, Event -from datetime import timedelta -from typing import Any - -from .utils import get_current_utc_as_int -from .utils import create_access_token - - -class CommunicationTokenCredential(object): - """Credential type used for authenticating to an Azure Communication service. - :param str token: The token used to authenticate to an Azure Communication service. - :keyword token_refresher: The sync token refresher to provide capacity to fetch a fresh token. - The returned token must be valid (expiration date must be in the future). - :paramtype token_refresher: Callable[[], AccessToken] - :keyword bool proactive_refresh: Whether to refresh the token proactively or not. - If the proactive refreshing is enabled ('proactive_refresh' is true), the credential will use - a background thread to attempt to refresh the token within 10 minutes before the cached token expires, - the proactive refresh will request a new token by calling the 'token_refresher' callback. - When 'proactive_refresh' is enabled, the Credential object must be either run within a context manager - or the 'close' method must be called once the object usage has been finished. - :raises: TypeError if paramater 'token' is not a string - :raises: ValueError if the 'proactive_refresh' is enabled without providing the 'token_refresher' callable. - """ - - _ON_DEMAND_REFRESHING_INTERVAL_MINUTES = 2 - _DEFAULT_AUTOREFRESH_INTERVAL_MINUTES = 10 - - def __init__(self, token: str, **kwargs: Any): - if not isinstance(token, str): - raise TypeError("Token must be a string.") - self._token = create_access_token(token) - self._token_refresher = kwargs.pop("token_refresher", None) - self._proactive_refresh = kwargs.pop("proactive_refresh", False) - if self._proactive_refresh and self._token_refresher is None: - raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") - self._timer = None - self._lock = Condition(Lock()) - self._some_thread_refreshing = False - self._is_closed = Event() - - def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument - # type (*str, **Any) -> AccessToken - """The value of the configured token. - :param any scopes: Scopes to be added to the token. - :return: AccessToken - :rtype: ~azure.core.credentials.AccessToken - """ - if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") - - if not self._token_refresher or not self._is_token_expiring_soon(self._token): - return self._token - self._update_token_and_reschedule() - return self._token - - def _update_token_and_reschedule(self): - should_this_thread_refresh = False - with self._lock: - while self._is_token_expiring_soon(self._token): - if self._some_thread_refreshing: - if self._is_token_valid(self._token): - return self._token - self._wait_till_lock_owner_finishes_refreshing() - else: - should_this_thread_refresh = True - self._some_thread_refreshing = True - break - - if should_this_thread_refresh: - try: - new_token = self._token_refresher() - if not self._is_token_valid(new_token): - raise ValueError("The token returned from the token_refresher is expired.") - with self._lock: - self._token = new_token - self._some_thread_refreshing = False - self._lock.notify_all() - except: - with self._lock: - self._some_thread_refreshing = False - self._lock.notify_all() - raise - if self._proactive_refresh: - self._schedule_refresh() - return self._token - - def _schedule_refresh(self): - if self._is_closed.is_set(): - return - if self._timer is not None: - self._timer.cancel() - - token_ttl = self._token.expires_on - get_current_utc_as_int() - - if self._is_token_expiring_soon(self._token): - # Schedule the next refresh for when it reaches a certain percentage of the remaining lifetime. - timespan = token_ttl // 2 - else: - # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() - if timespan <= TIMEOUT_MAX: - self._timer = Timer(timespan, self._update_token_and_reschedule) - self._timer.daemon = True - self._timer.start() - - def _wait_till_lock_owner_finishes_refreshing(self): - self._lock.release() - self._lock.acquire() - - def _is_token_expiring_soon(self, token): - if self._proactive_refresh: - interval = timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES) - else: - interval = timedelta(minutes=self._ON_DEMAND_REFRESHING_INTERVAL_MINUTES) - return (token.expires_on - get_current_utc_as_int()) < interval.total_seconds() - - @classmethod - def _is_token_valid(cls, token): - return get_current_utc_as_int() < token.expires_on - - def __enter__(self): - if self._proactive_refresh: - if self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) - self._schedule_refresh() - return self - - def __exit__(self, *args): - self.close() - - def close(self) -> None: - if self._timer is not None: - self._timer.cancel() - self._timer = None - self._is_closed.set() diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential_async.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential_async.py deleted file mode 100644 index c55896c5b6bb..000000000000 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/user_credential_async.py +++ /dev/null @@ -1,148 +0,0 @@ -# ------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# -------------------------------------------------------------------------- -# pylint: disable=C4763 -from asyncio import Condition, Lock, Event -from datetime import timedelta -from typing import Any -import sys - -from .utils import get_current_utc_as_int -from .utils import create_access_token -from .utils_async import AsyncTimer - - -class CommunicationTokenCredential(object): - """Credential type used for authenticating to an Azure Communication service. - :param str token: The token used to authenticate to an Azure Communication service. - :keyword token_refresher: The async token refresher to provide capacity to fetch a fresh token. - The returned token must be valid (expiration date must be in the future). - :paramtype token_refresher: Callable[[], Awaitable[AccessToken]] - :keyword bool proactive_refresh: Whether to refresh the token proactively or not. - If the proactive refreshing is enabled ('proactive_refresh' is true), the credential will use - a background thread to attempt to refresh the token within 10 minutes before the cached token expires, - the proactive refresh will request a new token by calling the 'token_refresher' callback. - When 'proactive_refresh is enabled', the Credential object must be either run within a context manager - or the 'close' method must be called once the object usage has been finished. - :raises: TypeError if paramater 'token' is not a string - :raises: ValueError if the 'proactive_refresh' is enabled without providing the 'token_refresher' function. - """ - - _ON_DEMAND_REFRESHING_INTERVAL_MINUTES = 2 - _DEFAULT_AUTOREFRESH_INTERVAL_MINUTES = 10 - - def __init__(self, token: str, **kwargs: Any): - if not isinstance(token, str): - raise TypeError("Token must be a string.") - self._token = create_access_token(token) - self._token_refresher = kwargs.pop("token_refresher", None) - self._proactive_refresh = kwargs.pop("proactive_refresh", False) - if self._proactive_refresh and self._token_refresher is None: - raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") - self._timer = None - self._async_mutex = Lock() - if sys.version_info[:3] == (3, 10, 0): - # Workaround for Python 3.10 bug(https://bugs.python.org/issue45416): - getattr(self._async_mutex, "_get_loop", lambda: None)() - self._lock = Condition(self._async_mutex) - self._some_thread_refreshing = False - self._is_closed = Event() - - async def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument - # type (*str, **Any) -> AccessToken - """The value of the configured token. - :param any scopes: Scopes to be added to the token. - :return: AccessToken - :rtype: ~azure.core.credentials.AccessToken - """ - if self._proactive_refresh and self._is_closed.is_set(): - raise RuntimeError("An instance of CommunicationTokenCredential cannot be reused once it has been closed.") - - if not self._token_refresher or not self._is_token_expiring_soon(self._token): - return self._token - await self._update_token_and_reschedule() - return self._token - - async def _update_token_and_reschedule(self): - should_this_thread_refresh = False - async with self._lock: - while self._is_token_expiring_soon(self._token): - if self._some_thread_refreshing: - if self._is_token_valid(self._token): - return self._token - await self._wait_till_lock_owner_finishes_refreshing() - else: - should_this_thread_refresh = True - self._some_thread_refreshing = True - break - - if should_this_thread_refresh: - try: - new_token = await self._token_refresher() - if not self._is_token_valid(new_token): - raise ValueError("The token returned from the token_refresher is expired.") - async with self._lock: - self._token = new_token - self._some_thread_refreshing = False - self._lock.notify_all() - except: - async with self._lock: - self._some_thread_refreshing = False - self._lock.notify_all() - raise - if self._proactive_refresh: - self._schedule_refresh() - return self._token - - def _schedule_refresh(self): - if self._is_closed.is_set(): - return - if self._timer is not None: - self._timer.cancel() - - token_ttl = self._token.expires_on - get_current_utc_as_int() - - if self._is_token_expiring_soon(self._token): - # Schedule the next refresh for when it reaches a certain percentage of the remaining lifetime. - timespan = token_ttl // 2 - else: - # Schedule the next refresh for when it gets in to the soon-to-expire window. - timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() - - self._timer = AsyncTimer(timespan, self._update_token_and_reschedule) - self._timer.start() - - async def _wait_till_lock_owner_finishes_refreshing(self): - self._lock.release() - await self._lock.acquire() - - def _is_token_expiring_soon(self, token): - if self._proactive_refresh: - interval = timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES) - else: - interval = timedelta(minutes=self._ON_DEMAND_REFRESHING_INTERVAL_MINUTES) - return (token.expires_on - get_current_utc_as_int()) < interval.total_seconds() - - @classmethod - def _is_token_valid(cls, token): - return get_current_utc_as_int() < token.expires_on - - async def __aenter__(self): - if self._proactive_refresh: - if self._is_closed.is_set(): - raise RuntimeError( - "An instance of CommunicationTokenCredential cannot be reused once it has been closed." - ) - self._schedule_refresh() - return self - - async def __aexit__(self, *args): - await self.close() - - async def close(self) -> None: - if self._timer is not None: - self._timer.cancel() - self._timer = None - self._is_closed.set() diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils.py deleted file mode 100644 index 38a62a49dc3f..000000000000 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils.py +++ /dev/null @@ -1,89 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- - -import base64 -import json -import calendar -from typing import cast, Tuple, Optional -from datetime import datetime -from azure.core.serialization import TZ_UTC -from azure.core.credentials import AccessToken - - -def _convert_datetime_to_utc_int(input_datetime) -> int: - """ - Converts DateTime in local time to the Epoch in UTC in second. - - :param input_datetime: Input datetime - :type input_datetime: datetime - :return: Integer - :rtype: int - """ - return int(calendar.timegm(input_datetime.utctimetuple())) - - -def parse_connection_str(conn_str: Optional[str]) -> Tuple[str, str]: - if conn_str is None: - raise ValueError("Connection string is undefined.") - endpoint = None - shared_access_key = None - for element in conn_str.split(";"): - key, _, value = element.partition("=") - if key.lower() == "endpoint": - endpoint = value.rstrip("/") - elif key.lower() == "accesskey": - shared_access_key = value - if not all([endpoint, shared_access_key]): - raise ValueError( - "Invalid connection string. You can get the connection string from your resource page in the Azure Portal. " - "The format should be as follows: endpoint=https:///;accesskey=" - ) - left_slash_pos = cast(str, endpoint).find("//") - if left_slash_pos != -1: - host = cast(str, endpoint)[left_slash_pos + 2 :] - else: - host = str(endpoint) - - return host, str(shared_access_key) - - -def get_current_utc_time() -> str: - return str(datetime.now(tz=TZ_UTC).strftime("%a, %d %b %Y %H:%M:%S ")) + "GMT" - - -def get_current_utc_as_int() -> int: - current_utc_datetime = datetime.utcnow() - return _convert_datetime_to_utc_int(current_utc_datetime) - - -def create_access_token(token) -> AccessToken: - """Creates an instance of azure.core.credentials.AccessToken from a - string token. The input string is jwt token in the following form: - .. - This method looks into the token_payload which is a json and extracts the expiry time - for that token and creates a tuple of type azure.core.credentials.AccessToken - (, ) - :param token: User token - :type token: str - :return: Instance of azure.core.credentials.AccessToken - token and expiry date of it - :rtype: ~azure.core.credentials.AccessToken - """ - - token_parse_err_msg = "Token is not formatted correctly" - parts = token.split(".") - - if len(parts) < 3: - raise ValueError(token_parse_err_msg) - - try: - padded_base64_payload = base64.b64decode(parts[1] + "==").decode("ascii") - payload = json.loads(padded_base64_payload) - return AccessToken( - token, - _convert_datetime_to_utc_int(datetime.fromtimestamp(payload["exp"], TZ_UTC)), - ) - except ValueError as val_error: - raise ValueError(token_parse_err_msg) from val_error diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils_async.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils_async.py deleted file mode 100644 index 7402d088a880..000000000000 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/utils_async.py +++ /dev/null @@ -1,30 +0,0 @@ -# ------------------------------------------------------------------------ -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. -# ------------------------------------------------------------------------- -# pylint: disable=C4763 -from asyncio import sleep, ensure_future - -class AsyncTimer: - """A non-blocking timer, that calls a function after a specified number of seconds: - :param int interval: time interval in seconds - :param callable callback: function to be called after the interval has elapsed - """ - - def __init__(self, interval, callback): - self._interval = interval - self._callback = callback - self._task = None - - def start(self): - self._task = ensure_future(self._job()) - - async def _job(self): - await sleep(self._interval) - await self._callback() - - def cancel(self): - if self._task is not None: - self._task.cancel() - self._task = None diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/__init__.py similarity index 58% rename from sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/__init__.py rename to sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/__init__.py index 5b396cd202e8..8026245c2abc 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_shared/__init__.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/__init__.py @@ -1,5 +1,6 @@ -# ------------------------------------------------------------------------- +# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_model_base.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/model_base.py similarity index 57% rename from sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_model_base.py rename to sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/model_base.py index d951cecef5ac..49d5c7259389 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_model_base.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/model_base.py @@ -1,11 +1,14 @@ +# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for -# license information. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# pylint: disable=protected-access, arguments-differ, signature-differs, broad-except +# pylint: disable=protected-access, broad-except +import copy import calendar import decimal import functools @@ -13,12 +16,13 @@ import logging import base64 import re -import copy import typing import enum import email.utils from datetime import datetime, date, time, timedelta, timezone from json import JSONEncoder +import xml.etree.ElementTree as ET +from collections.abc import MutableMapping from typing_extensions import Self import isodate from azure.core.exceptions import DeserializationError @@ -26,11 +30,6 @@ from azure.core.pipeline import PipelineResponse from azure.core.serialization import _Null -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping - _LOGGER = logging.getLogger(__name__) __all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] @@ -123,7 +122,7 @@ def _serialize_datetime(o, format: typing.Optional[str] = None): def _is_readonly(p): try: - return p._visibility == ["read"] # pylint: disable=protected-access + return p._visibility == ["read"] except AttributeError: return False @@ -286,6 +285,12 @@ def _deserialize_decimal(attr): return decimal.Decimal(str(attr)) +def _deserialize_int_as_str(attr): + if isinstance(attr, int): + return attr + return int(attr) + + _DESERIALIZE_MAPPING = { datetime: _deserialize_datetime, date: _deserialize_date, @@ -307,9 +312,11 @@ def _deserialize_decimal(attr): def get_deserializer(annotation: typing.Any, rf: typing.Optional["_RestField"] = None): + if annotation is int and rf and rf._format == "str": + return _deserialize_int_as_str if rf and rf._format: return _DESERIALIZE_MAPPING_WITHFORMAT.get(rf._format) - return _DESERIALIZE_MAPPING.get(annotation) + return _DESERIALIZE_MAPPING.get(annotation) # pyright: ignore def _get_type_alias_type(module_name: str, alias_name: str): @@ -337,9 +344,9 @@ def _get_model(module_name: str, model_name: str): _UNSET = object() -class _MyMutableMapping(MutableMapping[str, typing.Any]): # pylint: disable=unsubscriptable-object +class _MyMutableMapping(MutableMapping[str, typing.Any]): def __init__(self, data: typing.Dict[str, typing.Any]) -> None: - self._data = copy.deepcopy(data) + self._data = data def __contains__(self, key: typing.Any) -> bool: return key in self._data @@ -363,50 +370,97 @@ def __ne__(self, other: typing.Any) -> bool: return not self.__eq__(other) def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ return self._data.items() def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ try: return self[key] except KeyError: return default @typing.overload - def pop(self, key: str) -> typing.Any: ... + def pop(self, key: str) -> typing.Any: ... # pylint: disable=arguments-differ @typing.overload - def pop(self, key: str, default: _T) -> _T: ... + def pop(self, key: str, default: _T) -> _T: ... # pylint: disable=signature-differs @typing.overload - def pop(self, key: str, default: typing.Any) -> typing.Any: ... + def pop(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ if default is _UNSET: return self._data.pop(key) return self._data.pop(key, default) def popitem(self) -> typing.Tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ return self._data.popitem() def clear(self) -> None: + """ + Remove all items from D. + """ self._data.clear() - def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: + def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: # pylint: disable=arguments-differ + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ self._data.update(*args, **kwargs) @typing.overload def setdefault(self, key: str, default: None = None) -> None: ... @typing.overload - def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... + def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... # pylint: disable=signature-differs def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ if default is _UNSET: return self._data.setdefault(key) return self._data.setdefault(key, default) @@ -441,6 +495,10 @@ def _serialize(o, format: typing.Optional[str] = None): # pylint: disable=too-m return float(o) if isinstance(o, enum.Enum): return o.value + if isinstance(o, int): + if format == "str": + return str(o) + return o try: # First try datetime.datetime return _serialize_datetime(o, format) @@ -471,11 +529,16 @@ def _create_value(rf: typing.Optional["_RestField"], value: typing.Any) -> typin return value if rf._is_model: return _deserialize(rf._type, value) + if isinstance(value, ET.Element): + value = _deserialize(rf._type, value) return _serialize(value, rf._format) class Model(_MyMutableMapping): _is_model = True + # label whether current class's _attr_to_rest_field has been calculated + # could not see _attr_to_rest_field directly because subclass inherits it from parent class + _calculated: typing.Set[str] = set() def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: class_name = self.__class__.__name__ @@ -486,10 +549,58 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: for rest_field in self._attr_to_rest_field.values() if rest_field._default is not _UNSET } - if args: - dict_to_pass.update( - {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} - ) + if args: # pylint: disable=too-many-nested-blocks + if isinstance(args[0], ET.Element): + existed_attr_keys = [] + model_meta = getattr(self, "_xml", {}) + + for rf in self._attr_to_rest_field.values(): + prop_meta = getattr(rf, "_xml", {}) + xml_name = prop_meta.get("name", rf._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + # attribute + if prop_meta.get("attribute", False) and args[0].get(xml_name) is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].get(xml_name)) + continue + + # unwrapped element is array + if prop_meta.get("unwrapped", False): + # unwrapped array could either use prop items meta/prop meta + if prop_meta.get("itemsName"): + xml_name = prop_meta.get("itemsName") + xml_ns = prop_meta.get("itemNs") + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + items = args[0].findall(xml_name) # pyright: ignore + if len(items) > 0: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, items) + continue + + # text element is primitive type + if prop_meta.get("text", False): + if args[0].text is not None: + dict_to_pass[rf._rest_name] = _deserialize(rf._type, args[0].text) + continue + + # wrapped element could be normal property or array, it should only have one element + item = args[0].find(xml_name) + if item is not None: + existed_attr_keys.append(xml_name) + dict_to_pass[rf._rest_name] = _deserialize(rf._type, item) + + # rest thing is additional properties + for e in args[0]: + if e.tag not in existed_attr_keys: + dict_to_pass[e.tag] = _convert_element(e) + else: + dict_to_pass.update( + {k: _create_value(_get_rest_field(self._attr_to_rest_field, k), v) for k, v in args[0].items()} + ) else: non_attr_kwargs = [k for k in kwargs if k not in self._attr_to_rest_field] if non_attr_kwargs: @@ -507,55 +618,70 @@ def __init__(self, *args: typing.Any, **kwargs: typing.Any) -> None: def copy(self) -> "Model": return Model(self.__dict__) - def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: # pylint: disable=unused-argument - # we know the last three classes in mro are going to be 'Model', 'dict', and 'object' - mros = cls.__mro__[:-3][::-1] # ignore model, dict, and object parents, and reverse the mro order - attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property - k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") - } - annotations = { - k: v - for mro_class in mros - if hasattr(mro_class, "__annotations__") # pylint: disable=no-member - for k, v in mro_class.__annotations__.items() # pylint: disable=no-member - } - for attr, rf in attr_to_rest_field.items(): - rf._module = cls.__module__ - if not rf._type: - rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) - if not rf._rest_name_input: - rf._rest_name_input = attr - cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items()) - - return super().__new__(cls) # pylint: disable=no-value-for-parameter + def __new__(cls, *args: typing.Any, **kwargs: typing.Any) -> Self: + if f"{cls.__module__}.{cls.__qualname__}" not in cls._calculated: + # we know the last nine classes in mro are going to be 'Model', '_MyMutableMapping', 'MutableMapping', + # 'Mapping', 'Collection', 'Sized', 'Iterable', 'Container' and 'object' + mros = cls.__mro__[:-9][::-1] # ignore parents, and reverse the mro order + attr_to_rest_field: typing.Dict[str, _RestField] = { # map attribute name to rest_field property + k: v for mro_class in mros for k, v in mro_class.__dict__.items() if k[0] != "_" and hasattr(v, "_type") + } + annotations = { + k: v + for mro_class in mros + if hasattr(mro_class, "__annotations__") + for k, v in mro_class.__annotations__.items() + } + for attr, rf in attr_to_rest_field.items(): + rf._module = cls.__module__ + if not rf._type: + rf._type = rf._get_deserialize_callable_from_annotation(annotations.get(attr, None)) + if not rf._rest_name_input: + rf._rest_name_input = attr + cls._attr_to_rest_field: typing.Dict[str, _RestField] = dict(attr_to_rest_field.items()) + cls._calculated.add(f"{cls.__module__}.{cls.__qualname__}") + + return super().__new__(cls) def __init_subclass__(cls, discriminator: typing.Optional[str] = None) -> None: for base in cls.__bases__: - if hasattr(base, "__mapping__"): # pylint: disable=no-member - base.__mapping__[discriminator or cls.__name__] = cls # type: ignore # pylint: disable=no-member + if hasattr(base, "__mapping__"): + base.__mapping__[discriminator or cls.__name__] = cls # type: ignore @classmethod - def _get_discriminator(cls, exist_discriminators) -> typing.Optional[str]: + def _get_discriminator(cls, exist_discriminators) -> typing.Optional["_RestField"]: for v in cls.__dict__.values(): - if ( - isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators - ): # pylint: disable=protected-access - return v._rest_name # pylint: disable=protected-access + if isinstance(v, _RestField) and v._is_discriminator and v._rest_name not in exist_discriminators: + return v return None @classmethod def _deserialize(cls, data, exist_discriminators): - if not hasattr(cls, "__mapping__"): # pylint: disable=no-member + if not hasattr(cls, "__mapping__"): return cls(data) discriminator = cls._get_discriminator(exist_discriminators) - exist_discriminators.append(discriminator) - mapped_cls = cls.__mapping__.get(data.get(discriminator), cls) # pyright: ignore # pylint: disable=no-member - if mapped_cls == cls: + if discriminator is None: return cls(data) - return mapped_cls._deserialize(data, exist_discriminators) # pylint: disable=protected-access + exist_discriminators.append(discriminator._rest_name) + if isinstance(data, ET.Element): + model_meta = getattr(cls, "_xml", {}) + prop_meta = getattr(discriminator, "_xml", {}) + xml_name = prop_meta.get("name", discriminator._rest_name) + xml_ns = prop_meta.get("ns", model_meta.get("ns", None)) + if xml_ns: + xml_name = "{" + xml_ns + "}" + xml_name + + if data.get(xml_name) is not None: + discriminator_value = data.get(xml_name) + else: + discriminator_value = data.find(xml_name).text # pyright: ignore + else: + discriminator_value = data.get(discriminator._rest_name) + mapped_cls = cls.__mapping__.get(discriminator_value, cls) # pyright: ignore # pylint: disable=no-member + return mapped_cls._deserialize(data, exist_discriminators) def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing.Any]: - """Return a dict that can be JSONify using json.dump. + """Return a dict that can be turned into json using json.dump. :keyword bool exclude_readonly: Whether to remove the readonly properties. :returns: A dict JSON compatible object @@ -563,6 +689,7 @@ def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing. """ result = {} + readonly_props = [] if exclude_readonly: readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] for k, v in self.items(): @@ -589,12 +716,74 @@ def _as_dict_value(v: typing.Any, exclude_readonly: bool = False) -> typing.Any: return v.as_dict(exclude_readonly=exclude_readonly) if hasattr(v, "as_dict") else v -def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, R0912 +def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): + if _is_model(obj): + return obj + return _deserialize(model_deserializer, obj) + + +def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): + if obj is None: + return obj + return _deserialize_with_callable(if_obj_deserializer, obj) + + +def _deserialize_with_union(deserializers, obj): + for deserializer in deserializers: + try: + return _deserialize(deserializer, obj) + except DeserializationError: + pass + raise DeserializationError() + + +def _deserialize_dict( + value_deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj: typing.Dict[typing.Any, typing.Any], +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = {child.tag: child for child in obj} + return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} + + +def _deserialize_multiple_sequence( + entry_deserializers: typing.List[typing.Optional[typing.Callable]], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + return type(obj)(_deserialize(deserializer, entry, module) for entry, deserializer in zip(obj, entry_deserializers)) + + +def _deserialize_sequence( + deserializer: typing.Optional[typing.Callable], + module: typing.Optional[str], + obj, +): + if obj is None: + return obj + if isinstance(obj, ET.Element): + obj = list(obj) + return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) + + +def _sorted_annotations(types: typing.List[typing.Any]) -> typing.List[typing.Any]: + return sorted( + types, + key=lambda x: hasattr(x, "__name__") and x.__name__.lower() in ("str", "float", "int", "bool"), + ) + + +def _get_deserialize_callable_from_annotation( # pylint: disable=too-many-return-statements, too-many-branches annotation: typing.Any, module: typing.Optional[str], rf: typing.Optional["_RestField"] = None, ) -> typing.Optional[typing.Callable[[typing.Any], typing.Any]]: - if not annotation or annotation in [int, float]: + if not annotation: return None # is it a type alias? @@ -609,18 +798,13 @@ def _get_deserialize_callable_from_annotation( # pylint: disable=R0911, R0915, except AttributeError: model_name = annotation if module is not None: - annotation = _get_model(module, model_name) + annotation = _get_model(module, model_name) # type: ignore try: if module and _is_model(annotation): if rf: rf._is_model = True - def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj): - if _is_model(obj): - return obj - return _deserialize(model_deserializer, obj) - return functools.partial(_deserialize_model, annotation) # pyright: ignore except Exception: pass @@ -635,36 +819,27 @@ def _deserialize_model(model_deserializer: typing.Optional[typing.Callable], obj # is it optional? try: if any(a for a in annotation.__args__ if a == type(None)): # pyright: ignore - if_obj_deserializer = _get_deserialize_callable_from_annotation( - next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore - ) - - def _deserialize_with_optional(if_obj_deserializer: typing.Optional[typing.Callable], obj): - if obj is None: - return obj - return _deserialize_with_callable(if_obj_deserializer, obj) - - return functools.partial(_deserialize_with_optional, if_obj_deserializer) + if len(annotation.__args__) <= 2: # pyright: ignore + if_obj_deserializer = _get_deserialize_callable_from_annotation( + next(a for a in annotation.__args__ if a != type(None)), module, rf # pyright: ignore + ) + + return functools.partial(_deserialize_with_optional, if_obj_deserializer) + # the type is Optional[Union[...]], we need to remove the None type from the Union + annotation_copy = copy.copy(annotation) + annotation_copy.__args__ = [a for a in annotation_copy.__args__ if a != type(None)] # pyright: ignore + return _get_deserialize_callable_from_annotation(annotation_copy, module, rf) except AttributeError: pass + # is it union? if getattr(annotation, "__origin__", None) is typing.Union: # initial ordering is we make `string` the last deserialization option, because it is often them most generic deserializers = [ _get_deserialize_callable_from_annotation(arg, module, rf) - for arg in sorted( - annotation.__args__, key=lambda x: hasattr(x, "__name__") and x.__name__ == "str" # pyright: ignore - ) + for arg in _sorted_annotations(annotation.__args__) # pyright: ignore ] - def _deserialize_with_union(deserializers, obj): - for deserializer in deserializers: - try: - return _deserialize(deserializer, obj) - except DeserializationError: - pass - raise DeserializationError() - return functools.partial(_deserialize_with_union, deserializers) try: @@ -673,53 +848,26 @@ def _deserialize_with_union(deserializers, obj): annotation.__args__[1], module, rf # pyright: ignore ) - def _deserialize_dict( - value_deserializer: typing.Optional[typing.Callable], - obj: typing.Dict[typing.Any, typing.Any], - ): - if obj is None: - return obj - return {k: _deserialize(value_deserializer, v, module) for k, v in obj.items()} - return functools.partial( _deserialize_dict, value_deserializer, + module, ) except (AttributeError, IndexError): pass try: if annotation._name in ["List", "Set", "Tuple", "Sequence"]: # pyright: ignore if len(annotation.__args__) > 1: # pyright: ignore - - def _deserialize_multiple_sequence( - entry_deserializers: typing.List[typing.Optional[typing.Callable]], - obj, - ): - if obj is None: - return obj - return type(obj)( - _deserialize(deserializer, entry, module) - for entry, deserializer in zip(obj, entry_deserializers) - ) - entry_deserializers = [ _get_deserialize_callable_from_annotation(dt, module, rf) for dt in annotation.__args__ # pyright: ignore ] - return functools.partial(_deserialize_multiple_sequence, entry_deserializers) + return functools.partial(_deserialize_multiple_sequence, entry_deserializers, module) deserializer = _get_deserialize_callable_from_annotation( annotation.__args__[0], module, rf # pyright: ignore ) - def _deserialize_sequence( - deserializer: typing.Optional[typing.Callable], - obj, - ): - if obj is None: - return obj - return type(obj)(_deserialize(deserializer, entry, module) for entry in obj) - - return functools.partial(_deserialize_sequence, deserializer) + return functools.partial(_deserialize_sequence, deserializer, module) except (TypeError, IndexError, AttributeError, SyntaxError): pass @@ -744,12 +892,23 @@ def _deserialize_default( def _deserialize_with_callable( deserializer: typing.Optional[typing.Callable[[typing.Any], typing.Any]], value: typing.Any, -): +): # pylint: disable=too-many-return-statements try: if value is None or isinstance(value, _Null): return None + if isinstance(value, ET.Element): + if deserializer is str: + return value.text or "" + if deserializer is int: + return int(value.text) if value.text else None + if deserializer is float: + return float(value.text) if value.text else None + if deserializer is bool: + return value.text == "true" if value.text else None if deserializer is None: return value + if deserializer in [int, float, bool]: + return deserializer(value) if isinstance(deserializer, CaseInsensitiveEnumMeta): try: return deserializer(value) @@ -779,6 +938,35 @@ def _deserialize( return _deserialize_with_callable(deserializer, value) +def _failsafe_deserialize( + deserializer: typing.Any, + value: typing.Any, + module: typing.Optional[str] = None, + rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, +) -> typing.Any: + try: + return _deserialize(deserializer, value, module, rf, format) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + +def _failsafe_deserialize_xml( + deserializer: typing.Any, + value: typing.Any, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, value) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + class _RestField: def __init__( self, @@ -790,6 +978,7 @@ def __init__( default: typing.Any = _UNSET, format: typing.Optional[str] = None, is_multipart_file_input: bool = False, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, ): self._type = type self._rest_name_input = name @@ -800,6 +989,7 @@ def __init__( self._default = default self._format = format self._is_multipart_file_input = is_multipart_file_input + self._xml = xml if xml is not None else {} @property def _class_type(self) -> typing.Any: @@ -850,6 +1040,7 @@ def rest_field( default: typing.Any = _UNSET, format: typing.Optional[str] = None, is_multipart_file_input: bool = False, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, ) -> typing.Any: return _RestField( name=name, @@ -858,6 +1049,7 @@ def rest_field( default=default, format=format, is_multipart_file_input=is_multipart_file_input, + xml=xml, ) @@ -865,5 +1057,176 @@ def rest_discriminator( *, name: typing.Optional[str] = None, type: typing.Optional[typing.Callable] = None, # pylint: disable=redefined-builtin + visibility: typing.Optional[typing.List[str]] = None, + xml: typing.Optional[typing.Dict[str, typing.Any]] = None, ) -> typing.Any: - return _RestField(name=name, type=type, is_discriminator=True) + return _RestField(name=name, type=type, is_discriminator=True, visibility=visibility, xml=xml) + + +def serialize_xml(model: Model, exclude_readonly: bool = False) -> str: + """Serialize a model to XML. + + :param Model model: The model to serialize. + :param bool exclude_readonly: Whether to exclude readonly properties. + :returns: The XML representation of the model. + :rtype: str + """ + return ET.tostring(_get_element(model, exclude_readonly), encoding="unicode") # type: ignore + + +def _get_element( + o: typing.Any, + exclude_readonly: bool = False, + parent_meta: typing.Optional[typing.Dict[str, typing.Any]] = None, + wrapped_element: typing.Optional[ET.Element] = None, +) -> typing.Union[ET.Element, typing.List[ET.Element]]: + if _is_model(o): + model_meta = getattr(o, "_xml", {}) + + # if prop is a model, then use the prop element directly, else generate a wrapper of model + if wrapped_element is None: + wrapped_element = _create_xml_element( + model_meta.get("name", o.__class__.__name__), + model_meta.get("prefix"), + model_meta.get("ns"), + ) + + readonly_props = [] + if exclude_readonly: + readonly_props = [p._rest_name for p in o._attr_to_rest_field.values() if _is_readonly(p)] + + for k, v in o.items(): + # do not serialize readonly properties + if exclude_readonly and k in readonly_props: + continue + + prop_rest_field = _get_rest_field(o._attr_to_rest_field, k) + if prop_rest_field: + prop_meta = getattr(prop_rest_field, "_xml").copy() + # use the wire name as xml name if no specific name is set + if prop_meta.get("name") is None: + prop_meta["name"] = k + else: + # additional properties will not have rest field, use the wire name as xml name + prop_meta = {"name": k} + + # if no ns for prop, use model's + if prop_meta.get("ns") is None and model_meta.get("ns"): + prop_meta["ns"] = model_meta.get("ns") + prop_meta["prefix"] = model_meta.get("prefix") + + if prop_meta.get("unwrapped", False): + # unwrapped could only set on array + wrapped_element.extend(_get_element(v, exclude_readonly, prop_meta)) + elif prop_meta.get("text", False): + # text could only set on primitive type + wrapped_element.text = _get_primitive_type_value(v) + elif prop_meta.get("attribute", False): + xml_name = prop_meta.get("name", k) + if prop_meta.get("ns"): + ET.register_namespace(prop_meta.get("prefix"), prop_meta.get("ns")) # pyright: ignore + xml_name = "{" + prop_meta.get("ns") + "}" + xml_name # pyright: ignore + # attribute should be primitive type + wrapped_element.set(xml_name, _get_primitive_type_value(v)) + else: + # other wrapped prop element + wrapped_element.append(_get_wrapped_element(v, exclude_readonly, prop_meta)) + return wrapped_element + if isinstance(o, list): + return [_get_element(x, exclude_readonly, parent_meta) for x in o] # type: ignore + if isinstance(o, dict): + result = [] + for k, v in o.items(): + result.append( + _get_wrapped_element( + v, + exclude_readonly, + { + "name": k, + "ns": parent_meta.get("ns") if parent_meta else None, + "prefix": parent_meta.get("prefix") if parent_meta else None, + }, + ) + ) + return result + + # primitive case need to create element based on parent_meta + if parent_meta: + return _get_wrapped_element( + o, + exclude_readonly, + { + "name": parent_meta.get("itemsName", parent_meta.get("name")), + "prefix": parent_meta.get("itemsPrefix", parent_meta.get("prefix")), + "ns": parent_meta.get("itemsNs", parent_meta.get("ns")), + }, + ) + + raise ValueError("Could not serialize value into xml: " + o) + + +def _get_wrapped_element( + v: typing.Any, + exclude_readonly: bool, + meta: typing.Optional[typing.Dict[str, typing.Any]], +) -> ET.Element: + wrapped_element = _create_xml_element( + meta.get("name") if meta else None, meta.get("prefix") if meta else None, meta.get("ns") if meta else None + ) + if isinstance(v, (dict, list)): + wrapped_element.extend(_get_element(v, exclude_readonly, meta)) + elif _is_model(v): + _get_element(v, exclude_readonly, meta, wrapped_element) + else: + wrapped_element.text = _get_primitive_type_value(v) + return wrapped_element + + +def _get_primitive_type_value(v) -> str: + if v is True: + return "true" + if v is False: + return "false" + if isinstance(v, _Null): + return "" + return str(v) + + +def _create_xml_element(tag, prefix=None, ns=None): + if prefix and ns: + ET.register_namespace(prefix, ns) + if ns: + return ET.Element("{" + ns + "}" + tag) + return ET.Element(tag) + + +def _deserialize_xml( + deserializer: typing.Any, + value: str, +) -> typing.Any: + element = ET.fromstring(value) # nosec + return _deserialize(deserializer, element) + + +def _convert_element(e: ET.Element): + # dict case + if len(e.attrib) > 0 or len({child.tag for child in e}) > 1: + dict_result: typing.Dict[str, typing.Any] = {} + for child in e: + if dict_result.get(child.tag) is not None: + if isinstance(dict_result[child.tag], list): + dict_result[child.tag].append(_convert_element(child)) + else: + dict_result[child.tag] = [dict_result[child.tag], _convert_element(child)] + else: + dict_result[child.tag] = _convert_element(child) + dict_result.update(e.attrib) + return dict_result + # array case + if len(e) > 0: + array_result: typing.List[typing.Any] = [] + for child in e: + array_result.append(_convert_element(child)) + return array_result + # primitive case + return e.text diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_serialization.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/serialization.py similarity index 82% rename from sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_serialization.py rename to sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/serialization.py index 2f781d740827..eb86ea23c965 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_serialization.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/serialization.py @@ -1,30 +1,12 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# pylint: skip-file # pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode @@ -48,11 +30,8 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, List, - Mapping, ) try: @@ -62,13 +41,13 @@ import xml.etree.ElementTree as ET import isodate # type: ignore +from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -ModelType = TypeVar("ModelType", bound="Model") JSON = MutableMapping[str, Any] @@ -91,6 +70,8 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: :param data: Input, could be bytes or stream (will be decoded with UTF8) or text :type data: str or bytes or IO :param str content_type: The content type. + :return: The deserialized data. + :rtype: object """ if hasattr(data, "read"): # Assume a stream @@ -112,7 +93,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: try: return json.loads(data_as_str) except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) + raise DeserializationError("JSON is invalid: {}".format(err), err) from err elif "xml" in (content_type or []): try: @@ -144,6 +125,8 @@ def _json_attemp(data): # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") raise DeserializationError("XML is invalid") from err + elif content_type.startswith("text/"): + return data_as_str raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -153,6 +136,11 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], Use bytes and headers to NOT use any requests/aiohttp or whatever specific implementation. Headers will tested for "content-type" + + :param bytes body_bytes: The body of the response. + :param dict headers: The headers of the response. + :returns: The deserialized data. + :rtype: object """ # Try to use content-type from headers if available content_type = None @@ -177,80 +165,31 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], except NameError: _long_type = int - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -try: - from datetime import timezone as _FixedOffset # type: ignore -except ImportError: # Python 2.7 - - class _FixedOffset(datetime.tzinfo): # type: ignore - """Fixed offset in minutes east from UTC. - Copy/pasted from Python doc - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc -except ImportError: - TZ_UTC = UTC() # type: ignore +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? None: self.additional_properties: Optional[Dict[str, Any]] = {} - for k in kwargs: + for k in kwargs: # pylint: disable=consider-using-dict-items if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) elif k in self._validation and self._validation[k].get("readonly", False): @@ -298,13 +244,23 @@ def __init__(self, **kwargs: Any) -> None: setattr(self, k, kwargs[k]) def __eq__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are equal + :rtype: bool + """ if isinstance(other, self.__class__): return self.__dict__ == other.__dict__ return False def __ne__(self, other: Any) -> bool: - """Compare objects by comparing all attributes.""" + """Compare objects by comparing all attributes. + + :param object other: The object to compare + :returns: True if objects are not equal + :rtype: bool + """ return not self.__eq__(other) def __str__(self) -> str: @@ -324,7 +280,11 @@ def is_xml_model(cls) -> bool: @classmethod def _create_xml_node(cls): - """Create XML node.""" + """Create XML node. + + :returns: The XML node + :rtype: xml.etree.ElementTree.Element + """ try: xml_map = cls._xml_map # type: ignore except AttributeError: @@ -344,7 +304,9 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) def as_dict( self, @@ -378,12 +340,15 @@ def my_key_transformer(key, attr_desc, value): If you want XML serialization, you can pass the kwargs is_xml=True. + :param bool keep_readonly: If you want to serialize the readonly attributes :param function key_transformer: A key transformer function. :returns: A dict JSON compatible object :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs + ) @classmethod def _infer_class_models(cls): @@ -393,30 +358,31 @@ def _infer_class_models(cls): client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} if cls.__name__ not in client_models: raise ValueError("Not Autorest generated code") - except Exception: + except Exception: # pylint: disable=broad-exception-caught # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. client_models = {cls.__name__: cls} return client_models @classmethod - def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def from_dict( - cls: Type[ModelType], + cls, data: Any, key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, content_type: Optional[str] = None, - ) -> ModelType: + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -424,9 +390,11 @@ def from_dict( and last_rest_key_case_insensitive_extractor) :param dict data: A dict using RestAPI structure + :param function key_extractors: A key extractor function. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -446,21 +414,25 @@ def _flatten_subtype(cls, key, objects): return {} result = dict(cls._subtype_map[key]) for valuetype in cls._subtype_map[key].values(): - result.update(objects[valuetype]._flatten_subtype(key, objects)) + result.update(objects[valuetype]._flatten_subtype(key, objects)) # pylint: disable=protected-access return result @classmethod def _classify(cls, response, objects): """Check the class _subtype_map for any child classes. We want to ignore any inherited _subtype_maps. - Remove the polymorphic key from the initial data. + + :param dict response: The initial data + :param dict objects: The class objects + :returns: The class to be used + :rtype: class """ for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): subtype_value = None if not isinstance(response, ET.Element): rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] - subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + subtype_value = response.get(rest_api_response_key, None) or response.get(subtype_key, None) else: subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) if subtype_value: @@ -499,11 +471,13 @@ def _decode_attribute_map_key(key): inside the received data. :param str key: A key string from the generated code + :returns: The decoded key + :rtype: str """ return key.replace("\\.", ".") -class Serializer(object): +class Serializer: # pylint: disable=too-many-public-methods """Request object model serializer.""" basic_types = {str: "str", int: "int", bool: "bool", float: "float"} @@ -538,7 +512,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -558,13 +532,16 @@ def __init__(self, classes: Optional[Mapping[str, type]] = None): self.key_transformer = full_restapi_key_transformer self.client_side_validation = True - def _serialize(self, target_obj, data_type=None, **kwargs): + def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, too-many-statements, too-many-locals + self, target_obj, data_type=None, **kwargs + ): """Serialize data into a string according to type. - :param target_obj: The data to be serialized. + :param object target_obj: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, dict - :raises: SerializationError if serialization fails. + :raises SerializationError: if serialization fails. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -590,12 +567,14 @@ def _serialize(self, target_obj, data_type=None, **kwargs): serialized = {} if is_xml_model_serialization: - serialized = target_obj._create_xml_node() + serialized = target_obj._create_xml_node() # pylint: disable=protected-access try: - attributes = target_obj._attribute_map + attributes = target_obj._attribute_map # pylint: disable=protected-access for attr, attr_desc in attributes.items(): attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + if not keep_readonly and target_obj._validation.get( # pylint: disable=protected-access + attr_name, {} + ).get("readonly", False): continue if attr_name == "additional_properties" and attr_desc["key"] == "": @@ -631,7 +610,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if isinstance(new_attr, list): serialized.extend(new_attr) # type: ignore elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + # If the down XML has no XML/Name, + # we MUST replace the tag with the local tag. But keeping the namespaces. if "name" not in getattr(orig_attr, "_xml_map", {}): splitted_tag = new_attr.tag.split("}") if len(splitted_tag) == 2: # Namespace @@ -662,17 +642,17 @@ def _serialize(self, target_obj, data_type=None, **kwargs): except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) raise SerializationError(msg) from err - else: - return serialized + return serialized def body(self, data, data_type, **kwargs): """Serialize data intended for a request body. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized request body """ # Just in case this is a dict @@ -701,7 +681,7 @@ def body(self, data, data_type, **kwargs): attribute_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, ] - data = deserializer._deserialize(data_type, data) + data = deserializer._deserialize(data_type, data) # pylint: disable=protected-access except DeserializationError as err: raise SerializationError("Unable to build a model: " + str(err)) from err @@ -710,11 +690,13 @@ def body(self, data, data_type, **kwargs): def url(self, name, data, data_type, **kwargs): """Serialize data intended for a URL path. - :param data: The data to be serialized. + :param str name: The name of the URL path parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :returns: The serialized URL path + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -726,21 +708,20 @@ def url(self, name, data, data_type, **kwargs): output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return output def query(self, name, data, data_type, **kwargs): """Serialize data intended for a URL query. - :param data: The data to be serialized. + :param str name: The name of the query parameter. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :keyword bool skip_quote: Whether to skip quote the serialized result. - Defaults to False. :rtype: str, list - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized query parameter """ try: # Treat the list aside, since we don't want to encode the div separator @@ -757,19 +738,20 @@ def query(self, name, data, data_type, **kwargs): output = str(output) else: output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def header(self, name, data, data_type, **kwargs): """Serialize data intended for a request header. - :param data: The data to be serialized. + :param str name: The name of the header. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -778,21 +760,20 @@ def header(self, name, data, data_type, **kwargs): output = self.serialize_data(data, data_type, **kwargs) if data_type == "bool": output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) + except SerializationError as exc: + raise TypeError("{} must be type {}.".format(name, data_type)) from exc + return str(output) def serialize_data(self, data, data_type, **kwargs): """Serialize generic data according to supplied data type. - :param data: The data to be serialized. + :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") @@ -803,7 +784,7 @@ def serialize_data(self, data, data_type, **kwargs): if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) - elif data_type in self.serialize_type: + if data_type in self.serialize_type: return self.serialize_type[data_type](data, **kwargs) # If dependencies is empty, try with current data class @@ -819,11 +800,10 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." raise SerializationError(msg.format(data, data_type)) from err - else: - return self._serialize(data, **kwargs) + return self._serialize(data, **kwargs) @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): + def _get_custom_serializers(cls, data_type, **kwargs): # pylint: disable=inconsistent-return-statements custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) if custom_serializer: return custom_serializer @@ -839,23 +819,26 @@ def serialize_basic(cls, data, data_type, **kwargs): - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - is_xml bool : If set, use xml_basic_types_serializers - :param data: Object to be serialized. + :param obj data: Object to be serialized. :param str data_type: Type of object in the iterable. + :rtype: str, int, float, bool + :return: serialized object """ custom_serializer = cls._get_custom_serializers(data_type, **kwargs) if custom_serializer: return custom_serializer(data) if data_type == "str": return cls.serialize_unicode(data) - return eval(data_type)(data) # nosec + return eval(data_type)(data) # nosec # pylint: disable=eval-used @classmethod def serialize_unicode(cls, data): """Special handling for serializing unicode strings in Py2. Encode to UTF-8 if unicode, otherwise handle as a str. - :param data: Object to be serialized. + :param str data: Object to be serialized. :rtype: str + :return: serialized object """ try: # If I received an enum, return its value return data.value @@ -869,8 +852,7 @@ def serialize_unicode(cls, data): return data except NameError: return str(data) - else: - return str(data) + return str(data) def serialize_iter(self, data, iter_type, div=None, **kwargs): """Serialize iterable. @@ -880,15 +862,13 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialization_ctxt['type'] should be same as data_type. - is_xml bool : If set, serialize as XML - :param list attr: Object to be serialized. + :param list data: Object to be serialized. :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. :param str div: If set, this str will be used to combine the elements in the iterable into a combined string. Default is 'None'. - :keyword bool do_quote: Whether to quote the serialized result of each iterable element. Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -943,9 +923,8 @@ def serialize_dict(self, attr, dict_type, **kwargs): :param dict attr: Object to be serialized. :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. :rtype: dict + :return: serialized dictionary """ serialization_ctxt = kwargs.get("serialization_ctxt", {}) serialized = {} @@ -969,7 +948,7 @@ def serialize_dict(self, attr, dict_type, **kwargs): return serialized - def serialize_object(self, attr, **kwargs): + def serialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Serialize a generic object. This will be handled as a dictionary. If object passed in is not a basic type (str, int, float, dict, list) it will simply be @@ -977,6 +956,7 @@ def serialize_object(self, attr, **kwargs): :param dict attr: Object to be serialized. :rtype: dict or str + :return: serialized object """ if attr is None: return None @@ -1001,7 +981,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_decimal(attr) # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): + if obj_type in self.dependencies.values() or isinstance(attr, Model): return self._serialize(attr) if obj_type == dict: @@ -1032,56 +1012,61 @@ def serialize_enum(attr, enum_obj=None): try: enum_obj(result) # type: ignore return result - except ValueError: + except ValueError as exc: for enum_value in enum_obj: # type: ignore if enum_value.value.lower() == str(attr).lower(): return enum_value.value error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) + raise SerializationError(error.format(attr, enum_obj)) from exc @staticmethod - def serialize_bytearray(attr, **kwargs): + def serialize_bytearray(attr, **kwargs): # pylint: disable=unused-argument """Serialize bytearray into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ return b64encode(attr).decode() @staticmethod - def serialize_base64(attr, **kwargs): + def serialize_base64(attr, **kwargs): # pylint: disable=unused-argument """Serialize str into base-64 string. - :param attr: Object to be serialized. + :param str attr: Object to be serialized. :rtype: str + :return: serialized base64 """ encoded = b64encode(attr).decode("ascii") return encoded.strip("=").replace("+", "-").replace("/", "_") @staticmethod - def serialize_decimal(attr, **kwargs): + def serialize_decimal(attr, **kwargs): # pylint: disable=unused-argument """Serialize Decimal object to float. - :param attr: Object to be serialized. + :param decimal attr: Object to be serialized. :rtype: float + :return: serialized decimal """ return float(attr) @staticmethod - def serialize_long(attr, **kwargs): + def serialize_long(attr, **kwargs): # pylint: disable=unused-argument """Serialize long (Py2) or int (Py3). - :param attr: Object to be serialized. + :param int attr: Object to be serialized. :rtype: int/long + :return: serialized long """ return _long_type(attr) @staticmethod - def serialize_date(attr, **kwargs): + def serialize_date(attr, **kwargs): # pylint: disable=unused-argument """Serialize Date object into ISO-8601 formatted string. :param Date attr: Object to be serialized. :rtype: str + :return: serialized date """ if isinstance(attr, str): attr = isodate.parse_date(attr) @@ -1089,11 +1074,12 @@ def serialize_date(attr, **kwargs): return t @staticmethod - def serialize_time(attr, **kwargs): + def serialize_time(attr, **kwargs): # pylint: disable=unused-argument """Serialize Time object into ISO-8601 formatted string. :param datetime.time attr: Object to be serialized. :rtype: str + :return: serialized time """ if isinstance(attr, str): attr = isodate.parse_time(attr) @@ -1103,30 +1089,32 @@ def serialize_time(attr, **kwargs): return t @staticmethod - def serialize_duration(attr, **kwargs): + def serialize_duration(attr, **kwargs): # pylint: disable=unused-argument """Serialize TimeDelta object into ISO-8601 formatted string. :param TimeDelta attr: Object to be serialized. :rtype: str + :return: serialized duration """ if isinstance(attr, str): attr = isodate.parse_duration(attr) return isodate.duration_isoformat(attr) @staticmethod - def serialize_rfc(attr, **kwargs): + def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into RFC-1123 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. + :return: serialized rfc """ try: if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("RFC1123 object must be valid Datetime object.") from exc return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( Serializer.days[utc.tm_wday], @@ -1139,12 +1127,13 @@ def serialize_rfc(attr, **kwargs): ) @staticmethod - def serialize_iso(attr, **kwargs): + def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into ISO-8601 formatted string. :param Datetime attr: Object to be serialized. :rtype: str - :raises: SerializationError if format invalid. + :raises SerializationError: if format invalid. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1170,13 +1159,14 @@ def serialize_iso(attr, **kwargs): raise TypeError(msg) from err @staticmethod - def serialize_unix(attr, **kwargs): + def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument """Serialize Datetime object into IntTime format. This is represented as seconds. :param Datetime attr: Object to be serialized. :rtype: int - :raises: SerializationError if format invalid + :raises SerializationError: if format invalid + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1184,11 +1174,11 @@ def serialize_unix(attr, **kwargs): if not attr.tzinfo: _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") + except AttributeError as exc: + raise TypeError("Unix time object must be valid Datetime object.") from exc -def rest_key_extractor(attr, attr_desc, data): +def rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument key = attr_desc["key"] working_data = data @@ -1209,7 +1199,9 @@ def rest_key_extractor(attr, attr_desc, data): return working_data.get(key) -def rest_key_case_insensitive_extractor(attr, attr_desc, data): +def rest_key_case_insensitive_extractor( # pylint: disable=unused-argument, inconsistent-return-statements + attr, attr_desc, data +): key = attr_desc["key"] working_data = data @@ -1230,17 +1222,29 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): return attribute_key_case_insensitive_extractor(key, None, working_data) -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" +def last_rest_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument + """Extract the attribute in "data" based on the last part of the JSON path key. + + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute + """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) return attribute_key_extractor(dict_keys[-1], None, data) -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): # pylint: disable=unused-argument """Extract the attribute in "data" based on the last part of the JSON path key. This is the case insensitive version of "last_rest_key_extractor" + :param str attr: The attribute to extract + :param dict attr_desc: The attribute description + :param dict data: The data to extract from + :rtype: object + :returns: The extracted attribute """ key = attr_desc["key"] dict_keys = _FLATTEN.split(key) @@ -1277,7 +1281,7 @@ def _extract_name_from_internal_type(internal_type): return xml_name -def xml_key_extractor(attr, attr_desc, data): +def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument,too-many-return-statements if isinstance(data, dict): return None @@ -1329,22 +1333,21 @@ def xml_key_extractor(attr, attr_desc, data): if is_iter_type: if is_wrapped: return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list + return [] # not wrapped, assume empty list return None # Assume it's not there, maybe an optional node. # If is_iter_type and not wrapped, return all found children if is_iter_type: if not is_wrapped: return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) + # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name ) - return list(children[0]) # Might be empty list and that's ok. + ) + return list(children[0]) # Might be empty list and that's ok. # Here it's not a itertype, we should have found one element only or empty if len(children) > 1: @@ -1352,7 +1355,7 @@ def xml_key_extractor(attr, attr_desc, data): return children[0] -class Deserializer(object): +class Deserializer: """Response object model deserializer. :param dict classes: Class type dictionary for deserializing complex types. @@ -1361,9 +1364,9 @@ class Deserializer(object): basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") - def __init__(self, classes: Optional[Mapping[str, type]] = None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1399,27 +1402,29 @@ def __call__(self, target_obj, response_data, content_type=None): :param str target_obj: Target data type to deserialize to. :param requests.Response response_data: REST response object. :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ data = self._unpack_content(response_data, content_type) return self._deserialize(target_obj, data) - def _deserialize(self, target_obj, data): + def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return-statements """Call the deserializer on a model. Data needs to be already deserialized as JSON or XML ElementTree :param str target_obj: Target data type to deserialize to. :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ # This is already a model, go recursive just in case if hasattr(data, "_attribute_map"): constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] try: - for attr, mapconfig in data._attribute_map.items(): + for attr, mapconfig in data._attribute_map.items(): # pylint: disable=protected-access if attr in constants: continue value = getattr(data, attr) @@ -1438,13 +1443,13 @@ def _deserialize(self, target_obj, data): if isinstance(response, str): return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): + if isinstance(response, type) and issubclass(response, Enum): return self.deserialize_enum(data, response) - if data is None: + if data is None or data is CoreNull: return data try: - attributes = response._attribute_map # type: ignore + attributes = response._attribute_map # type: ignore # pylint: disable=protected-access d_attrs = {} for attr, attr_desc in attributes.items(): # Check empty string. If it's not empty, someone has a real "additionalProperties"... @@ -1474,9 +1479,8 @@ def _deserialize(self, target_obj, data): except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore raise DeserializationError(msg) from err - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) def _build_additional_properties(self, attribute_map, data): if not self.additional_properties_detection: @@ -1503,6 +1507,8 @@ def _classify_target(self, target, data): :param str target: The target object type to deserialize to. :param str/dict data: The response data to deserialize. + :return: The classified target object and its class name. + :rtype: tuple """ if target is None: return None, None @@ -1514,7 +1520,7 @@ def _classify_target(self, target, data): return target, target try: - target = target._classify(data, self.dependencies) # type: ignore + target = target._classify(data, self.dependencies) # type: ignore # pylint: disable=protected-access except AttributeError: pass # Target is not a Model, no classify return target, target.__class__.__name__ # type: ignore @@ -1529,10 +1535,12 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): :param str target_obj: The target object type to deserialize to. :param str/dict data: The response data to deserialize. :param str content_type: Swagger "produces" if available. + :return: Deserialized object. + :rtype: object """ try: return self(target_obj, data, content_type=content_type) - except: + except: # pylint: disable=bare-except _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) @@ -1550,10 +1558,12 @@ def _unpack_content(raw_data, content_type=None): If raw_data is something else, bypass all logic and return it directly. - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. + :param obj raw_data: Data to be processed. + :param str content_type: How to parse if raw_data is a string/bytes. :raises JSONDecodeError: If JSON is requested and parsing is impossible. :raises UnicodeDecodeError: If bytes is not UTF8 + :rtype: object + :return: Unpacked content. """ # Assume this is enough to detect a Pipeline Response without importing it context = getattr(raw_data, "context", {}) @@ -1577,24 +1587,35 @@ def _unpack_content(raw_data, content_type=None): def _instantiate_model(self, response, attrs, additional_properties=None): """Instantiate a response model passing in deserialized args. - :param response: The response model class. - :param d_attrs: The deserialized response attributes. + :param Response response: The response model class. + :param dict attrs: The deserialized response attributes. + :param dict additional_properties: Additional properties to be set. + :rtype: Response + :return: The instantiated response model. """ if callable(response): subtype = getattr(response, "_subtype_map", {}) try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] + readonly = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("readonly") + ] + const = [ + k + for k, v in response._validation.items() # pylint: disable=protected-access # type: ignore + if v.get("constant") + ] kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} response_obj = response(**kwargs) for attr in readonly: setattr(response_obj, attr, attrs.get(attr)) if additional_properties: - response_obj.additional_properties = additional_properties + response_obj.additional_properties = additional_properties # type: ignore return response_obj except TypeError as err: msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore - raise DeserializationError(msg + str(err)) + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1603,15 +1624,16 @@ def _instantiate_model(self, response, attrs, additional_properties=None): except Exception as exp: msg = "Unable to populate response model. " msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + raise DeserializationError(msg) from exp - def deserialize_data(self, data, data_type): + def deserialize_data(self, data, data_type): # pylint: disable=too-many-return-statements """Process data for deserialization according to data type. :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1625,7 +1647,11 @@ def deserialize_data(self, data, data_type): if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): return data - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + is_a_text_parsing_type = lambda x: x not in [ # pylint: disable=unnecessary-lambda-assignment + "object", + "[]", + r"{}", + ] if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: return None data_val = self.deserialize_type[data_type](data) @@ -1645,14 +1671,14 @@ def deserialize_data(self, data, data_type): msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) raise DeserializationError(msg) from err - else: - return self._deserialize(obj_type, data) + return self._deserialize(obj_type, data) def deserialize_iter(self, attr, iter_type): """Deserialize an iterable. :param list attr: Iterable to be deserialized. :param str iter_type: The type of object in the iterable. + :return: Deserialized iterable. :rtype: list """ if attr is None: @@ -1669,6 +1695,7 @@ def deserialize_dict(self, attr, dict_type): :param dict/list attr: Dictionary to be deserialized. Also accepts a list of key, value pairs. :param str dict_type: The object type of the items in the dictionary. + :return: Deserialized dictionary. :rtype: dict """ if isinstance(attr, list): @@ -1679,13 +1706,14 @@ def deserialize_dict(self, attr, dict_type): attr = {el.tag: el.text for el in attr} return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - def deserialize_object(self, attr, **kwargs): + def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return-statements """Deserialize a generic object. This will be handled as a dictionary. :param dict attr: Dictionary to be deserialized. + :return: Deserialized object. :rtype: dict - :raises: TypeError if non-builtin datatype encountered. + :raises TypeError: if non-builtin datatype encountered. """ if attr is None: return None @@ -1718,11 +1746,10 @@ def deserialize_object(self, attr, **kwargs): pass return deserialized - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) - def deserialize_basic(self, attr, data_type): + def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return-statements """Deserialize basic builtin data type from string. Will attempt to convert to str, int, float and bool. This function will also accept '1', '0', 'true' and 'false' as @@ -1730,8 +1757,9 @@ def deserialize_basic(self, attr, data_type): :param str attr: response string to be deserialized. :param str data_type: deserialization data type. + :return: Deserialized basic type. :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. + :raises TypeError: if string format is not valid. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1741,24 +1769,23 @@ def deserialize_basic(self, attr, data_type): if data_type == "str": # None or '', node is empty string. return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None if data_type == "bool": if attr in [True, False, 1, 0]: return bool(attr) - elif isinstance(attr, str): + if isinstance(attr, str): if attr.lower() in ["true", "1"]: return True - elif attr.lower() in ["false", "0"]: + if attr.lower() in ["false", "0"]: return False raise TypeError("Invalid boolean value: {}".format(attr)) if data_type == "str": return self.deserialize_unicode(attr) - return eval(data_type)(attr) # nosec + return eval(data_type)(attr) # nosec # pylint: disable=eval-used @staticmethod def deserialize_unicode(data): @@ -1766,6 +1793,7 @@ def deserialize_unicode(data): as a string. :param str data: response string to be deserialized. + :return: Deserialized string. :rtype: str or unicode """ # We might be here because we have an enum modeled as string, @@ -1779,8 +1807,7 @@ def deserialize_unicode(data): return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1792,6 +1819,7 @@ def deserialize_enum(data, enum_obj): :param str data: Response string to be deserialized. If this value is None or invalid it will be returned as-is. :param Enum enum_obj: Enum object to deserialize to. + :return: Deserialized enum object. :rtype: Enum """ if isinstance(data, enum_obj) or data is None: @@ -1802,9 +1830,9 @@ def deserialize_enum(data, enum_obj): # Workaround. We might consider remove it in the future. try: return list(enum_obj.__members__.values())[data] - except IndexError: + except IndexError as exc: error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) + raise DeserializationError(error.format(data, enum_obj)) from exc try: return enum_obj(str(data)) except ValueError: @@ -1820,8 +1848,9 @@ def deserialize_bytearray(attr): """Deserialize string into bytearray. :param str attr: response string to be deserialized. + :return: Deserialized bytearray :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1832,8 +1861,9 @@ def deserialize_base64(attr): """Deserialize base64 encoded string into string. :param str attr: response string to be deserialized. + :return: Deserialized base64 string :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1847,8 +1877,9 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. + :return: Deserialized decimal + :raises DeserializationError: if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text @@ -1863,8 +1894,9 @@ def deserialize_long(attr): """Deserialize string into long (Py2) or int (Py3). :param str attr: response string to be deserialized. + :return: Deserialized int :rtype: long or int - :raises: ValueError if string format invalid. + :raises ValueError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1875,8 +1907,9 @@ def deserialize_duration(attr): """Deserialize ISO-8601 formatted string into TimeDelta object. :param str attr: response string to be deserialized. + :return: Deserialized duration :rtype: TimeDelta - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1885,16 +1918,16 @@ def deserialize_duration(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." raise DeserializationError(msg) from err - else: - return duration + return duration @staticmethod def deserialize_date(attr): """Deserialize ISO-8601 formatted string into Date object. :param str attr: response string to be deserialized. + :return: Deserialized date :rtype: Date - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1908,8 +1941,9 @@ def deserialize_time(attr): """Deserialize ISO-8601 formatted string into time object. :param str attr: response string to be deserialized. + :return: Deserialized time :rtype: datetime.time - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1922,31 +1956,32 @@ def deserialize_rfc(attr): """Deserialize RFC-1123 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized RFC datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text try: parsed_date = email.utils.parsedate_tz(attr) # type: ignore date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) ) if not date_obj.tzinfo: date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_iso(attr): """Deserialize ISO-8601 formatted string into Datetime object. :param str attr: response string to be deserialized. + :return: Deserialized ISO datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1974,8 +2009,7 @@ def deserialize_iso(attr): except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj @staticmethod def deserialize_unix(attr): @@ -1983,8 +2017,9 @@ def deserialize_unix(attr): This is represented as seconds. :param int attr: Object to be serialized. + :return: Deserialized datetime :rtype: Datetime - :raises: DeserializationError if format invalid + :raises DeserializationError: if format invalid """ if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore @@ -1994,5 +2029,4 @@ def deserialize_unix(attr): except ValueError as err: msg = "Cannot deserialize to unix datetime object." raise DeserializationError(msg) from err - else: - return date_obj + return date_obj diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_vendor.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/utils.py similarity index 71% rename from sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_vendor.py rename to sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/utils.py index 2671426c897b..927adb7c8ae2 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_vendor.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_utils/utils.py @@ -6,33 +6,23 @@ # -------------------------------------------------------------------------- from abc import ABC -from typing import Optional, TYPE_CHECKING +from typing import Generic, Optional, TYPE_CHECKING, TypeVar from azure.core import MatchConditions -from ._configuration import JobRouterAdministrationClientConfiguration, JobRouterClientConfiguration - if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import PipelineClient - - from ._serialization import Deserializer, Serializer - + from .serialization import Deserializer, Serializer -class JobRouterAdministrationClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - _client: "PipelineClient" - _config: JobRouterAdministrationClientConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" +TClient = TypeVar("TClient") +TConfig = TypeVar("TConfig") -class JobRouterClientMixinABC(ABC): +class ClientMixinABC(ABC, Generic[TClient, TConfig]): """DO NOT use this class. It is for internal typing use only.""" - _client: "PipelineClient" - _config: JobRouterClientConfiguration + _client: TClient + _config: TConfig _serialize: "Serializer" _deserialize: "Deserializer" diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_version.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_version.py index f6cd39818b76..a1f432eddc4e 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_version.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.1.0b2" +VERSION = "1.1.0b1" diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/__init__.py index 2cad3c9bd6b0..a00bc5c726de 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/__init__.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/__init__.py @@ -5,13 +5,19 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._patch import JobRouterAdministrationClient -from ._patch import JobRouterClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import JobRouterAdministrationClient # type: ignore +from ._client import JobRouterClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk @@ -20,6 +26,6 @@ "JobRouterAdministrationClient", "JobRouterClient", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_client.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_client.py index ddf6e6531806..bdac771760d0 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_client.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_client.py @@ -7,35 +7,38 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable +from typing import Any, Awaitable, TYPE_CHECKING +from typing_extensions import Self from azure.core import AsyncPipelineClient from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest -from .._serialization import Deserializer, Serializer +from .._utils.serialization import Deserializer, Serializer from ._configuration import JobRouterAdministrationClientConfiguration, JobRouterClientConfiguration from ._operations import JobRouterAdministrationClientOperationsMixin, JobRouterClientOperationsMixin +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential -class JobRouterAdministrationClient( - JobRouterAdministrationClientOperationsMixin -): # pylint: disable=client-accepts-api-version-keyword + +class JobRouterAdministrationClient(JobRouterAdministrationClientOperationsMixin): """JobRouterAdministrationClient. :param endpoint: Uri of your Communication resource. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential :keyword api_version: The API version to use for this operation. Default value is "2024-01-18-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, **kwargs: Any - ) -> None: + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: _endpoint = "{endpoint}" - self._config = JobRouterAdministrationClientConfiguration(endpoint=endpoint, **kwargs) + self._config = JobRouterAdministrationClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -81,7 +84,7 @@ def send_request( request_copy = deepcopy(request) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) @@ -90,7 +93,7 @@ def send_request( async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "JobRouterAdministrationClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self @@ -98,22 +101,23 @@ async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) -class JobRouterClient(JobRouterClientOperationsMixin): # pylint: disable=client-accepts-api-version-keyword +class JobRouterClient(JobRouterClientOperationsMixin): """JobRouterClient. :param endpoint: Uri of your Communication resource. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential :keyword api_version: The API version to use for this operation. Default value is "2024-01-18-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__( # pylint: disable=missing-client-constructor-parameter-credential - self, endpoint: str, **kwargs: Any - ) -> None: + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: _endpoint = "{endpoint}" - self._config = JobRouterClientConfiguration(endpoint=endpoint, **kwargs) + self._config = JobRouterClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) + _policies = kwargs.pop("policies", None) if _policies is None: _policies = [ @@ -159,7 +163,7 @@ def send_request( request_copy = deepcopy(request) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) @@ -168,7 +172,7 @@ def send_request( async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "JobRouterClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_configuration.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_configuration.py index 038bdbcfaf66..0735799eaf48 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_configuration.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_configuration.py @@ -6,12 +6,15 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from typing import Any +from typing import Any, TYPE_CHECKING from azure.core.pipeline import policies from .._version import VERSION +if TYPE_CHECKING: + from azure.core.credentials_async import AsyncTokenCredential + class JobRouterAdministrationClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for JobRouterAdministrationClient. @@ -21,20 +24,26 @@ class JobRouterAdministrationClientConfiguration: # pylint: disable=too-many-in :param endpoint: Uri of your Communication resource. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential :keyword api_version: The API version to use for this operation. Default value is "2024-01-18-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, endpoint: str, **kwargs: Any) -> None: + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: api_version: str = kwargs.pop("api_version", "2024-01-18-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") self.endpoint = endpoint + self.credential = credential self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://communication.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "communication-jobrouter/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) @@ -49,9 +58,13 @@ def _configure(self, **kwargs: Any) -> None: self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) -class JobRouterClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long +class JobRouterClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for JobRouterClient. Note that all parameters used to create this instance are saved as instance @@ -59,20 +72,26 @@ class JobRouterClientConfiguration: # pylint: disable=too-many-instance-attribu :param endpoint: Uri of your Communication resource. Required. :type endpoint: str + :param credential: Credential used to authenticate requests to the service. Required. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential :keyword api_version: The API version to use for this operation. Default value is "2024-01-18-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, endpoint: str, **kwargs: Any) -> None: + def __init__(self, endpoint: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: api_version: str = kwargs.pop("api_version", "2024-01-18-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") self.endpoint = endpoint + self.credential = credential self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://communication.azure.com/.default"]) kwargs.setdefault("sdk_moniker", "communication-jobrouter/{}".format(VERSION)) self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) @@ -87,3 +106,7 @@ def _configure(self, **kwargs: Any) -> None: self.redirect_policy = kwargs.get("redirect_policy") or policies.AsyncRedirectPolicy(**kwargs) self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.AsyncBearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/__init__.py index 06eb1614ceb7..462bfe7de7f9 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/__init__.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/__init__.py @@ -5,17 +5,23 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._patch import JobRouterAdministrationClientOperationsMixin -from ._patch import JobRouterClientOperationsMixin +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import JobRouterAdministrationClientOperationsMixin # type: ignore +from ._operations import JobRouterClientOperationsMixin # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "JobRouterAdministrationClientOperationsMixin", "JobRouterClientOperationsMixin", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py index ce08bff0ad1d..5d753376df55 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_operations.py @@ -1,4 +1,4 @@ -# pylint: disable=too-many-lines,too-many-statements +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -6,14 +6,14 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from collections.abc import MutableMapping import datetime from io import IOBase import json -import sys -from typing import Any, Callable, Dict, IO, List, Optional, TypeVar, Union, overload +from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, overload import urllib.parse -from azure.core import MatchConditions +from azure.core import AsyncPipelineClient, MatchConditions from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( ClientAuthenticationError, @@ -22,6 +22,8 @@ ResourceModifiedError, ResourceNotFoundError, ResourceNotModifiedError, + StreamClosedError, + StreamConsumedError, map_error, ) from azure.core.pipeline import PipelineResponse @@ -31,7 +33,6 @@ from azure.core.utils import case_insensitive_dict from ... import models as _models -from ..._model_base import SdkJSONEncoder, _deserialize from ..._operations._operations import ( build_job_router_accept_job_offer_request, build_job_router_administration_delete_classification_policy_request, @@ -67,20 +68,19 @@ build_job_router_upsert_job_request, build_job_router_upsert_worker_request, ) -from .._vendor import JobRouterAdministrationClientMixinABC, JobRouterClientMixinABC +from ..._utils.model_base import SdkJSONEncoder, _deserialize +from ..._utils.utils import ClientMixinABC +from .._configuration import JobRouterAdministrationClientConfiguration, JobRouterClientConfiguration -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object +JSON = MutableMapping[str, Any] T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class JobRouterAdministrationClientOperationsMixin( # pylint: disable=name-too-long - JobRouterAdministrationClientMixinABC + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], JobRouterAdministrationClientConfiguration] ): + @overload async def upsert_distribution_policy( self, @@ -93,7 +93,6 @@ async def upsert_distribution_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.DistributionPolicy: - # pylint: disable=line-too-long """Creates or updates a distribution policy. Creates or updates a distribution policy. @@ -116,243 +115,6 @@ async def upsert_distribution_policy( :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DistributionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ @overload @@ -367,7 +129,6 @@ async def upsert_distribution_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.DistributionPolicy: - # pylint: disable=line-too-long """Creates or updates a distribution policy. Creates or updates a distribution policy. @@ -390,162 +151,6 @@ async def upsert_distribution_policy( :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DistributionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ @overload @@ -560,7 +165,6 @@ async def upsert_distribution_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.DistributionPolicy: - # pylint: disable=line-too-long """Creates or updates a distribution policy. Creates or updates a distribution policy. @@ -583,162 +187,6 @@ async def upsert_distribution_policy( :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DistributionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ @distributed_trace_async @@ -752,7 +200,6 @@ async def upsert_distribution_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.DistributionPolicy: - # pylint: disable=line-too-long """Creates or updates a distribution policy. Creates or updates a distribution policy. @@ -773,245 +220,8 @@ async def upsert_distribution_policy( :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DistributionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1050,7 +260,7 @@ async def upsert_distribution_policy( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -1063,28 +273,21 @@ async def upsert_distribution_policy( if response.status_code not in [200, 201]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.DistributionPolicy, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.DistributionPolicy, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.DistributionPolicy, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -1093,7 +296,6 @@ async def upsert_distribution_policy( @distributed_trace_async async def get_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) -> _models.DistributionPolicy: - # pylint: disable=line-too-long """Retrieves an existing distribution policy by Id. Retrieves an existing distribution policy by Id. @@ -1103,93 +305,8 @@ async def get_distribution_policy(self, distribution_policy_id: str, **kwargs: A :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DistributionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1209,7 +326,7 @@ async def get_distribution_policy(self, distribution_policy_id: str, **kwargs: A params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -1222,7 +339,10 @@ async def get_distribution_policy(self, distribution_policy_id: str, **kwargs: A if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1240,10 +360,8 @@ async def get_distribution_policy(self, distribution_policy_id: str, **kwargs: A return deserialized # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace - def list_distribution_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.DistributionPolicy"]: - # pylint: disable=line-too-long + def list_distribution_policies(self, **kwargs: Any) -> AsyncIterable["_models.DistributionPolicy"]: """Retrieves existing distribution policies. Retrieves existing distribution policies. @@ -1252,91 +370,6 @@ def list_distribution_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.D :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.DistributionPolicy] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "bestWorker": - distribution_mode = { - "kind": "bestWorker", - "bypassSelectors": bool, # Optional. If set to true, then router will match - workers to jobs even if they don't match label selectors. Warning: You may get - workers that are not qualified for a job they are matched with if you set this - variable to true. This flag is intended more for temporary usage. By default, set - to false. - "maxConcurrentOffers": 0, # Optional. Governs the maximum number of active - concurrent offers a job can have. - "minConcurrentOffers": 0, # Optional. Governs the minimum desired number of - active concurrent offers a job can have. - "scoringRule": router_rule, - "scoringRuleOptions": { - "batchSize": 0, # Optional. Set batch size when - 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. - "descendingOrder": bool, # Optional. If false, will sort scores by - ascending order. By default, set to true. - "isBatchScoringEnabled": bool, # Optional. If set to true, will - score workers in batches, and the parameter name of the worker labels will be - sent as ``workers``. By default, set to false and the parameter name for the - worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' - to set batch size. - "scoringParameters": [ - "str" # Optional. List of extra parameters from a job that - will be sent as part of the payload to scoring rule. If not set, a job's - labels (sent in the payload as ``job``"" ) and a job's worker selectors - (sent in the payload as ``selectors``"" ) are added to the payload of the - scoring rule by default. Note: Worker labels are always sent with scoring - payload. - ] - } - } - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a distribution policy. Required. - "mode": distribution_mode, - "name": "str", # Optional. Friendly name of this policy. - "offerExpiresAfterSeconds": 0.0 # Optional. Number of seconds after which - any offers created under this policy will be expired. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -1344,7 +377,7 @@ def list_distribution_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.D maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.DistributionPolicy]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1362,9 +395,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -1382,9 +413,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -1392,7 +421,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.DistributionPolicy], deserialized["value"]) + list_of_elem = _deserialize(List[_models.DistributionPolicy], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -1407,8 +436,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1417,9 +444,7 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def delete_distribution_policy( # pylint: disable=inconsistent-return-statements - self, distribution_policy_id: str, **kwargs: Any - ) -> None: + async def delete_distribution_policy(self, distribution_policy_id: str, **kwargs: Any) -> None: """Delete a distribution policy by Id. Delete a distribution policy by Id. @@ -1430,7 +455,7 @@ async def delete_distribution_policy( # pylint: disable=inconsistent-return-sta :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -1450,7 +475,7 @@ async def delete_distribution_policy( # pylint: disable=inconsistent-return-sta params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -1462,8 +487,6 @@ async def delete_distribution_policy( # pylint: disable=inconsistent-return-sta response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -1482,7 +505,6 @@ async def upsert_classification_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.ClassificationPolicy: - # pylint: disable=line-too-long """Creates or updates a classification policy. Creates or updates a classification policy. @@ -1505,192 +527,6 @@ async def upsert_classification_policy( :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ @overload @@ -1705,7 +541,6 @@ async def upsert_classification_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.ClassificationPolicy: - # pylint: disable=line-too-long """Creates or updates a classification policy. Creates or updates a classification policy. @@ -1728,126 +563,6 @@ async def upsert_classification_policy( :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ @overload @@ -1862,7 +577,6 @@ async def upsert_classification_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.ClassificationPolicy: - # pylint: disable=line-too-long """Creates or updates a classification policy. Creates or updates a classification policy. @@ -1885,126 +599,6 @@ async def upsert_classification_policy( :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ @distributed_trace_async @@ -2018,7 +612,6 @@ async def upsert_classification_policy( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.ClassificationPolicy: - # pylint: disable=line-too-long """Creates or updates a classification policy. Creates or updates a classification policy. @@ -2039,194 +632,8 @@ async def upsert_classification_policy( :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2265,7 +672,7 @@ async def upsert_classification_policy( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -2278,28 +685,21 @@ async def upsert_classification_policy( if response.status_code not in [200, 201]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.ClassificationPolicy, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.ClassificationPolicy, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ClassificationPolicy, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2310,7 +710,6 @@ async def upsert_classification_policy( async def get_classification_policy( self, classification_policy_id: str, **kwargs: Any ) -> _models.ClassificationPolicy: - # pylint: disable=line-too-long """Retrieves an existing classification policy by Id. Retrieves an existing classification policy by Id. @@ -2320,78 +719,8 @@ async def get_classification_policy( :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2411,7 +740,7 @@ async def get_classification_policy( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -2424,7 +753,10 @@ async def get_classification_policy( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -2442,10 +774,8 @@ async def get_classification_policy( return deserialized # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace - def list_classification_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.ClassificationPolicy"]: - # pylint: disable=line-too-long + def list_classification_policies(self, **kwargs: Any) -> AsyncIterable["_models.ClassificationPolicy"]: """Retrieves existing classification policies. Retrieves existing classification policies. @@ -2454,76 +784,6 @@ def list_classification_policies(self, **kwargs: Any) -> AsyncItemPaged["_models :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.ClassificationPolicy] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "directMap": - router_rule = { - "kind": "directMap" - } - - # JSON input template for discriminator value "expression": - router_rule = { - "expression": "str", # An expression to evaluate. Should contain return - statement with calculated values. Required. - "kind": "expression", - "language": "str" # Optional. The expression language to compile to and - execute. "powerFx" - } - - # JSON input template for discriminator value "function": - router_rule = { - "functionUri": "str", # URL for Azure Function. Required. - "kind": "function", - "credential": { - "appKey": "str", # Optional. Access key scoped to a Azure Function - app. This key grants access to all functions under the app. - "clientId": "str", # Optional. Client id, when AppKey is provided In - context of Azure function, this is usually the name of the key. - "functionKey": "str" # Optional. Access key scoped to a particular - function. - } - } - - # JSON input template for discriminator value "static": - router_rule = { - "kind": "static", - "value": {} # Optional. The static value this rule always returns. Values - must be primitive values - number, string, boolean. - } - - # JSON input template for discriminator value "webhook": - router_rule = { - "kind": "webhook", - "authorizationServerUri": "str", # Optional. Uri for Authorization Server. - "clientCredential": { - "clientId": "str", # Optional. ClientId for Contoso Authorization - server. - "clientSecret": "str" # Optional. Client secret for Contoso - Authorization server. - }, - "webhookUri": "str" # Optional. Uri for Contoso's Web Server. - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a classification policy. Required. - "fallbackQueueId": "str", # Optional. Id of a fallback queue to select if - queue selector attachments doesn't find a match. - "name": "str", # Optional. Friendly name of this policy. - "prioritizationRule": router_rule, - "queueSelectorAttachments": [ - queue_selector_attachment - ], - "workerSelectorAttachments": [ - worker_selector_attachment - ] - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -2531,7 +791,7 @@ def list_classification_policies(self, **kwargs: Any) -> AsyncItemPaged["_models maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.ClassificationPolicy]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2549,9 +809,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -2569,9 +827,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -2579,7 +835,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.ClassificationPolicy], deserialized["value"]) + list_of_elem = _deserialize(List[_models.ClassificationPolicy], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -2594,8 +850,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -2604,9 +858,7 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def delete_classification_policy( # pylint: disable=inconsistent-return-statements - self, classification_policy_id: str, **kwargs: Any - ) -> None: + async def delete_classification_policy(self, classification_policy_id: str, **kwargs: Any) -> None: """Delete a classification policy by Id. Delete a classification policy by Id. @@ -2617,7 +869,7 @@ async def delete_classification_policy( # pylint: disable=inconsistent-return-s :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2637,7 +889,7 @@ async def delete_classification_policy( # pylint: disable=inconsistent-return-s params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -2649,8 +901,6 @@ async def delete_classification_policy( # pylint: disable=inconsistent-return-s response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -2691,41 +941,6 @@ async def upsert_exception_policy( :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ @overload @@ -2762,25 +977,6 @@ async def upsert_exception_policy( :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ @overload @@ -2817,25 +1013,6 @@ async def upsert_exception_policy( :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ @distributed_trace_async @@ -2869,43 +1046,8 @@ async def upsert_exception_policy( :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -2944,7 +1086,7 @@ async def upsert_exception_policy( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -2957,28 +1099,21 @@ async def upsert_exception_policy( if response.status_code not in [200, 201]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.ExceptionPolicy, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.ExceptionPolicy, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.ExceptionPolicy, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -2996,27 +1131,8 @@ async def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3036,7 +1152,7 @@ async def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3049,7 +1165,10 @@ async def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3067,9 +1186,8 @@ async def get_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> return deserialized # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace - def list_exception_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.ExceptionPolicy"]: + def list_exception_policies(self, **kwargs: Any) -> AsyncIterable["_models.ExceptionPolicy"]: """Retrieves existing exception policies. Retrieves existing exception policies. @@ -3078,25 +1196,6 @@ def list_exception_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.Exce :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.ExceptionPolicy] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of an exception policy. Required. - "exceptionRules": [ - { - "actions": [ - exception_action - ], - "id": "str", # Id of an exception rule. Required. - "trigger": exception_trigger - } - ], - "name": "str" # Optional. Friendly name of this policy. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -3104,7 +1203,7 @@ def list_exception_policies(self, **kwargs: Any) -> AsyncItemPaged["_models.Exce maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.ExceptionPolicy]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3122,9 +1221,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3142,9 +1239,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3152,7 +1247,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.ExceptionPolicy], deserialized["value"]) + list_of_elem = _deserialize(List[_models.ExceptionPolicy], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -3167,8 +1262,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3177,9 +1270,7 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def delete_exception_policy( # pylint: disable=inconsistent-return-statements - self, exception_policy_id: str, **kwargs: Any - ) -> None: + async def delete_exception_policy(self, exception_policy_id: str, **kwargs: Any) -> None: """Deletes a exception policy by Id. Deletes a exception policy by Id. @@ -3190,7 +1281,7 @@ async def delete_exception_policy( # pylint: disable=inconsistent-return-statem :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3210,7 +1301,7 @@ async def delete_exception_policy( # pylint: disable=inconsistent-return-statem params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3222,8 +1313,6 @@ async def delete_exception_policy( # pylint: disable=inconsistent-return-statem response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3242,7 +1331,6 @@ async def upsert_queue( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterQueue: - # pylint: disable=line-too-long """Creates or updates a queue. Creates or updates a queue. @@ -3264,42 +1352,7 @@ async def upsert_queue( :paramtype match_condition: ~azure.core.MatchConditions :return: RouterQueue. The RouterQueue is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } + :raises ~azure.core.exceptions.HttpResponseError: """ @overload @@ -3314,7 +1367,6 @@ async def upsert_queue( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterQueue: - # pylint: disable=line-too-long """Creates or updates a queue. Creates or updates a queue. @@ -3337,25 +1389,6 @@ async def upsert_queue( :return: RouterQueue. The RouterQueue is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueue :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } """ @overload @@ -3370,7 +1403,6 @@ async def upsert_queue( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterQueue: - # pylint: disable=line-too-long """Creates or updates a queue. Creates or updates a queue. @@ -3393,25 +1425,6 @@ async def upsert_queue( :return: RouterQueue. The RouterQueue is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueue :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } """ @distributed_trace_async @@ -3425,7 +1438,6 @@ async def upsert_queue( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterQueue: - # pylint: disable=line-too-long """Creates or updates a queue. Creates or updates a queue. @@ -3446,43 +1458,8 @@ async def upsert_queue( :return: RouterQueue. The RouterQueue is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueue :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3521,7 +1498,7 @@ async def upsert_queue( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3534,28 +1511,21 @@ async def upsert_queue( if response.status_code not in [200, 201]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterQueue, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterQueue, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.RouterQueue, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -3564,7 +1534,6 @@ async def upsert_queue( @distributed_trace_async async def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue: - # pylint: disable=line-too-long """Retrieves an existing queue by Id. Retrieves an existing queue by Id. @@ -3574,27 +1543,8 @@ async def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue: :return: RouterQueue. The RouterQueue is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueue :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3614,7 +1564,7 @@ async def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue: params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3627,7 +1577,10 @@ async def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue: if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3645,10 +1598,8 @@ async def get_queue(self, queue_id: str, **kwargs: Any) -> _models.RouterQueue: return deserialized # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace - def list_queues(self, **kwargs: Any) -> AsyncItemPaged["_models.RouterQueue"]: - # pylint: disable=line-too-long + def list_queues(self, **kwargs: Any) -> AsyncIterable["_models.RouterQueue"]: """Retrieves existing queues. Retrieves existing queues. @@ -3657,25 +1608,6 @@ def list_queues(self, **kwargs: Any) -> AsyncItemPaged["_models.RouterQueue"]: :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterQueue] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a queue. Required. - "distributionPolicyId": "str", # Optional. Id of a distribution policy that - will determine how a job is distributed to workers. - "exceptionPolicyId": "str", # Optional. Id of an exception policy that - determines various job escalation rules. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "name": "str" # Optional. Friendly name of this queue. - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -3683,7 +1615,7 @@ def list_queues(self, **kwargs: Any) -> AsyncItemPaged["_models.RouterQueue"]: maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.RouterQueue]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3701,9 +1633,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3721,9 +1651,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3731,7 +1659,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.RouterQueue], deserialized["value"]) + list_of_elem = _deserialize(List[_models.RouterQueue], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -3746,8 +1674,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3756,9 +1682,7 @@ async def get_next(next_link=None): return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def delete_queue( # pylint: disable=inconsistent-return-statements - self, queue_id: str, **kwargs: Any - ) -> None: + async def delete_queue(self, queue_id: str, **kwargs: Any) -> None: """Deletes a queue by Id. Deletes a queue by Id. @@ -3769,7 +1693,7 @@ async def delete_queue( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -3789,7 +1713,7 @@ async def delete_queue( # pylint: disable=inconsistent-return-statements params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -3801,8 +1725,6 @@ async def delete_queue( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -3810,7 +1732,10 @@ async def delete_queue( # pylint: disable=inconsistent-return-statements return cls(pipeline_response, None, {}) # type: ignore -class JobRouterClientOperationsMixin(JobRouterClientMixinABC): +class JobRouterClientOperationsMixin( + ClientMixinABC[AsyncPipelineClient[HttpRequest, AsyncHttpResponse], JobRouterClientConfiguration] +): + @overload async def upsert_job( self, @@ -3823,7 +1748,6 @@ async def upsert_job( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterJob: - # pylint: disable=line-too-long """Creates or updates a router job. Creates or updates a router job. @@ -3846,256 +1770,6 @@ async def upsert_job( :return: RouterJob. The RouterJob is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJob :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ @overload @@ -4110,7 +1784,6 @@ async def upsert_job( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterJob: - # pylint: disable=line-too-long """Creates or updates a router job. Creates or updates a router job. @@ -4133,142 +1806,6 @@ async def upsert_job( :return: RouterJob. The RouterJob is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJob :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ @overload @@ -4283,7 +1820,6 @@ async def upsert_job( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterJob: - # pylint: disable=line-too-long """Creates or updates a router job. Creates or updates a router job. @@ -4306,142 +1842,6 @@ async def upsert_job( :return: RouterJob. The RouterJob is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJob :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ @distributed_trace_async @@ -4455,7 +1855,6 @@ async def upsert_job( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterJob: - # pylint: disable=line-too-long """Creates or updates a router job. Creates or updates a router job. @@ -4476,258 +1875,8 @@ async def upsert_job( :return: RouterJob. The RouterJob is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJob :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4766,7 +1915,7 @@ async def upsert_job( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -4779,28 +1928,21 @@ async def upsert_job( if response.status_code not in [200, 201]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterJob, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterJob, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.RouterJob, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -4809,7 +1951,6 @@ async def upsert_job( @distributed_trace_async async def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob: - # pylint: disable=line-too-long """Retrieves an existing job by Id. Retrieves an existing job by Id. @@ -4819,126 +1960,8 @@ async def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob: :return: RouterJob. The RouterJob is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJob :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -4958,7 +1981,7 @@ async def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob: params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -4971,7 +1994,10 @@ async def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob: if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -4990,7 +2016,7 @@ async def get_job(self, job_id: str, **kwargs: Any) -> _models.RouterJob: return deserialized # type: ignore @distributed_trace_async - async def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + async def delete_job(self, job_id: str, **kwargs: Any) -> None: """Deletes a job and all of its traces. Deletes a job and all of its traces. @@ -5001,7 +2027,7 @@ async def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disab :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5021,7 +2047,7 @@ async def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disab params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -5033,8 +2059,6 @@ async def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disab response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -5042,32 +2066,30 @@ async def delete_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disab return cls(pipeline_response, None, {}) # type: ignore @overload - async def _reclassify_job( # pylint: disable=protected-access + async def _reclassify_job( self, job_id: str, options: Optional[_models._models.ReclassifyJobOptions] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: ... - + ) -> _models.ReclassifyJobResult: ... @overload - async def _reclassify_job( # pylint: disable=protected-access + async def _reclassify_job( self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: ... - + ) -> _models.ReclassifyJobResult: ... @overload - async def _reclassify_job( # pylint: disable=protected-access + async def _reclassify_job( self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.ReclassifyJobResult: ... + ) -> _models.ReclassifyJobResult: ... @distributed_trace_async - async def _reclassify_job( # pylint: disable=protected-access + async def _reclassify_job( self, job_id: str, options: Optional[Union[_models._models.ReclassifyJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any - ) -> _models._models.ReclassifyJobResult: + ) -> _models.ReclassifyJobResult: """Reclassify a job. Reclassify a job. @@ -5076,18 +2098,13 @@ async def _reclassify_job( # pylint: disable=protected-access :type job_id: str :param options: Request object for reclassifying a job. Is one of the following types: ReclassifyJobOptions, JSON, IO[bytes] Default value is None. - :type options: ~azure.communication.jobrouter.models.ReclassifyJobOptions or JSON or IO[bytes] + :type options: ~azure.communication.jobrouter.models._models.ReclassifyJobOptions or JSON or + IO[bytes] :return: ReclassifyJobResult. The ReclassifyJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.ReclassifyJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = {} """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5099,7 +2116,7 @@ async def _reclassify_job( # pylint: disable=protected-access _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models._models.ReclassifyJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[_models.ReclassifyJobResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -5120,7 +2137,7 @@ async def _reclassify_job( # pylint: disable=protected-access params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -5133,16 +2150,17 @@ async def _reclassify_job( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.ReclassifyJobResult, response.json() # pylint: disable=protected-access - ) + deserialized = _deserialize(_models.ReclassifyJobResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5150,30 +2168,27 @@ async def _reclassify_job( # pylint: disable=protected-access return deserialized # type: ignore @overload - async def _cancel_job( # pylint: disable=protected-access + async def _cancel_job( self, job_id: str, options: Optional[_models.CancelJobOptions] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: ... - + ) -> _models.CancelJobResult: ... @overload - async def _cancel_job( # pylint: disable=protected-access + async def _cancel_job( self, job_id: str, options: Optional[JSON] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: ... - + ) -> _models.CancelJobResult: ... @overload - async def _cancel_job( # pylint: disable=protected-access + async def _cancel_job( self, job_id: str, options: Optional[IO[bytes]] = None, *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CancelJobResult: ... + ) -> _models.CancelJobResult: ... @distributed_trace_async - async def _cancel_job( # pylint: disable=protected-access + async def _cancel_job( self, job_id: str, options: Optional[Union[_models.CancelJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any - ) -> _models._models.CancelJobResult: - # pylint: disable=line-too-long + ) -> _models.CancelJobResult: """Submits request to cancel an existing job by Id while supplying free-form cancellation reason. Submits request to cancel an existing job by Id while supplying free-form cancellation reason. @@ -5186,20 +2201,8 @@ async def _cancel_job( # pylint: disable=protected-access :return: CancelJobResult. The CancelJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.CancelJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "dispositionCode": "str", # Optional. Indicates the outcome of a job, - populate this field with your own custom values. If not provided, default value - of "Cancelled" is set. - "note": "str" # Optional. A note that will be appended to a job's Notes - collection with the current timestamp. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5211,7 +2214,7 @@ async def _cancel_job( # pylint: disable=protected-access _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models._models.CancelJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[_models.CancelJobResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -5232,7 +2235,7 @@ async def _cancel_job( # pylint: disable=protected-access params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -5245,16 +2248,17 @@ async def _cancel_job( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.CancelJobResult, response.json() # pylint: disable=protected-access - ) + deserialized = _deserialize(_models.CancelJobResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5262,7 +2266,7 @@ async def _cancel_job( # pylint: disable=protected-access return deserialized # type: ignore @overload - async def _complete_job( # pylint: disable=protected-access + async def _complete_job( self, job_id: str, assignment_id: str, @@ -5270,10 +2274,9 @@ async def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: ... - + ) -> _models.CompleteJobResult: ... @overload - async def _complete_job( # pylint: disable=protected-access + async def _complete_job( self, job_id: str, assignment_id: str, @@ -5281,10 +2284,9 @@ async def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: ... - + ) -> _models.CompleteJobResult: ... @overload - async def _complete_job( # pylint: disable=protected-access + async def _complete_job( self, job_id: str, assignment_id: str, @@ -5292,16 +2294,16 @@ async def _complete_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CompleteJobResult: ... + ) -> _models.CompleteJobResult: ... @distributed_trace_async - async def _complete_job( # pylint: disable=protected-access + async def _complete_job( self, job_id: str, assignment_id: str, options: Optional[Union[_models.CompleteJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any - ) -> _models._models.CompleteJobResult: + ) -> _models.CompleteJobResult: """Completes an assigned job. Completes an assigned job. @@ -5316,17 +2318,8 @@ async def _complete_job( # pylint: disable=protected-access :return: CompleteJobResult. The CompleteJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.CompleteJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "note": "str" # Optional. A note that will be appended to a job's Notes - collection with the current timestamp. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5338,7 +2331,7 @@ async def _complete_job( # pylint: disable=protected-access _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models._models.CompleteJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[_models.CompleteJobResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -5360,7 +2353,7 @@ async def _complete_job( # pylint: disable=protected-access params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -5373,16 +2366,17 @@ async def _complete_job( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.CompleteJobResult, response.json() # pylint: disable=protected-access - ) + deserialized = _deserialize(_models.CompleteJobResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -5390,7 +2384,7 @@ async def _complete_job( # pylint: disable=protected-access return deserialized # type: ignore @overload - async def _close_job( # pylint: disable=protected-access + async def _close_job( self, job_id: str, assignment_id: str, @@ -5398,10 +2392,9 @@ async def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: ... - + ) -> _models.CloseJobResult: ... @overload - async def _close_job( # pylint: disable=protected-access + async def _close_job( self, job_id: str, assignment_id: str, @@ -5409,10 +2402,9 @@ async def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: ... - + ) -> _models.CloseJobResult: ... @overload - async def _close_job( # pylint: disable=protected-access + async def _close_job( self, job_id: str, assignment_id: str, @@ -5420,17 +2412,16 @@ async def _close_job( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.CloseJobResult: ... + ) -> _models.CloseJobResult: ... @distributed_trace_async - async def _close_job( # pylint: disable=protected-access + async def _close_job( self, job_id: str, assignment_id: str, options: Optional[Union[_models.CloseJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any - ) -> _models._models.CloseJobResult: - # pylint: disable=line-too-long + ) -> _models.CloseJobResult: """Closes a completed job. Closes a completed job. @@ -5445,23 +2436,8 @@ async def _close_job( # pylint: disable=protected-access :return: CloseJobResult. The CloseJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.CloseJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "closeAt": "2020-02-20 00:00:00", # Optional. If not provided, worker - capacity is released immediately along with a JobClosedEvent notification. If - provided, worker capacity is released along with a JobClosedEvent notification at - a future time in UTC. - "dispositionCode": "str", # Optional. Indicates the outcome of a job, - populate this field with your own custom values. - "note": "str" # Optional. A note that will be appended to a job's Notes - collection with the current timestamp. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5473,7 +2449,7 @@ async def _close_job( # pylint: disable=protected-access _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models._models.CloseJobResult] = kwargs.pop("cls", None) # pylint: disable=protected-access + cls: ClsType[_models.CloseJobResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -5495,7 +2471,7 @@ async def _close_job( # pylint: disable=protected-access params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -5508,23 +2484,23 @@ async def _close_job( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.CloseJobResult, response.json() # pylint: disable=protected-access - ) + deserialized = _deserialize(_models.CloseJobResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore return deserialized # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace def list_jobs( self, @@ -5536,8 +2512,7 @@ def list_jobs( scheduled_before: Optional[datetime.datetime] = None, scheduled_after: Optional[datetime.datetime] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.RouterJob"]: - # pylint: disable=line-too-long + ) -> AsyncIterable["_models.RouterJob"]: """Retrieves list of jobs based on filter parameters. Retrieves list of jobs based on filter parameters. @@ -5564,124 +2539,6 @@ def list_jobs( :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterJob] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # The response is polymorphic. The following are possible polymorphic responses based - off discriminator "kind": - - # JSON input template for discriminator value "queueAndMatch": - job_matching_mode = { - "kind": "queueAndMatch" - } - - # JSON input template for discriminator value "scheduleAndSuspend": - job_matching_mode = { - "kind": "scheduleAndSuspend", - "scheduleAt": "2020-02-20 00:00:00" # Requested schedule time. Required. - } - - # JSON input template for discriminator value "suspend": - job_matching_mode = { - "kind": "suspend" - } - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a job. Required. - "assignments": { - "str": { - "assignedAt": "2020-02-20 00:00:00", # Timestamp when the - job was assigned to a worker in UTC. Required. - "assignmentId": "str", # Id of a job assignment. Required. - "closedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as closed after being completed in UTC. - "completedAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the job was marked as completed after being assigned in UTC. - "workerId": "str" # Optional. Id of the Worker assigned to - the job. - } - }, - "attachedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "channelId": "str", # Optional. The channel identifier. eg. voice, chat, - etc. - "channelReference": "str", # Optional. Reference to an external parent - context, eg. call ID. - "classificationPolicyId": "str", # Optional. Id of a classification policy - used for classifying this job. - "dispositionCode": "str", # Optional. Reason code for cancelled or closed - jobs. - "enqueuedAt": "2020-02-20 00:00:00", # Optional. Timestamp a job was queued - in UTC. - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "matchingMode": job_matching_mode, - "notes": [ - { - "message": "str", # The message contained in the note. - Required. - "addedAt": "2020-02-20 00:00:00" # Optional. The time at - which the note was added in UTC. If not provided, will default to the - current time. - } - ], - "priority": 0, # Optional. Priority of this job. - "queueId": "str", # Optional. Id of a queue that this job is queued to. - "requestedWorkerSelectors": [ - { - "key": "str", # The label key to query against. Required. - "labelOperator": "str", # Describes how the value of the - label is compared to the value defined on the worker selector. Required. - Known values are: "equal", "notEqual", "lessThan", "lessThanOrEqual", - "greaterThan", and "greaterThanOrEqual". - "expedite": bool, # Optional. Pushes a job to the front of - the queue as long as this selector is active. - "expiresAfterSeconds": 0.0, # Optional. Describes how long - this label selector is valid in seconds. - "expiresAt": "2020-02-20 00:00:00", # Optional. The time at - which this worker selector expires in UTC. - "status": "str", # Optional. Status of the worker selector. - Known values are: "active" and "expired". - "value": {} # Optional. The value to compare against the - actual label value with the given operator. Values must be primitive - values - number, string, boolean. - } - ], - "scheduledAt": "2020-02-20 00:00:00", # Optional. If set, job will be - scheduled to be enqueued at a given time. - "status": "str", # Optional. The status of the job. Known values are: - "pendingClassification", "queued", "assigned", "completed", "closed", - "cancelled", "classificationFailed", "created", "pendingSchedule", "scheduled", - "scheduleFailed", and "waitingForActivation". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this job. Values must be primitive values - number, string, boolean. - } - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -5689,7 +2546,7 @@ def list_jobs( maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.RouterJob]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5713,9 +2570,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -5733,9 +2588,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -5743,7 +2596,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.RouterJob], deserialized["value"]) + list_of_elem = _deserialize(List[_models.RouterJob], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -5758,8 +2611,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -5779,23 +2630,8 @@ async def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.Router MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterJobPositionDetails :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "estimatedWaitTimeMinutes": 0.0, # Estimated wait time of the job rounded up - to the nearest minute. Required. - "jobId": "str", # Id of the job these details are about. Required. - "position": 0, # Position of the job in question within that queue. - Required. - "queueId": "str", # Id of the queue this job is enqueued in. Required. - "queueLength": 0 # Length of the queue: total number of enqueued jobs. - Required. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -5815,7 +2651,7 @@ async def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.Router params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -5828,7 +2664,10 @@ async def get_queue_position(self, job_id: str, **kwargs: Any) -> _models.Router if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -5852,7 +2691,6 @@ async def unassign_job( content_type: str = "application/json", **kwargs: Any ) -> _models.UnassignJobResult: - # pylint: disable=line-too-long """Unassign a job. Unassign a job. @@ -5869,22 +2707,6 @@ async def unassign_job( :return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.UnassignJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "suspendMatching": bool # Optional. If SuspendMatching is true, then a job - is not queued for re-matching with a worker. - } - - # response body for status code(s): 200 - response == { - "jobId": "str", # Id of an unassigned job. Required. - "unassignmentCount": 0 # The number of times a job is unassigned. At a - maximum 3. Required. - } """ @overload @@ -5913,16 +2735,6 @@ async def unassign_job( :return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.UnassignJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "jobId": "str", # Id of an unassigned job. Required. - "unassignmentCount": 0 # The number of times a job is unassigned. At a - maximum 3. Required. - } """ @overload @@ -5951,16 +2763,6 @@ async def unassign_job( :return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.UnassignJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "jobId": "str", # Id of an unassigned job. Required. - "unassignmentCount": 0 # The number of times a job is unassigned. At a - maximum 3. Required. - } """ @distributed_trace_async @@ -5971,7 +2773,6 @@ async def unassign_job( options: Optional[Union[_models.UnassignJobOptions, JSON, IO[bytes]]] = None, **kwargs: Any ) -> _models.UnassignJobResult: - # pylint: disable=line-too-long """Unassign a job. Unassign a job. @@ -5986,24 +2787,8 @@ async def unassign_job( :return: UnassignJobResult. The UnassignJobResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.UnassignJobResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "suspendMatching": bool # Optional. If SuspendMatching is true, then a job - is not queued for re-matching with a worker. - } - - # response body for status code(s): 200 - response == { - "jobId": "str", # Id of an unassigned job. Required. - "unassignmentCount": 0 # The number of times a job is unassigned. At a - maximum 3. Required. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6037,7 +2822,7 @@ async def unassign_job( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6050,7 +2835,10 @@ async def unassign_job( if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -6079,20 +2867,8 @@ async def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) - :return: AcceptJobOfferResult. The AcceptJobOfferResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.AcceptJobOfferResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "assignmentId": "str", # Id of job assignment that assigns a worker that has - accepted an offer to a job. Required. - "jobId": "str", # Id of the job assigned. Required. - "workerId": "str" # Id of the worker that has been assigned this job. - Required. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6113,7 +2889,7 @@ async def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) - params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6126,7 +2902,10 @@ async def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) - if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -6141,7 +2920,7 @@ async def accept_job_offer(self, worker_id: str, offer_id: str, **kwargs: Any) - return deserialized # type: ignore @overload - async def _decline_job_offer( # pylint: disable=protected-access + async def _decline_job_offer( self, worker_id: str, offer_id: str, @@ -6149,10 +2928,9 @@ async def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: ... - + ) -> _models.DeclineJobOfferResult: ... @overload - async def _decline_job_offer( # pylint: disable=protected-access + async def _decline_job_offer( self, worker_id: str, offer_id: str, @@ -6160,10 +2938,9 @@ async def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: ... - + ) -> _models.DeclineJobOfferResult: ... @overload - async def _decline_job_offer( # pylint: disable=protected-access + async def _decline_job_offer( self, worker_id: str, offer_id: str, @@ -6171,17 +2948,16 @@ async def _decline_job_offer( # pylint: disable=protected-access *, content_type: str = "application/json", **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: ... + ) -> _models.DeclineJobOfferResult: ... @distributed_trace_async - async def _decline_job_offer( # pylint: disable=protected-access + async def _decline_job_offer( self, worker_id: str, offer_id: str, options: Optional[Union[_models.DeclineJobOfferOptions, JSON, IO[bytes]]] = None, **kwargs: Any - ) -> _models._models.DeclineJobOfferResult: - # pylint: disable=line-too-long + ) -> _models.DeclineJobOfferResult: """Declines an offer to work on a job. Declines an offer to work on a job. @@ -6197,21 +2973,8 @@ async def _decline_job_offer( # pylint: disable=protected-access :return: DeclineJobOfferResult. The DeclineJobOfferResult is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.DeclineJobOfferResult :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - options = { - "retryOfferAt": "2020-02-20 00:00:00" # Optional. If the RetryOfferAt is not - provided, then this job will not be offered again to the worker who declined this - job unless the worker is de-registered and re-registered. If a RetryOfferAt time - is provided, then the job will be re-matched to eligible workers at the retry - time in UTC. The worker that declined the job will also be eligible for the job - at that time. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6223,9 +2986,7 @@ async def _decline_job_offer( # pylint: disable=protected-access _params = kwargs.pop("params", {}) or {} content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) - cls: ClsType[_models._models.DeclineJobOfferResult] = kwargs.pop( # pylint: disable=protected-access - "cls", None - ) + cls: ClsType[_models.DeclineJobOfferResult] = kwargs.pop("cls", None) content_type = content_type or "application/json" _content = None @@ -6247,7 +3008,7 @@ async def _decline_job_offer( # pylint: disable=protected-access params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6260,16 +3021,17 @@ async def _decline_job_offer( # pylint: disable=protected-access if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if _stream: deserialized = response.iter_bytes() else: - deserialized = _deserialize( - _models._models.DeclineJobOfferResult, response.json() # pylint: disable=protected-access - ) + deserialized = _deserialize(_models.DeclineJobOfferResult, response.json()) if cls: return cls(pipeline_response, deserialized, {}) # type: ignore @@ -6278,7 +3040,6 @@ async def _decline_job_offer( # pylint: disable=protected-access @distributed_trace_async async def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.RouterQueueStatistics: - # pylint: disable=line-too-long """Retrieves a queue's statistics. Retrieves a queue's statistics. @@ -6288,23 +3049,8 @@ async def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.Ro :return: RouterQueueStatistics. The RouterQueueStatistics is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterQueueStatistics :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "length": 0, # Length of the queue: total number of enqueued jobs. Required. - "queueId": "str", # Id of the queue these details are about. Required. - "estimatedWaitTimeMinutes": { - "str": 0.0 # Optional. The estimated wait time of this queue rounded - up to the nearest minute, grouped by job priority. - }, - "longestJobWaitTimeMinutes": 0.0 # Optional. The wait time of the job that - has been enqueued in this queue for the longest. - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6324,7 +3070,7 @@ async def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.Ro params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6337,7 +3083,10 @@ async def get_queue_statistics(self, queue_id: str, **kwargs: Any) -> _models.Ro if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -6363,7 +3112,6 @@ async def upsert_worker( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterWorker: - # pylint: disable=line-too-long """Creates or updates a worker. Creates or updates a worker. @@ -6386,133 +3134,6 @@ async def upsert_worker( :return: RouterWorker. The RouterWorker is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterWorker :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ @overload @@ -6527,7 +3148,6 @@ async def upsert_worker( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterWorker: - # pylint: disable=line-too-long """Creates or updates a worker. Creates or updates a worker. @@ -6550,71 +3170,6 @@ async def upsert_worker( :return: RouterWorker. The RouterWorker is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterWorker :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ @overload @@ -6629,7 +3184,6 @@ async def upsert_worker( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterWorker: - # pylint: disable=line-too-long """Creates or updates a worker. Creates or updates a worker. @@ -6652,71 +3206,6 @@ async def upsert_worker( :return: RouterWorker. The RouterWorker is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterWorker :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ @distributed_trace_async @@ -6730,7 +3219,6 @@ async def upsert_worker( match_condition: Optional[MatchConditions] = None, **kwargs: Any ) -> _models.RouterWorker: - # pylint: disable=line-too-long """Creates or updates a worker. Creates or updates a worker. @@ -6751,135 +3239,8 @@ async def upsert_worker( :return: RouterWorker. The RouterWorker is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterWorker :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - resource = { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } - - # response body for status code(s): 201, 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -6918,7 +3279,7 @@ async def upsert_worker( params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -6931,28 +3292,21 @@ async def upsert_worker( if response.status_code not in [200, 201]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) response_headers = {} - if response.status_code == 200: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterWorker, response.json()) - - if response.status_code == 201: - response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) - response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) + response_headers["ETag"] = self._deserialize("str", response.headers.get("ETag")) + response_headers["Last-Modified"] = self._deserialize("rfc-1123", response.headers.get("Last-Modified")) - if _stream: - deserialized = response.iter_bytes() - else: - deserialized = _deserialize(_models.RouterWorker, response.json()) + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize(_models.RouterWorker, response.json()) if cls: return cls(pipeline_response, deserialized, response_headers) # type: ignore @@ -6961,7 +3315,6 @@ async def upsert_worker( @distributed_trace_async async def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorker: - # pylint: disable=line-too-long """Retrieves an existing worker by Id. Retrieves an existing worker by Id. @@ -6971,73 +3324,8 @@ async def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorke :return: RouterWorker. The RouterWorker is compatible with MutableMapping :rtype: ~azure.communication.jobrouter.models.RouterWorker :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -7057,7 +3345,7 @@ async def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorke params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7070,7 +3358,10 @@ async def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorke if response.status_code not in [200]: if _stream: - await response.read() # Load the body in memory and close the socket + try: + await response.read() # Load the body in memory and close the socket + except (StreamConsumedError, StreamClosedError): + pass map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) @@ -7089,9 +3380,7 @@ async def get_worker(self, worker_id: str, **kwargs: Any) -> _models.RouterWorke return deserialized # type: ignore @distributed_trace_async - async def delete_worker( # pylint: disable=inconsistent-return-statements - self, worker_id: str, **kwargs: Any - ) -> None: + async def delete_worker(self, worker_id: str, **kwargs: Any) -> None: """Deletes a worker and all of its traces. Deletes a worker and all of its traces. @@ -7102,7 +3391,7 @@ async def delete_worker( # pylint: disable=inconsistent-return-statements :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -7122,7 +3411,7 @@ async def delete_worker( # pylint: disable=inconsistent-return-statements params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7134,15 +3423,12 @@ async def delete_worker( # pylint: disable=inconsistent-return-statements response = pipeline_response.http_response if response.status_code not in [204]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) if cls: return cls(pipeline_response, None, {}) # type: ignore - # https://github.com/Azure/autorest.python/issues/2262 @distributed_trace def list_workers( self, @@ -7152,8 +3438,7 @@ def list_workers( queue_id: Optional[str] = None, has_capacity: Optional[bool] = None, **kwargs: Any - ) -> AsyncItemPaged["_models.RouterWorker"]: - # pylint: disable=line-too-long + ) -> AsyncIterable["_models.RouterWorker"]: """Retrieves existing workers. Retrieves existing workers. @@ -7176,71 +3461,6 @@ def list_workers( :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterWorker] :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "etag": "str", # The entity tag for this resource. Required. - "id": "str", # Id of a worker. Required. - "assignedJobs": [ - { - "assignedAt": "2020-02-20 00:00:00", # The assignment time - of the job in UTC. Required. - "assignmentId": "str", # Id of the assignment. Required. - "capacityCost": 0, # The amount of capacity this assignment - has consumed on the worker. Required. - "jobId": "str" # Id of the job assigned. Required. - } - ], - "availableForOffers": bool, # Optional. A flag indicating this worker is - open to receive offers or not. - "capacity": 0, # Optional. The total capacity score this worker has to - manage multiple concurrent jobs. - "channels": [ - { - "capacityCostPerJob": 0, # The amount of capacity that an - instance of a job of this channel will consume of the total worker - capacity. Required. - "channelId": "str", # Id of a channel. Required. - "maxNumberOfJobs": 0 # Optional. The maximum number of jobs - that can be supported concurrently for this channel. - } - ], - "labels": { - "str": {} # Optional. A set of key/value pairs that are identifying - attributes used by the rules engines to make decisions. Values must be - primitive values - number, string, boolean. - }, - "loadRatio": 0.0, # Optional. A value indicating the workers capacity. A - value of '1' means all capacity is consumed. A value of '0' means no capacity is - currently consumed. - "maxConcurrentOffers": 0, # Optional. If this is set, the worker will only - receive up to this many new offers at a time. - "offers": [ - { - "capacityCost": 0, # The capacity cost consumed by the job - offer. Required. - "jobId": "str", # Id of the job. Required. - "offerId": "str", # Id of an offer. Required. - "expiresAt": "2020-02-20 00:00:00", # Optional. Timestamp - when the offer will expire in UTC. - "offeredAt": "2020-02-20 00:00:00" # Optional. Timestamp - when the offer was created in UTC. - } - ], - "queues": [ - "str" # Optional. Collection of queue(s) that this worker can - receive work from. - ], - "state": "str", # Optional. Current state of a worker. Known values are: - "active", "draining", and "inactive". - "tags": { - "str": {} # Optional. A set of non-identifying attributes attached - to this worker. Values must be primitive values - number, string, boolean. - } - } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} @@ -7248,7 +3468,7 @@ def list_workers( maxpagesize = kwargs.pop("maxpagesize", None) cls: ClsType[List[_models.RouterWorker]] = kwargs.pop("cls", None) - error_map = { + error_map: MutableMapping = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError, @@ -7270,9 +3490,7 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7290,9 +3508,7 @@ def prepare_request(next_link=None): "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params ) path_format_arguments = { - "endpoint": self._serialize.url( - "self._config.endpoint", self._config.endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str"), } _request.url = self._client.format_url(_request.url, **path_format_arguments) @@ -7300,7 +3516,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[_models.RouterWorker], deserialized["value"]) + list_of_elem = _deserialize(List[_models.RouterWorker], deserialized.get("value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("nextLink") or None, AsyncList(list_of_elem) @@ -7315,8 +3531,6 @@ async def get_next(next_link=None): response = pipeline_response.http_response if response.status_code not in [200]: - if _stream: - await response.read() # Load the body in memory and close the socket map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_patch.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_patch.py index dc7e9c9541ff..8bcb627aa475 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_patch.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_operations/_patch.py @@ -1,2122 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -import sys -import datetime -from typing import List, Any, Optional, Dict, Union, overload, IO, Literal +from typing import List -from azure.core import MatchConditions -from azure.core.tracing.decorator import distributed_trace -from azure.core.async_paging import AsyncItemPaged -from azure.core.tracing.decorator_async import distributed_trace_async - -from ... import models as _models -from ._operations import ( - JobRouterClientOperationsMixin as JobRouterClientOperationsMixinGenerated, - JobRouterAdministrationClientOperationsMixin as JobRouterAdministrationClientOperationsMixinGenerated, -) -from ..._model_base import _deserialize_datetime as _convert_str_to_datetime - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore - - -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - - -class JobRouterAdministrationClientOperationsMixin( - JobRouterAdministrationClientOperationsMixinGenerated -): # pylint:disable=too-many-lines,line-too-long,name-too-long,arguments-differ - # region ExceptionPolicy - @overload - async def upsert_exception_policy( # pylint: disable=arguments-differ - self, - exception_policy_id: str, - *, - exception_rules: Optional[List[_models.ExceptionRule]], - name: Optional[str], - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ExceptionPolicy: - """Update an exception policy. - - :param str exception_policy_id: Id of the exception policy. - :keyword exception_rules: (Optional) A collection of exception rules on the exception policy. - :paramtype exception_rules: Optional[Dict[str, ~azure.communication.jobrouter.models.ExceptionRule]] - :keyword Optional[str] name: The name of this policy. - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :return: Instance of ExceptionPolicy - :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy - :raises: ~azure.core.exceptions.HttpResponseError - - .. admonition:: Example: - - .. literalinclude:: ../samples/exception_policy_crud_ops_async.py - :start-after: [START update_exception_policy_async] - :end-before: [END update_exception_policy_async] - :language: python - :dedent: 8 - :caption: Using a JobRouterAdministrationClient to update an exception policy - """ - - @overload - async def upsert_exception_policy( - self, - exception_policy_id: str, - resource: _models.ExceptionPolicy, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ExceptionPolicy: - """Creates or updates a exception policy. - - Creates or updates a exception policy. - - :param exception_policy_id: The Id of the exception policy. Required. - :type exception_policy_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.ExceptionPolicy - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_exception_policy( - self, - exception_policy_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ExceptionPolicy: - """Creates or updates a exception policy. - - Creates or updates a exception policy. - - :param exception_policy_id: The Id of the exception policy. Required. - :type exception_policy_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_exception_policy( - self, - exception_policy_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ExceptionPolicy: - """Creates or updates a exception policy. - - Creates or updates a exception policy. - - :param exception_policy_id: The Id of the exception policy. Required. - :type exception_policy_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ExceptionPolicy. The ExceptionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - async def upsert_exception_policy( # pylint: disable=docstring-missing-param - self, exception_policy_id: str, *args: Union[_models.ExceptionPolicy, JSON, IO[bytes]], **kwargs: Any - ) -> _models.ExceptionPolicy: - """Update an exception policy. - - :param str exception_policy_id: Id of the exception policy. - - :keyword exception_rules: (Optional) A collection of exception rules on the exception - policy. - :paramtype exception_rules: Optional[Dict[str, ~azure.communication.jobrouter.models.ExceptionRule]] - - :keyword Optional[str] name: The name of this policy. - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of ExceptionPolicy - :rtype: ~azure.communication.jobrouter.models.ExceptionPolicy - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - - .. admonition:: Example: - - .. literalinclude:: ../samples/exception_policy_crud_ops_async.py - :start-after: [START update_exception_policy_async] - :end-before: [END update_exception_policy_async] - :language: python - :dedent: 8 - :caption: Using a JobRouterAdministrationClient to update an exception policy - """ - if not exception_policy_id: - raise ValueError("exception_policy_id cannot be None.") - - exception_policy: Union[_models.ExceptionPolicy, JSON, IO[bytes]] = _models.ExceptionPolicy() - if len(args) == 1: - exception_policy = args[0] - - patch = exception_policy - if isinstance(exception_policy, _models.ExceptionPolicy): - patch = _models.ExceptionPolicy( - name=kwargs.pop("name", exception_policy.name), - exception_rules=kwargs.pop("exception_rules", exception_policy.exception_rules), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return await super().upsert_exception_policy( - exception_policy_id=exception_policy_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_exception_policies( - self, *, results_per_page: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged[_models.ExceptionPolicy]: - """Retrieves existing exception policies. - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of ExceptionPolicyItem - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.ExceptionPolicyItem] - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/exception_policy_crud_ops_async.py - :start-after: [START list_exception_policies_async] - :end-before: [END list_exception_policies_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list exception policies - - .. admonition:: Example: - - .. literalinclude:: ../samples/exception_policy_crud_ops_async.py - :start-after: [START list_exception_policies_batched_async] - :end-before: [END list_exception_policies_batched_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list exception policies in batches - """ - return super().list_exception_policies(maxpagesize=results_per_page, **kwargs) - - # endregion ExceptionPolicy - - # region DistributionPolicy - @overload - async def upsert_distribution_policy( # pylint: disable=arguments-differ - self, - distribution_policy_id: str, - *, - name: Optional[str], - offer_expires_after_seconds: Optional[float], - mode: Optional[Union[_models.BestWorkerMode, _models.LongestIdleMode, _models.RoundRobinMode]], - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.DistributionPolicy: - """Update a distribution policy. - - :param str distribution_policy_id: Id of the distribution policy. - - :keyword Optional[float] offer_expires_after_seconds: The expiry time of any offers created under this policy - will be governed by the offer time to live. - - :keyword mode: Specified distribution mode - :paramtype mode: Optional[Union[~azure.communication.jobrouter.models.BestWorkerMode, - ~azure.communication.jobrouter.models.LongestIdleMode, - ~azure.communication.jobrouter.models.RoundRobinMode]] - - :keyword Optional[str] name: The name of this policy. - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of DistributionPolicy - :rtype: ~azure.communication.jobrouter.models.DistributionPolicy - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/distribution_policy_crud_ops_async.py - :start-after: [START update_distribution_policy_async] - :end-before: [END update_distribution_policy_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a distribution policy - """ - - @overload - async def upsert_distribution_policy( - self, - distribution_policy_id: str, - resource: _models.DistributionPolicy, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.DistributionPolicy: - """Creates or updates a distribution policy. - - Creates or updates a distribution policy. - - :param distribution_policy_id: The unique identifier of the policy. Required. - :type distribution_policy_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.DistributionPolicy - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.DistributionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_distribution_policy( - self, - distribution_policy_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.DistributionPolicy: - """Creates or updates a distribution policy. - - Creates or updates a distribution policy. - - :param distribution_policy_id: The unique identifier of the policy. Required. - :type distribution_policy_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.DistributionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_distribution_policy( - self, - distribution_policy_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.DistributionPolicy: - """Creates or updates a distribution policy. - - Creates or updates a distribution policy. - - :param distribution_policy_id: The unique identifier of the policy. Required. - :type distribution_policy_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: DistributionPolicy. The DistributionPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.DistributionPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - async def upsert_distribution_policy( # pylint: disable=docstring-missing-param - self, distribution_policy_id: str, *args: Union[_models.DistributionPolicy, JSON, IO[bytes]], **kwargs: Any - ) -> _models.DistributionPolicy: - """Update a distribution policy. - - :param str distribution_policy_id: Id of the distribution policy. - - :keyword Optional[float] offer_expires_after_seconds: The expiry time of any offers created under this policy - will be governed by the offer time to live. - - :keyword mode: Specified distribution mode - :paramtype mode: Optional[Union[~azure.communication.jobrouter.models.BestWorkerMode, - ~azure.communication.jobrouter.models.LongestIdleMode, - ~azure.communication.jobrouter.models.RoundRobinMode]] - - :keyword Optional[str] name: The name of this policy. - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of DistributionPolicy - :rtype: ~azure.communication.jobrouter.models.DistributionPolicy - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/distribution_policy_crud_ops_async.py - :start-after: [START update_distribution_policy_async] - :end-before: [END update_distribution_policy_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a distribution policy - """ - if not distribution_policy_id: - raise ValueError("distribution_policy_id cannot be None.") - - distribution_policy: Union[_models.DistributionPolicy, JSON, IO[bytes]] = _models.DistributionPolicy() - if len(args) == 1: - distribution_policy = args[0] - - patch = distribution_policy - if isinstance(distribution_policy, _models.DistributionPolicy): - patch = _models.DistributionPolicy( - name=kwargs.pop("name", distribution_policy.name), - offer_expires_after_seconds=kwargs.pop( - "offer_expires_after_seconds", distribution_policy.offer_expires_after_seconds - ), - mode=kwargs.pop("mode", distribution_policy.mode), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return await super().upsert_distribution_policy( - distribution_policy_id=distribution_policy_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_distribution_policies( - self, *, results_per_page: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged[_models.DistributionPolicy]: - """Retrieves existing distribution policies. - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of DistributionPolicy - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.DistributionPolicy] - :raises: ~azure.core.exceptions.HttpResponseError - - .. admonition:: Example: - - .. literalinclude:: ../samples/distribution_policy_crud_ops_async.py - :start-after: [START list_distribution_policies_async] - :end-before: [END list_distribution_policies_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list distribution policies - - .. admonition:: Example: - - .. literalinclude:: ../samples/distribution_policy_crud_ops_async.py - :start-after: [START list_distribution_policies_batched_async] - :end-before: [END list_distribution_policies_batched_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list distribution policies in batches - """ - return super().list_distribution_policies(maxpagesize=results_per_page, **kwargs) - - # endregion DistributionPolicy - - # region Queue - @overload - async def upsert_queue( # pylint: disable=arguments-differ - self, - queue_id: str, - *, - distribution_policy_id: Optional[str], - name: Optional[str], - labels: Optional[Dict[str, Union[int, float, str, bool]]], - exception_policy_id: Optional[str], - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterQueue: - """Update a job queue - - :param str queue_id: Id of the queue. - - :keyword Optional[str] distribution_policy_id: The ID of the distribution policy that will determine - how a job is distributed to workers. - - :keyword Optional[str] name: The name of this queue. - - :keyword labels: A set of key/value pairs that are - identifying attributes used by the rules engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool]]] - - :keyword Optional[str] exception_policy_id: The ID of the exception policy that determines various - job escalation rules. - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterQueue - :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/job_queue_crud_ops_async.py - :start-after: [START update_queue_async] - :end-before: [END update_queue_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a queue - """ - - @overload - async def upsert_queue( - self, - queue_id: str, - resource: _models.RouterQueue, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterQueue: - """Creates or updates a queue. - - Creates or updates a queue. - - :param queue_id: The Id of this queue. Required. - :type queue_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.RouterQueue - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterQueue. The RouterQueue is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_queue( - self, - queue_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterQueue: - """Creates or updates a queue. - - Creates or updates a queue. - - :param queue_id: The Id of this queue. Required. - :type queue_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterQueue. The RouterQueue is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_queue( - self, - queue_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterQueue: - """Creates or updates a queue. - - Creates or updates a queue. - - :param queue_id: The Id of this queue. Required. - :type queue_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterQueue. The RouterQueue is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises ~azure.core.exceptions.HttpResponseError: - """ - - async def upsert_queue( # pylint: disable=docstring-missing-param - self, queue_id: str, *args: Union[_models.RouterQueue, JSON, IO[bytes]], **kwargs: Any - ) -> _models.RouterQueue: - """Update a job queue - - :param str queue_id: Id of the queue. - - :keyword Optional[str] distribution_policy_id: The ID of the distribution policy that will determine - how a job is distributed to workers. - - :keyword Optional[str] name: The name of this queue. - - :keyword labels: A set of key/value pairs that are - identifying attributes used by the rules engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool]]] - - :keyword Optional[str] exception_policy_id: The ID of the exception policy that determines various - job escalation rules. - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterQueue - :rtype: ~azure.communication.jobrouter.models.RouterQueue - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/job_queue_crud_ops_async.py - :start-after: [START update_queue_async] - :end-before: [END update_queue_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a queue - """ - if not queue_id: - raise ValueError("queue_id cannot be None.") - - queue: Union[_models.RouterQueue, JSON, IO[bytes]] = _models.RouterQueue() - if len(args) == 1: - queue = args[0] - - patch = queue - if isinstance(queue, _models.RouterQueue): - patch = _models.RouterQueue( - name=kwargs.pop("name", queue.name), - distribution_policy_id=kwargs.pop("distribution_policy_id", queue.distribution_policy_id), - labels=kwargs.pop("labels", queue.labels), - exception_policy_id=kwargs.pop("exception_policy_id", queue.exception_policy_id), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return await super().upsert_queue( - queue_id=queue_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_queues( - self, *, results_per_page: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged[_models.RouterQueue]: - """Retrieves existing queues. - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of RouterQueue - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterQueue] - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/job_queue_crud_ops_async.py - :start-after: [START list_queues_async] - :end-before: [END list_queues_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list queues - - .. admonition:: Example: - - .. literalinclude:: ../samples/job_queue_crud_ops_async.py - :start-after: [START list_queues_batched_async] - :end-before: [END list_queues_batched_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list queues in batches - """ - - return super().list_queues(maxpagesize=results_per_page, **kwargs) - - # endregion Queue - - # region ClassificationPolicy - @overload - async def upsert_classification_policy( # pylint: disable=arguments-differ - self, - classification_policy_id: str, - *, - name: Optional[str], - fallback_queue_id: Optional[str], - queue_selectors: Optional[ - List[ - Union[ - _models.StaticQueueSelectorAttachment, - _models.ConditionalQueueSelectorAttachment, - _models.RuleEngineQueueSelectorAttachment, - _models.PassThroughQueueSelectorAttachment, - _models.WeightedAllocationQueueSelectorAttachment, - ] - ] - ], # pylint: disable=line-too-long - prioritization_rule: Optional[ - Union[ - _models.StaticRouterRule, - _models.ExpressionRouterRule, - _models.FunctionRouterRule, - _models.WebhookRouterRule, - ] - ], # pylint: disable=line-too-long - worker_selectors: Optional[ - List[ - Union[ - _models.StaticWorkerSelectorAttachment, - _models.ConditionalWorkerSelectorAttachment, - _models.RuleEngineWorkerSelectorAttachment, - _models.PassThroughWorkerSelectorAttachment, - _models.WeightedAllocationWorkerSelectorAttachment, - ] - ] - ], # pylint: disable=line-too-long - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ClassificationPolicy: - """Update a classification policy - - :param str classification_policy_id: Id of the classification policy. - - :keyword Optional[str] name: Friendly name of this policy. - - :keyword fallback_queue_id: The fallback queue to select if the queue selector doesn't find a match. - :paramtype fallback_queue_id: Optional[str] - - :keyword queue_selectors: The queue selectors to resolve a queue for a given job. - :paramtype queue_selectors: Optional[List[Union[ - ~azure.communication.jobrouter.models.StaticQueueSelectorAttachment, - ~azure.communication.jobrouter.models.ConditionalQueueSelectorAttachment, - ~azure.communication.jobrouter.models.RuleEngineQueueSelectorAttachment, - ~azure.communication.jobrouter.models.PassThroughQueueSelectorAttachment, - ~azure.communication.jobrouter.models.WeightedAllocationQueueSelectorAttachment]]] - - :keyword prioritization_rule: The rule to determine a priority score for a given job. - :paramtype prioritization_rule: Optional[Union[~azure.communication.jobrouter.models.StaticRouterRule, - ~azure.communication.jobrouter.models.ExpressionRouterRule, - ~azure.communication.jobrouter.models.FunctionRouterRule, - ~azure.communication.jobrouter.models.WebhookRouterRule]] - - :keyword worker_selectors: The worker label selectors to attach to a given job. - :paramtype worker_selectors: Optional[List[Union[~azure.communication.jobrouter.models.StaticWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.ConditionalWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.RuleEngineWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.PassThroughWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.WeightedAllocationWorkerSelectorAttachment]]] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of ClassificationPolicy - :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/classification_policy_crud_ops_async.py - :start-after: [START update_classification_policy_async] - :end-before: [END update_classification_policy_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a classification policy - """ - - @overload - async def upsert_classification_policy( - self, - classification_policy_id: str, - resource: _models.ClassificationPolicy, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ClassificationPolicy: - """Creates or updates a classification policy. - - Creates or updates a classification policy. - - :param classification_policy_id: Unique identifier of this policy. Required. - :type classification_policy_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.ClassificationPolicy - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_classification_policy( - self, - classification_policy_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ClassificationPolicy: - """Creates or updates a classification policy. - - Creates or updates a classification policy. - - :param classification_policy_id: Unique identifier of this policy. Required. - :type classification_policy_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_classification_policy( - self, - classification_policy_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.ClassificationPolicy: - """Creates or updates a classification policy. - - Creates or updates a classification policy. - - :param classification_policy_id: Unique identifier of this policy. Required. - :type classification_policy_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: ClassificationPolicy. The ClassificationPolicy is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy - :raises ~azure.core.exceptions.HttpResponseError: - """ - - async def upsert_classification_policy( # pylint: disable=docstring-missing-param - self, classification_policy_id: str, *args: Union[_models.ClassificationPolicy, JSON, IO[bytes]], **kwargs: Any - ) -> _models.ClassificationPolicy: - """Update a classification policy - - :param str classification_policy_id: Id of the classification policy. - - :keyword Optional[str] name: Friendly name of this policy. - - :keyword fallback_queue_id: The fallback queue to select if the queue selector doesn't find a match. - :paramtype fallback_queue_id: Optional[str] - - :keyword queue_selectors: The queue selectors to resolve a queue for a given job. - :paramtype queue_selectors: Optional[List[Union[ - ~azure.communication.jobrouter.models.StaticQueueSelectorAttachment, - ~azure.communication.jobrouter.models.ConditionalQueueSelectorAttachment, - ~azure.communication.jobrouter.models.RuleEngineQueueSelectorAttachment, - ~azure.communication.jobrouter.models.PassThroughQueueSelectorAttachment, - ~azure.communication.jobrouter.models.WeightedAllocationQueueSelectorAttachment]]] - - :keyword prioritization_rule: The rule to determine a priority score for a given job. - :paramtype prioritization_rule: Optional[Union[~azure.communication.jobrouter.models.StaticRouterRule, - ~azure.communication.jobrouter.models.ExpressionRouterRule, - ~azure.communication.jobrouter.models.FunctionRouterRule, - ~azure.communication.jobrouter.models.WebhookRouterRule]] - - :keyword worker_selectors: The worker label selectors to attach to a given job. - :paramtype worker_selectors: Optional[List[Union[~azure.communication.jobrouter.models.StaticWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.ConditionalWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.RuleEngineWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.PassThroughWorkerSelectorAttachment, - ~azure.communication.jobrouter.models.WeightedAllocationWorkerSelectorAttachment]]] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of ClassificationPolicy - :rtype: ~azure.communication.jobrouter.models.ClassificationPolicy - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/classification_policy_crud_ops_async.py - :start-after: [START update_classification_policy_async] - :end-before: [END update_classification_policy_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to update a classification policy - """ - if not classification_policy_id: - raise ValueError("classification_policy_id cannot be None.") - - classification_policy: Union[_models.ClassificationPolicy, JSON, IO[bytes]] = _models.ClassificationPolicy() - if len(args) == 1: - classification_policy = args[0] - - patch = classification_policy - if isinstance(classification_policy, _models.ClassificationPolicy): - patch = _models.ClassificationPolicy( - name=kwargs.pop("name", classification_policy.name), - fallback_queue_id=kwargs.pop("fallback_queue_id", classification_policy.fallback_queue_id), - queue_selector_attachments=kwargs.pop( - "queue_selector_attachments", classification_policy.queue_selector_attachments - ), - prioritization_rule=kwargs.pop("prioritization_rule", classification_policy.prioritization_rule), - worker_selector_attachments=kwargs.pop( - "worker_selector_attachments", classification_policy.worker_selector_attachments - ), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return await super().upsert_classification_policy( - classification_policy_id=classification_policy_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_classification_policies( - self, *, results_per_page: Optional[int] = None, **kwargs: Any - ) -> AsyncItemPaged[_models.ClassificationPolicy]: - """Retrieves existing classification policies. - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of ClassificationPolicy - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.ClassificationPolicy] - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/classification_policy_crud_ops_async.py - :start-after: [START list_classification_policies_async] - :end-before: [END list_classification_policies_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list classification policies - - .. admonition:: Example: - - .. literalinclude:: ../samples/classification_policy_crud_ops_async.py - :start-after: [START list_classification_policies_batched_async] - :end-before: [END list_classification_policies_batched_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterAdministrationClient to list classification policies in batches - """ - - return super().list_classification_policies(maxpagesize=results_per_page, **kwargs) - - # endregion ClassificationPolicy - - -class JobRouterClientOperationsMixin(JobRouterClientOperationsMixinGenerated): - # region Worker - @overload - async def upsert_worker( # pylint: disable=arguments-differ - self, - worker_id: str, - *, - queues: Optional[List[str]], - capacity: Optional[int], - labels: Optional[Dict[str, Union[int, float, str, bool]]], - tags: Optional[Dict[str, Union[int, float, str, bool]]], - channels: Optional[List[_models.RouterChannel]], - available_for_offers: Optional[bool], - max_concurrent_offers: Optional[int], - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterWorker: - """Update a router worker. - - :param str worker_id: Id of the worker. - - :keyword queues: The queue(s) that this worker can receive work from. - :paramtype queues: Optional[List[str]] - - :keyword capacity: The total capacity score this worker has to manage multiple concurrent - jobs. - :paramtype capacity: Optional[int] - - :keyword labels: A set of key/value pairs that are identifying attributes used by the rules - engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword tags: A set of tags. A set of non-identifying attributes attached to this worker. - :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword channels: The channel(s) this worker can handle and their impact on the - workers capacity. - :paramtype channels: Optional[List[~azure.communication.jobrouter.models.RouterChannel]] - - :keyword available_for_offers: A flag indicating this worker is open to receive offers or not. - :paramtype available_for_offers: Optional[bool] - - :keyword max_concurrent_offers: If this is set, the worker will only receive up to this many new - offers at a time. - :paramtype max_concurrent_offers: Optional[int] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterWorker - :rtype: ~azure.communication.jobrouter.models.RouterWorker - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops_async.py - :start-after: [START update_worker_async] - :end-before: [END update_worker_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to update a worker - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops.py - :start-after: [START register_worker_async] - :end-before: [END register_worker_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to register a worker - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops_async.py - :start-after: [START deregister_worker_async] - :end-before: [END deregister_worker_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to de-register a worker - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops_async.py - :start-after: [START create_worker_w_limit_concurrent_offers_async] - :end-before: [END create_worker_w_limit_concurrent_offers_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to create a worker with concurrent offer limit - - """ - - @overload - async def upsert_worker( - self, - worker_id: str, - resource: _models.RouterWorker, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterWorker: - """Creates or updates a worker. - - Creates or updates a worker. - - :param worker_id: Id of the worker. Required. - :type worker_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.RouterWorker - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterWorker. The RouterWorker is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterWorker - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_worker( - self, - worker_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterWorker: - """Creates or updates a worker. - - Creates or updates a worker. - - :param worker_id: Id of the worker. Required. - :type worker_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterWorker. The RouterWorker is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterWorker - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_worker( - self, - worker_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterWorker: - """Creates or updates a worker. - - Creates or updates a worker. - - :param worker_id: Id of the worker. Required. - :type worker_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterWorker. The RouterWorker is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterWorker - :raises ~azure.core.exceptions.HttpResponseError: - """ - - async def upsert_worker( # pylint: disable=docstring-missing-param - self, worker_id: str, *args: Union[_models.RouterWorker, JSON, IO[bytes]], **kwargs: Any - ) -> _models.RouterWorker: - """Update a router worker. - - :param str worker_id: Id of the worker. - - :keyword queues: The queue(s) that this worker can receive work from. - :paramtype queues: Optional[List[str]] - - :keyword capacity: The total capacity score this worker has to manage multiple concurrent - jobs. - :paramtype capacity: Optional[int] - - :keyword labels: A set of key/value pairs that are identifying attributes used by the rules - engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword tags: A set of tags. A set of non-identifying attributes attached to this worker. - :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword channels: The channel(s) this worker can handle and their impact on the - workers capacity. - :paramtype channels: Optional[List[~azure.communication.jobrouter.models.RouterChannel]] - - :keyword available_for_offers: A flag indicating this worker is open to receive offers or not. - :paramtype available_for_offers: Optional[bool] - - :keyword max_concurrent_offers: If this is set, the worker will only receive up to this many new - offers at a time. - :paramtype max_concurrent_offers: Optional[int] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterWorker - :rtype: ~azure.communication.jobrouter.models.RouterWorker - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops_async.py - :start-after: [START update_worker_async] - :end-before: [END update_worker_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to update a worker - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops_async.py - :start-after: [START register_worker_async] - :end-before: [END register_worker_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to register a worker - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops_async.py - :start-after: [START deregister_worker_async] - :end-before: [END deregister_worker_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to de-register a worker - """ - if not worker_id: - raise ValueError("worker_id cannot be None.") - - router_worker: Union[_models.RouterWorker, JSON, IO[bytes]] = _models.RouterWorker() - if len(args) == 1: - router_worker = args[0] - - patch = router_worker - if isinstance(router_worker, _models.RouterWorker): - patch = _models.RouterWorker( - queues=kwargs.pop("queues", router_worker.queues), - capacity=kwargs.pop("capacity", router_worker.capacity), - labels=kwargs.pop("labels", router_worker.labels), - tags=kwargs.pop("tags", router_worker.tags), - channels=kwargs.pop("channels", router_worker.channels), - available_for_offers=kwargs.pop("available_for_offers", router_worker.available_for_offers), - max_concurrent_offers=kwargs.pop("max_concurrent_offers", router_worker.max_concurrent_offers), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return await super().upsert_worker( - worker_id=worker_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_workers( - self, - *, - state: Optional[Union[str, _models.RouterWorkerState, Literal["all"]]] = "all", - channel_id: Optional[str] = None, - queue_id: Optional[str] = None, - has_capacity: Optional[bool] = None, - results_per_page: Optional[int] = None, - **kwargs: Any - ) -> AsyncItemPaged[_models.RouterWorker]: - """Retrieves existing workers. - - :keyword state: If specified, select workers by worker status. Default value is "all". - Accepted value(s): active, draining, inactive, all - :paramtype state: Optional[Union[str, ~azure.communication.jobrouter.models.RouterWorkerState, Literal["all"]]] - - :keyword channel_id: If specified, select workers who have a channel configuration - with this channel. Default value is None. - :paramtype channel_id: Optional[str] - - :keyword queue_id: If specified, select workers who are assigned to this queue. - Default value is None. - :paramtype queue_id: Optional[str] - - :keyword has_capacity: If set to true, select only workers who have capacity for the - channel specified by ``channelId`` or for any channel - :paramtype has_capacity: Optional[bool] - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of RouterWorker - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterWorker] - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops_async.py - :start-after: [START list_workers_async] - :end-before: [END list_workers_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to retrieve workers - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_worker_crud_ops_async.py - :start-after: [START list_workers_batched_async] - :end-before: [END list_workers_batched_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to retrieve workers in batches - """ - return super().list_workers( - maxpagesize=results_per_page, - state=state, - channel_id=channel_id, - queue_id=queue_id, - has_capacity=has_capacity, - **kwargs - ) - - # endregion Worker - - # region Job - @overload - async def upsert_job( # pylint: disable=arguments-differ - self, - job_id: str, - *, - channel_reference: Optional[str], - channel_id: Optional[str], - classification_policy_id: Optional[str], - queue_id: Optional[str], - priority: Optional[int], - disposition_code: Optional[str], - requested_worker_selectors: Optional[List[_models.RouterWorkerSelector]], - labels: Optional[Dict[str, Union[int, float, str, bool, None]]], - tags: Optional[Dict[str, Union[int, float, str, bool, None]]], - notes: Optional[Dict[datetime.datetime, str]], - matching_mode: Optional[_models.JobMatchingMode], - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterJob: - """Update a job. - - :param str job_id: Id of the job. - - :keyword channel_reference: Reference to an external parent context, eg. call ID. - :paramtype channel_reference: Optional[str] - - :keyword channel_id: The channel identifier. eg. voice, chat, etc. - :paramtype channel_id: Optional[str] - - :keyword classification_policy_id: The Id of the Classification policy used for classifying a - job. - :paramtype classification_policy_id: Optional[str] - - :keyword queue_id: The Id of the Queue that this job is queued to. - :paramtype queue_id: Optional[str] - - :keyword priority: The priority of this job. - :paramtype priority: Optional[int] - - :keyword disposition_code: Reason code for cancelled or closed jobs. - :paramtype disposition_code: Optional[str] - - :keyword requested_worker_selectors: A collection of manually specified label selectors, which - a worker must satisfy in order to process this job. - :paramtype requested_worker_selectors: Optional[List[ - ~azure.communication.jobrouter.models.RouterWorkerSelector]] - - :keyword labels: A set of key/value pairs that are identifying attributes used by the rules - engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword tags: A set of tags. A set of non-identifying attributes attached to this job. - :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword notes: Notes attached to a job, sorted by timestamp. - :paramtype notes: Optional[Dict[~datetime.datetime, str]] - - :keyword matching_mode: If set, determines how a job will be matched - :paramtype matching_mode: Optional[~azure.communication.jobrouter.models.JobMatchingMode] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterJob - :rtype: ~azure.communication.jobrouter.models.RouterJob - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops_async.py - :start-after: [START update_job_async] - :end-before: [END update_job_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to update a job - """ - - @overload - async def upsert_job( - self, - job_id: str, - resource: _models.RouterJob, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterJob: - """Creates or updates a router job. - - Creates or updates a router job. - - :param job_id: The id of the job. Required. - :type job_id: str - :param resource: The resource instance. Required. - :type resource: ~azure.communication.jobrouter.models.RouterJob - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterJob. The RouterJob is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterJob - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_job( - self, - job_id: str, - resource: JSON, - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterJob: - """Creates or updates a router job. - - Creates or updates a router job. - - :param job_id: The id of the job. Required. - :type job_id: str - :param resource: The resource instance. Required. - :type resource: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterJob. The RouterJob is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterJob - :raises ~azure.core.exceptions.HttpResponseError: - """ - - @overload - async def upsert_job( - self, - job_id: str, - resource: IO[bytes], - *, - content_type: str = "application/merge-patch+json", - if_unmodified_since: Optional[datetime.datetime] = None, - etag: Optional[str] = None, - match_condition: Optional[MatchConditions] = None, - **kwargs: Any - ) -> _models.RouterJob: - """Creates or updates a router job. - - Creates or updates a router job. - - :param job_id: The id of the job. Required. - :type job_id: str - :param resource: The resource instance. Required. - :type resource: IO[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". - :paramtype content_type: str - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: RouterJob. The RouterJob is compatible with MutableMapping - :rtype: ~azure.communication.jobrouter.models.RouterJob - :raises ~azure.core.exceptions.HttpResponseError: - """ - - async def upsert_job( # pylint: disable=docstring-missing-param - self, job_id: str, *args: Union[_models.RouterJob, JSON, IO[bytes]], **kwargs: Any - ) -> _models.RouterJob: - """Update a job. - - :param str job_id: Id of the job. - - :keyword channel_reference: Reference to an external parent context, eg. call ID. - :paramtype channel_reference: Optional[str] - - :keyword channel_id: The channel identifier. eg. voice, chat, etc. - :paramtype channel_id: Optional[str] - - :keyword classification_policy_id: The Id of the Classification policy used for classifying a - job. - :paramtype classification_policy_id: Optional[str] - - :keyword queue_id: The Id of the Queue that this job is queued to. - :paramtype queue_id: Optional[str] - - :keyword priority: The priority of this job. - :paramtype priority: Optional[int] - - :keyword disposition_code: Reason code for cancelled or closed jobs. - :paramtype disposition_code: Optional[str] - - :keyword requested_worker_selectors: A collection of manually specified label selectors, which - a worker must satisfy in order to process this job. - :paramtype requested_worker_selectors: Optional[List[ - ~azure.communication.jobrouter.models.RouterWorkerSelector]] - - :keyword labels: A set of key/value pairs that are identifying attributes used by the rules - engines to make decisions. - :paramtype labels: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword tags: A set of tags. A set of non-identifying attributes attached to this job. - :paramtype tags: Optional[Dict[str, Union[int, float, str, bool, None]]] - - :keyword notes: Notes attached to a job, sorted by timestamp. - :paramtype notes: Optional[Dict[~datetime.datetime, str]] - - :keyword matching_mode: If set, determines how a job will be matched - :paramtype matching_mode: Optional[~azure.communication.jobrouter.models.JobMatchingMode] - - :keyword if_unmodified_since: The request should only proceed if the entity was not modified - after this time. Default value is None. - :paramtype if_unmodified_since: ~datetime.datetime - :keyword etag: check if resource is changed. Set None to skip checking etag. Default value is - None. - :paramtype etag: str - :keyword match_condition: The match condition to use upon the etag. Default value is None. - :paramtype match_condition: ~azure.core.MatchConditions - - :return: Instance of RouterJob - :rtype: ~azure.communication.jobrouter.models.RouterJob - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops_async.py - :start-after: [START update_job_async] - :end-before: [END update_job_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to update a job - """ - if not job_id: - raise ValueError("job_id cannot be None.") - - router_job: Union[_models.RouterJob, JSON, IO[bytes]] = _models.RouterJob() - if len(args) == 1: - router_job = args[0] - - patch = router_job - if isinstance(router_job, _models.RouterJob): - patch = _models.RouterJob( - channel_reference=kwargs.pop("channel_reference", router_job.channel_reference), - channel_id=kwargs.pop("channel_id", router_job.channel_id), - classification_policy_id=kwargs.pop("classification_policy_id", router_job.classification_policy_id), - queue_id=kwargs.pop("queue_id", router_job.queue_id), - priority=kwargs.pop("priority", router_job.priority), - disposition_code=kwargs.pop("disposition_code", router_job.disposition_code), - requested_worker_selectors=kwargs.pop( - "requested_worker_selectors", router_job.requested_worker_selectors - ), - labels=kwargs.pop("labels", router_job.labels), - tags=kwargs.pop("tags", router_job.tags), - notes=kwargs.pop("notes", router_job.notes), - matching_mode=kwargs.pop("matching_mode", router_job.matching_mode), - ) - - if_unmodified_since = kwargs.pop("if_unmodified_since", None) - etag = kwargs.pop("etag", None) - match_condition = kwargs.pop("match_condition", None) - - return await super().upsert_job( - job_id=job_id, - resource=patch, - if_unmodified_since=if_unmodified_since, - etag=etag, - match_condition=match_condition, - **kwargs - ) - - @distributed_trace - def list_jobs( - self, - *, - status: Optional[Union[str, _models.RouterJobStatus, Literal["all", "active"]]] = "all", - channel_id: Optional[str] = None, - queue_id: Optional[str] = None, - classification_policy_id: Optional[str] = None, - scheduled_before: Optional[Union[str, datetime.datetime]] = None, - scheduled_after: Optional[Union[str, datetime.datetime]] = None, - results_per_page: Optional[int] = None, - **kwargs: Any - ) -> AsyncItemPaged[_models.RouterJob]: - """Retrieves list of jobs based on filter parameters. - - :keyword status: If specified, filter jobs by status. Default value is "all". - Accepted value(s): pendingClassification, queued, assigned, completed, closed, cancelled, - classificationFailed, active, all - :paramtype status: Optional[Union[ - str, ~azure.communication.jobrouter.models.RouterJobStatus, Literal["all","active"]]] - - :keyword channel_id: If specified, filter jobs by channel. Default value is None. - :paramtype channel_id: Optional[str] - - :keyword queue_id: If specified, filter jobs by queue. Default value is None. - :paramtype queue_id: Optional[str] - - :keyword classification_policy_id: If specified, filter jobs by classificationPolicy. Default value is None. - :paramtype classification_policy_id: Optional[str] - - :keyword scheduled_before: If specified, filter on jobs that was scheduled before or - at given timestamp. Range: (-Inf, scheduledBefore]. Default value is None. - :paramtype scheduled_before: Optional[~datetime.datetime] - - :keyword scheduled_after: If specified, filter on jobs that was scheduled at or - after given value. Range: [scheduledAfter, +Inf). Default value is None. - :paramtype scheduled_after: Optional[~datetime.datetime] - - - :keyword Optional[int] results_per_page: The maximum number of results to be returned per page. - - :return: An iterator like instance of RouterJob - :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.communication.jobrouter.models.RouterJob] - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops_async.py - :start-after: [START list_jobs_async] - :end-before: [END list_jobs_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to retrieve jobs - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops_async.py - :start-after: [START list_jobs_batched_async] - :end-before: [END list_jobs_batched_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to retrieve jobs in batches - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops_async.py - :start-after: [START list_scheduled_jobs_async] - :end-before: [END list_scheduled_jobs_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to retrieve scheduled jobs - """ - if scheduled_before is not None and isinstance(scheduled_before, str): - scheduled_before = _convert_str_to_datetime(scheduled_before) - - if scheduled_after is not None and isinstance(scheduled_after, str): - scheduled_after = _convert_str_to_datetime(scheduled_after) - - return super().list_jobs( - maxpagesize=results_per_page, - status=status, - channel_id=channel_id, - queue_id=queue_id, - classification_policy_id=classification_policy_id, - scheduled_before=scheduled_before, - scheduled_after=scheduled_after, - **kwargs - ) - - @distributed_trace_async - async def reclassify_job(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=arguments-differ - """Reclassify a job. - - :param str job_id: Id of the job. - - :return: None - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops_async.py - :start-after: [START reclassify_job_async] - :end-before: [END reclassify_job_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to re-classify a job - """ - if not job_id: - raise ValueError("job_id cannot be None.") - - await super()._reclassify_job(job_id=job_id, options={}, **kwargs) - - @distributed_trace_async - async def cancel_job( - self, job_id: str, options: Optional[Union[_models._models.CancelJobOptions, JSON, IO]] = None, **kwargs: Any - ) -> None: # pylint: disable=arguments-differ - """Closes a completed job. - - :param str job_id: Id of the job. - - :param options: Request model for cancelling job. Is one of the following types: - CancelJobOptions, JSON, IO Default value is None. - :type options: ~azure.communication.jobrouter.models.CancelJobOptions or JSON or IO - - :return: None - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops_async.py - :start-after: [START cancel_job_async] - :end-before: [END cancel_job_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to cancel a job - """ - if not job_id: - raise ValueError("job_id cannot be None.") - - await super()._cancel_job(job_id=job_id, options=options, **kwargs) - - @distributed_trace_async - async def complete_job( - self, - job_id: str, - assignment_id: str, - options: Optional[Union[_models._models.CompleteJobOptions, JSON, IO]] = None, - **kwargs: Any - ) -> None: # pylint: disable=arguments-differ - """Completes an assigned job. - - :param str job_id: Id of the job. - - :param assignment_id: The Id of the job assignment. Required. - :type assignment_id: str - - :param options: Request model for completing job. Is one of the following types: - CompleteJobOptions, JSON, IO Default value is None. - :type options: ~azure.communication.jobrouter.models.CompleteJobOptions or JSON or IO - - :return: None - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops_async.py - :start-after: [START complete_job_async] - :end-before: [END complete_job_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to complete a job - """ - if not job_id: - raise ValueError("job_id cannot be None.") - - if not assignment_id: - raise ValueError("assignment_id cannot be None.") - - await super()._complete_job(job_id=job_id, assignment_id=assignment_id, options=options, **kwargs) - - @distributed_trace_async - async def close_job( - self, - job_id: str, - assignment_id: str, - options: Optional[Union[_models._models.CloseJobOptions, JSON, IO]] = None, - **kwargs: Any - ) -> None: # pylint: disable=arguments-differ - """Closes a completed job. - - :param str job_id: Id of the job. - - :param assignment_id: The Id of the job assignment. Required. - :type assignment_id: str - - :param options: Request model for closing job. Is one of the following types: CloseJobOptions, - JSON, IO Default value is None. - :type options: ~azure.communication.jobrouter.models.CloseJobOptions or JSON or IO - - :return: None - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops_async.py - :start-after: [START close_job_async] - :end-before: [END close_job_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to close a job - """ - if not job_id: - raise ValueError("job_id cannot be None.") - - if not assignment_id: - raise ValueError("assignment_id cannot be None.") - - await super()._close_job(job_id=job_id, assignment_id=assignment_id, options=options, **kwargs) - - # endregion Job - - # region Offer - @distributed_trace_async - async def decline_job_offer( - self, - worker_id: str, - offer_id: str, - options: Optional[Union[_models._models.DeclineJobOfferOptions, JSON, IO]] = None, - **kwargs: Any - ) -> None: # pylint: disable=arguments-differ - """Declines an offer to work on a job. - - :param worker_id: Id of the worker. Required. - :type worker_id: str - :param offer_id: Id of the offer. Required. - :type offer_id: str - :param options: Request model for declining offer. Is one of the following types: - DeclineJobOfferOptions, JSON, IO Default value is None. - :type options: ~azure.communication.jobrouter.models.DeclineJobOfferOptions or JSON or IO - - :return: None - :rtype: None - :raises: ~azure.core.exceptions.HttpResponseError, ValueError - - .. admonition:: Example: - - .. literalinclude:: ../samples/router_job_crud_ops_async.py - :start-after: [START close_job_async] - :end-before: [END close_job_async] - :language: python - :dedent: 8 - :caption: Use a JobRouterClient to close a job - """ - if not worker_id: - raise ValueError("worker_id cannot be None.") - - if not offer_id: - raise ValueError("offer_id cannot be None.") - - await super()._decline_job_offer(worker_id=worker_id, offer_id=offer_id, options=options, **kwargs) - - # endregion Offer - - -__all__: List[str] = [ - "JobRouterClientOperationsMixin", - "JobRouterAdministrationClientOperationsMixin", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_patch.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_patch.py index 299ff2881418..8bcb627aa475 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_patch.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_patch.py @@ -1,161 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import ( - List, - Any, -) -from urllib.parse import urlparse -from azure.core.credentials import AzureKeyCredential -from .._shared.utils import parse_connection_str -from .._shared.policy import HMACCredentialsPolicy -from ._client import ( - JobRouterClient as JobRouterClientGenerated, - JobRouterAdministrationClient as JobRouterAdministrationClientGenerated, -) -from .._api_versions import DEFAULT_VERSION +from typing import List - -class JobRouterClient(JobRouterClientGenerated): - """A client to interact with the AzureCommunicationService JobRouter service. - - This client provides operations to create and update jobs, policies and workers. - - :param str endpoint: - The endpoint of the Azure Communication resource. - :param ~azure.core.credentials.AzureKeyCredential credential: - The credentials with which to authenticate - - :keyword api_version: Azure Communication Job Router API version. - Default value is "2023-11-01". - Note that overriding this default value may result in unsupported behavior. - """ - - def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> None: - if not credential: - raise ValueError("credential can not be None") - - # TokenCredential not supported at the moment - if hasattr(credential, "get_token"): - raise TypeError( - "Unsupported credential: {}. Use an AzureKeyCredential to use HMACCredentialsPolicy" - " for authentication".format(type(credential)) - ) - - try: - if not endpoint.lower().startswith("http"): - endpoint = "https://" + endpoint - except AttributeError: - raise ValueError("Host URL must be a string") # pylint:disable=raise-missing-from - - parsed_url = urlparse(endpoint.rstrip("/")) - if not parsed_url.netloc: - raise ValueError("Invalid URL: {}".format(endpoint)) - - self._endpoint = endpoint - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._authentication_policy = HMACCredentialsPolicy(endpoint, credential.key) - super().__init__( - self._endpoint, authentication_policy=self._authentication_policy, api_version=self._api_version, **kwargs - ) - - @classmethod - def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "JobRouterClient": - """Create JobRouterClient from a Connection String. - - :param str conn_str: - A connection string to an Azure Communication Service resource. - :return: Instance of JobRouterClient. - :rtype: ~azure.communication.jobrouter.aio.JobRouterClient - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_authentication_async.py - :start-after: [START auth_from_connection_string_async] - :end-before: [END auth_from_connection_string_async] - :language: python - :dedent: 8 - :caption: Authenticating a JobRouterClient from a connection_string - """ - endpoint, access_key = parse_connection_str(conn_str) - return cls(endpoint, AzureKeyCredential(access_key), **kwargs) - - -class JobRouterAdministrationClient(JobRouterAdministrationClientGenerated): - """A client to interact with the AzureCommunicationService JobRouter service. - - This client provides operations to create, update, list and delete the following entities: classification policy, - exception policy, distribution policy and queue. - - :param str endpoint: - The endpoint of the Azure Communication resource. - :param ~azure.core.credentials.AzureKeyCredential credential: - The credentials with which to authenticate - - :keyword api_version: Azure Communication Job Router API version. Default value is "2023-11-01". - Note that overriding this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, endpoint: str, credential: AzureKeyCredential, **kwargs: Any) -> "None": - if not credential: - raise ValueError("credential can not be None") - - # TokenCredential not supported at the moment - if hasattr(credential, "get_token"): - raise TypeError( - "Unsupported credential: {}. Use an AzureKeyCredential to use HMACCredentialsPolicy" - " for authentication".format(type(credential)) - ) - - try: - if not endpoint.lower().startswith("http"): - endpoint = "https://" + endpoint - except AttributeError: - raise ValueError("Host URL must be a string") # pylint: disable=raise-missing-from - - parsed_url = urlparse(endpoint.rstrip("/")) - if not parsed_url.netloc: - raise ValueError("Invalid URL: {}".format(endpoint)) - - self._endpoint = endpoint - self._api_version = kwargs.pop("api_version", DEFAULT_VERSION) - self._authentication_policy = HMACCredentialsPolicy(endpoint, credential.key) - super().__init__( - self._endpoint, authentication_policy=self._authentication_policy, api_version=self._api_version, **kwargs - ) - - @classmethod - def from_connection_string(cls, conn_str: str, **kwargs: Any) -> "JobRouterAdministrationClient": - """Create JobRouterClient from a Connection String. - - :param str conn_str: - A connection string to an Azure Communication Service resource. - :return: Instance of JobRouterAdministrationClient. - :rtype: ~azure.communication.jobrouter.aio.JobRouterAdministrationClient - - .. admonition:: Example: - - .. literalinclude:: ../samples/sample_authentication_async.py - :start-after: [START admin_auth_from_connection_string_async] - :end-before: [END admin_auth_from_connection_string_async] - :language: python - :dedent: 8 - :caption: Authenticating a JobRouterAdministrationClient from a connection_string - """ - endpoint, access_key = parse_connection_str(conn_str) - return cls(endpoint, AzureKeyCredential(access_key), **kwargs) - - -__all__: List[str] = [ - "JobRouterClient", - "JobRouterAdministrationClient", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_vendor.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_vendor.py deleted file mode 100644 index 8a2a6db2ca5a..000000000000 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/aio/_vendor.py +++ /dev/null @@ -1,67 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) Python Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from abc import ABC -from typing import Optional, TYPE_CHECKING - -from azure.core import MatchConditions - -from ._configuration import JobRouterAdministrationClientConfiguration, JobRouterClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core import AsyncPipelineClient - - from .._serialization import Deserializer, Serializer - - -class JobRouterAdministrationClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "AsyncPipelineClient" - _config: JobRouterAdministrationClientConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" - - -class JobRouterClientMixinABC(ABC): - """DO NOT use this class. It is for internal typing use only.""" - - _client: "AsyncPipelineClient" - _config: JobRouterClientConfiguration - _serialize: "Serializer" - _deserialize: "Deserializer" - - -def quote_etag(etag: Optional[str]) -> Optional[str]: - if not etag or etag == "*": - return etag - if etag.startswith("W/"): - return etag - if etag.startswith('"') and etag.endswith('"'): - return etag - if etag.startswith("'") and etag.endswith("'"): - return etag - return '"' + etag + '"' - - -def prep_if_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: - if match_condition == MatchConditions.IfNotModified: - if_match = quote_etag(etag) if etag else None - return if_match - if match_condition == MatchConditions.IfPresent: - return "*" - return None - - -def prep_if_none_match(etag: Optional[str], match_condition: Optional[MatchConditions]) -> Optional[str]: - if match_condition == MatchConditions.IfModified: - if_none_match = quote_etag(etag) if etag else None - return if_none_match - if match_condition == MatchConditions.IfMissing: - return "*" - return None diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/__init__.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/__init__.py index f81170a6f9e0..c56418d48dd3 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/__init__.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/__init__.py @@ -5,86 +5,102 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._models import AcceptJobOfferResult -from ._models import BestWorkerMode -from ._models import CancelExceptionAction -from ._models import CancelJobOptions -from ._models import ClassificationPolicy -from ._models import CloseJobOptions -from ._models import CompleteJobOptions -from ._models import ConditionalQueueSelectorAttachment -from ._models import ConditionalWorkerSelectorAttachment -from ._models import DeclineJobOfferOptions -from ._models import DirectMapRouterRule -from ._models import DistributionMode -from ._models import DistributionPolicy -from ._models import ExceptionAction -from ._models import ExceptionPolicy -from ._models import ExceptionRule -from ._models import ExceptionTrigger -from ._models import ExpressionRouterRule -from ._models import FunctionRouterRule -from ._models import FunctionRouterRuleCredential -from ._models import JobMatchingMode -from ._models import LongestIdleMode -from ._models import ManualReclassifyExceptionAction -from ._models import OAuth2WebhookClientCredential -from ._models import PassThroughQueueSelectorAttachment -from ._models import PassThroughWorkerSelectorAttachment -from ._models import QueueAndMatchMode -from ._models import QueueLengthExceptionTrigger -from ._models import QueueSelectorAttachment -from ._models import QueueWeightedAllocation -from ._models import ReclassifyExceptionAction -from ._models import RoundRobinMode -from ._models import RouterChannel -from ._models import RouterJob -from ._models import RouterJobAssignment -from ._models import RouterJobNote -from ._models import RouterJobOffer -from ._models import RouterJobPositionDetails -from ._models import RouterQueue -from ._models import RouterQueueSelector -from ._models import RouterQueueStatistics -from ._models import RouterRule -from ._models import RouterWorker -from ._models import RouterWorkerAssignment -from ._models import RouterWorkerSelector -from ._models import RuleEngineQueueSelectorAttachment -from ._models import RuleEngineWorkerSelectorAttachment -from ._models import ScheduleAndSuspendMode -from ._models import ScoringRuleOptions -from ._models import StaticQueueSelectorAttachment -from ._models import StaticRouterRule -from ._models import StaticWorkerSelectorAttachment -from ._models import SuspendMode -from ._models import UnassignJobOptions -from ._models import UnassignJobResult -from ._models import WaitTimeExceptionTrigger -from ._models import WebhookRouterRule -from ._models import WeightedAllocationQueueSelectorAttachment -from ._models import WeightedAllocationWorkerSelectorAttachment -from ._models import WorkerSelectorAttachment -from ._models import WorkerWeightedAllocation +from typing import TYPE_CHECKING -from ._enums import DistributionModeKind -from ._enums import ExceptionActionKind -from ._enums import ExceptionTriggerKind -from ._enums import ExpressionRouterRuleLanguage -from ._enums import JobMatchingModeKind -from ._enums import LabelOperator -from ._enums import QueueSelectorAttachmentKind -from ._enums import RouterJobStatus -from ._enums import RouterJobStatusSelector -from ._enums import RouterRuleKind -from ._enums import RouterWorkerSelectorStatus -from ._enums import RouterWorkerState -from ._enums import RouterWorkerStateSelector -from ._enums import ScoringRuleParameterSelector -from ._enums import WorkerSelectorAttachmentKind +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + + +from ._models import ( # type: ignore + AcceptJobOfferResult, + BestWorkerMode, + CancelExceptionAction, + CancelJobOptions, + CancelJobResult, + ClassificationPolicy, + CloseJobOptions, + CloseJobResult, + CompleteJobOptions, + CompleteJobResult, + ConditionalQueueSelectorAttachment, + ConditionalWorkerSelectorAttachment, + DeclineJobOfferOptions, + DeclineJobOfferResult, + DirectMapRouterRule, + DistributionMode, + DistributionPolicy, + ExceptionAction, + ExceptionPolicy, + ExceptionRule, + ExceptionTrigger, + ExpressionRouterRule, + FunctionRouterRule, + FunctionRouterRuleCredential, + JobMatchingMode, + LongestIdleMode, + ManualReclassifyExceptionAction, + OAuth2WebhookClientCredential, + PassThroughQueueSelectorAttachment, + PassThroughWorkerSelectorAttachment, + QueueAndMatchMode, + QueueLengthExceptionTrigger, + QueueSelectorAttachment, + QueueWeightedAllocation, + ReclassifyExceptionAction, + ReclassifyJobResult, + RoundRobinMode, + RouterChannel, + RouterJob, + RouterJobAssignment, + RouterJobNote, + RouterJobOffer, + RouterJobPositionDetails, + RouterQueue, + RouterQueueSelector, + RouterQueueStatistics, + RouterRule, + RouterWorker, + RouterWorkerAssignment, + RouterWorkerSelector, + RuleEngineQueueSelectorAttachment, + RuleEngineWorkerSelectorAttachment, + ScheduleAndSuspendMode, + ScoringRuleOptions, + StaticQueueSelectorAttachment, + StaticRouterRule, + StaticWorkerSelectorAttachment, + SuspendMode, + UnassignJobOptions, + UnassignJobResult, + WaitTimeExceptionTrigger, + WebhookRouterRule, + WeightedAllocationQueueSelectorAttachment, + WeightedAllocationWorkerSelectorAttachment, + WorkerSelectorAttachment, + WorkerWeightedAllocation, +) + +from ._enums import ( # type: ignore + DistributionModeKind, + ExceptionActionKind, + ExceptionTriggerKind, + ExpressionRouterRuleLanguage, + JobMatchingModeKind, + LabelOperator, + QueueSelectorAttachmentKind, + RouterJobStatus, + RouterJobStatusSelector, + RouterRuleKind, + RouterWorkerSelectorStatus, + RouterWorkerState, + RouterWorkerStateSelector, + ScoringRuleParameterSelector, + WorkerSelectorAttachmentKind, +) from ._patch import __all__ as _patch_all -from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ @@ -92,12 +108,16 @@ "BestWorkerMode", "CancelExceptionAction", "CancelJobOptions", + "CancelJobResult", "ClassificationPolicy", "CloseJobOptions", + "CloseJobResult", "CompleteJobOptions", + "CompleteJobResult", "ConditionalQueueSelectorAttachment", "ConditionalWorkerSelectorAttachment", "DeclineJobOfferOptions", + "DeclineJobOfferResult", "DirectMapRouterRule", "DistributionMode", "DistributionPolicy", @@ -119,6 +139,7 @@ "QueueSelectorAttachment", "QueueWeightedAllocation", "ReclassifyExceptionAction", + "ReclassifyJobResult", "RoundRobinMode", "RouterChannel", "RouterJob", @@ -165,5 +186,5 @@ "ScoringRuleParameterSelector", "WorkerSelectorAttachmentKind", ] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py index 56b16aa93487..df5119d76f8d 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_models.py @@ -1,17 +1,17 @@ +# pylint: disable=line-too-long,useless-suppression,too-many-lines # coding=utf-8 -# pylint: disable=too-many-lines,anomalous-backslash-in-string,name-too-long # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=useless-super-delegation import datetime from typing import Any, Dict, List, Literal, Mapping, Optional, TYPE_CHECKING, Union, overload -from .. import _model_base -from .._model_base import rest_discriminator, rest_field +from .._utils.model_base import Model as _Model, rest_discriminator, rest_field from ._enums import ( DistributionModeKind, ExceptionActionKind, @@ -23,15 +23,12 @@ ) if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from .. import models as _models -class AcceptJobOfferResult(_model_base.Model): +class AcceptJobOfferResult(_Model): """Response containing ids for the worker, job, and assignment from an accepted offer. - All required parameters must be populated in order to send to server. - :ivar assignment_id: Id of job assignment that assigns a worker that has accepted an offer to a job. Required. :vartype assignment_id: str @@ -41,11 +38,11 @@ class AcceptJobOfferResult(_model_base.Model): :vartype worker_id: str """ - assignment_id: str = rest_field(name="assignmentId") + assignment_id: str = rest_field(name="assignmentId", visibility=["read", "create", "update", "delete", "query"]) """Id of job assignment that assigns a worker that has accepted an offer to a job. Required.""" - job_id: str = rest_field(name="jobId") + job_id: str = rest_field(name="jobId", visibility=["read", "create", "update", "delete", "query"]) """Id of the job assigned. Required.""" - worker_id: str = rest_field(name="workerId") + worker_id: str = rest_field(name="workerId", visibility=["read", "create", "update", "delete", "query"]) """Id of the worker that has been assigned this job. Required.""" @overload @@ -55,27 +52,25 @@ def __init__( assignment_id: str, job_id: str, worker_id: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DistributionMode(_model_base.Model): +class DistributionMode(_Model): """Abstract base class for defining a distribution mode. You probably want to use the sub-classes and not this class directly. Known sub-classes are: BestWorkerMode, LongestIdleMode, RoundRobinMode - All required parameters must be populated in order to send to server. - :ivar min_concurrent_offers: Governs the minimum desired number of active concurrent offers a job can have. :vartype min_concurrent_offers: int @@ -92,17 +87,23 @@ class DistributionMode(_model_base.Model): :vartype kind: str or ~azure.communication.jobrouter.models.DistributionModeKind """ - __mapping__: Dict[str, _model_base.Model] = {} - min_concurrent_offers: Optional[int] = rest_field(name="minConcurrentOffers") + __mapping__: Dict[str, _Model] = {} + min_concurrent_offers: Optional[int] = rest_field( + name="minConcurrentOffers", visibility=["read", "create", "update", "delete", "query"] + ) """Governs the minimum desired number of active concurrent offers a job can have.""" - max_concurrent_offers: Optional[int] = rest_field(name="maxConcurrentOffers") + max_concurrent_offers: Optional[int] = rest_field( + name="maxConcurrentOffers", visibility=["read", "create", "update", "delete", "query"] + ) """Governs the maximum number of active concurrent offers a job can have.""" - bypass_selectors: Optional[bool] = rest_field(name="bypassSelectors") + bypass_selectors: Optional[bool] = rest_field( + name="bypassSelectors", visibility=["read", "create", "update", "delete", "query"] + ) """If set to true, then router will match workers to jobs even if they don't match label selectors. Warning: You may get workers that are not qualified for a job they are matched with if you set this variable to true. This flag is intended more for temporary usage. By default, set to false.""" - kind: str = rest_discriminator(name="kind") + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) """The type discriminator describing a sub-type of DistributionMode. Required. Known values are: \"bestWorker\", \"longestIdle\", and \"roundRobin\".""" @@ -114,24 +115,22 @@ def __init__( min_concurrent_offers: Optional[int] = None, max_concurrent_offers: Optional[int] = None, bypass_selectors: Optional[bool] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) class BestWorkerMode(DistributionMode, discriminator="bestWorker"): """Jobs are distributed to the worker with the strongest abilities available. - All required parameters must be populated in order to send to server. - :ivar min_concurrent_offers: Governs the minimum desired number of active concurrent offers a job can have. :vartype min_concurrent_offers: int @@ -146,7 +145,8 @@ class BestWorkerMode(DistributionMode, discriminator="bestWorker"): :ivar scoring_rule: Define a scoring rule to use, when calculating a score to determine the best worker. If not set, will use a default scoring formula that uses the number of job labels that the worker labels match, as well as the number of label selectors the worker labels match - and/or exceed using a logistic function (https://en.wikipedia.org/wiki/Logistic_function). + and/or exceed using a logistic function (`https://en.wikipedia.org/wiki/Logistic_function + `_). :vartype scoring_rule: ~azure.communication.jobrouter.models.RouterRule :ivar scoring_rule_options: Options to configure 'scoringRule'. If not set, default values are used. @@ -156,14 +156,19 @@ class BestWorkerMode(DistributionMode, discriminator="bestWorker"): :vartype kind: str or ~azure.communication.jobrouter.models.BEST_WORKER """ - scoring_rule: Optional["_models.RouterRule"] = rest_field(name="scoringRule") + scoring_rule: Optional["_models.RouterRule"] = rest_field( + name="scoringRule", visibility=["read", "create", "update", "delete", "query"] + ) """Define a scoring rule to use, when calculating a score to determine the best worker. If not set, will use a default scoring formula that uses the number of job labels that the worker labels match, as well as the number of label selectors the worker labels match and/or exceed - using a logistic function (https://en.wikipedia.org/wiki/Logistic_function).""" - scoring_rule_options: Optional["_models.ScoringRuleOptions"] = rest_field(name="scoringRuleOptions") + using a logistic function (`https://en.wikipedia.org/wiki/Logistic_function + `_).""" + scoring_rule_options: Optional["_models.ScoringRuleOptions"] = rest_field( + name="scoringRuleOptions", visibility=["read", "create", "update", "delete", "query"] + ) """Options to configure 'scoringRule'. If not set, default values are used.""" - kind: Literal[DistributionModeKind.BEST_WORKER] = rest_discriminator(name="kind") # type: ignore + kind: Literal[DistributionModeKind.BEST_WORKER] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of Mode. Required. Discriminator value for BestWorkerMode.""" @@ -176,27 +181,25 @@ def __init__( bypass_selectors: Optional[bool] = None, scoring_rule: Optional["_models.RouterRule"] = None, scoring_rule_options: Optional["_models.ScoringRuleOptions"] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=DistributionModeKind.BEST_WORKER, **kwargs) -class ExceptionAction(_model_base.Model): +class ExceptionAction(_Model): """The action to take when the exception is triggered. You probably want to use the sub-classes and not this class directly. Known sub-classes are: CancelExceptionAction, ManualReclassifyExceptionAction, ReclassifyExceptionAction - All required parameters must be populated in order to send to server. - :ivar id: Unique Id of the exception action. :vartype id: str :ivar kind: The type discriminator describing a sub-type of ExceptionAction. Required. Known @@ -204,10 +207,10 @@ class ExceptionAction(_model_base.Model): :vartype kind: str or ~azure.communication.jobrouter.models.ExceptionActionKind """ - __mapping__: Dict[str, _model_base.Model] = {} - id: Optional[str] = rest_field() + __mapping__: Dict[str, _Model] = {} + id: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Unique Id of the exception action.""" - kind: str = rest_discriminator(name="kind") + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) """The type discriminator describing a sub-type of ExceptionAction. Required. Known values are: \"cancel\", \"manualReclassify\", and \"reclassify\".""" @@ -217,24 +220,22 @@ def __init__( *, kind: str, id: Optional[str] = None, # pylint: disable=redefined-builtin - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) class CancelExceptionAction(ExceptionAction, discriminator="cancel"): """An action that marks a job as cancelled. - All required parameters must be populated in order to send to server. - :ivar id: Unique Id of the exception action. :vartype id: str :ivar note: A note that will be appended to a job's notes collection with the current @@ -248,11 +249,13 @@ class CancelExceptionAction(ExceptionAction, discriminator="cancel"): :vartype kind: str or ~azure.communication.jobrouter.models.CANCEL """ - note: Optional[str] = rest_field() + note: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A note that will be appended to a job's notes collection with the current timestamp.""" - disposition_code: Optional[str] = rest_field(name="dispositionCode") + disposition_code: Optional[str] = rest_field( + name="dispositionCode", visibility=["read", "create", "update", "delete", "query"] + ) """Indicates the outcome of a job, populate this field with your own custom values.""" - kind: Literal[ExceptionActionKind.CANCEL] = rest_discriminator(name="kind") # type: ignore + kind: Literal[ExceptionActionKind.CANCEL] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of ExceptionAction. Required. Discriminator value for CancelExceptionAction.""" @@ -263,20 +266,20 @@ def __init__( id: Optional[str] = None, # pylint: disable=redefined-builtin note: Optional[str] = None, disposition_code: Optional[str] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=ExceptionActionKind.CANCEL, **kwargs) -class CancelJobOptions(_model_base.Model): +class CancelJobOptions(_Model): """Request payload for cancelling a job. :ivar note: A note that will be appended to a job's Notes collection with the current @@ -287,9 +290,11 @@ class CancelJobOptions(_model_base.Model): :vartype disposition_code: str """ - note: Optional[str] = rest_field() + note: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A note that will be appended to a job's Notes collection with the current timestamp.""" - disposition_code: Optional[str] = rest_field(name="dispositionCode") + disposition_code: Optional[str] = rest_field( + name="dispositionCode", visibility=["read", "create", "update", "delete", "query"] + ) """Indicates the outcome of a job, populate this field with your own custom values. If not provided, default value of \"Cancelled\" is set.""" @@ -299,30 +304,26 @@ def __init__( *, note: Optional[str] = None, disposition_code: Optional[str] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class CancelJobResult(_model_base.Model): +class CancelJobResult(_Model): """Response payload from cancelling a job.""" -class ClassificationPolicy(_model_base.Model): +class ClassificationPolicy(_Model): """A container for the rules that govern how jobs are classified. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar etag: The entity tag for this resource. Required. :vartype etag: str :ivar id: Id of a classification policy. Required. @@ -347,18 +348,22 @@ class ClassificationPolicy(_model_base.Model): """The entity tag for this resource. Required.""" id: str = rest_field(visibility=["read"]) """Id of a classification policy. Required.""" - name: Optional[str] = rest_field() + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Friendly name of this policy.""" - fallback_queue_id: Optional[str] = rest_field(name="fallbackQueueId") + fallback_queue_id: Optional[str] = rest_field( + name="fallbackQueueId", visibility=["read", "create", "update", "delete", "query"] + ) """Id of a fallback queue to select if queue selector attachments doesn't find a match.""" queue_selector_attachments: Optional[List["_models.QueueSelectorAttachment"]] = rest_field( - name="queueSelectorAttachments" + name="queueSelectorAttachments", visibility=["read", "create", "update", "delete", "query"] ) """Queue selector attachments used to resolve a queue for a job.""" - prioritization_rule: Optional["_models.RouterRule"] = rest_field(name="prioritizationRule") + prioritization_rule: Optional["_models.RouterRule"] = rest_field( + name="prioritizationRule", visibility=["read", "create", "update", "delete", "query"] + ) """A rule to determine a priority score for a job.""" worker_selector_attachments: Optional[List["_models.WorkerSelectorAttachment"]] = rest_field( - name="workerSelectorAttachments" + name="workerSelectorAttachments", visibility=["read", "create", "update", "delete", "query"] ) """Worker selector attachments used to attach worker selectors to a job.""" @@ -371,20 +376,20 @@ def __init__( queue_selector_attachments: Optional[List["_models.QueueSelectorAttachment"]] = None, prioritization_rule: Optional["_models.RouterRule"] = None, worker_selector_attachments: Optional[List["_models.WorkerSelectorAttachment"]] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class CloseJobOptions(_model_base.Model): +class CloseJobOptions(_Model): """Request payload for closing jobs. :ivar disposition_code: Indicates the outcome of a job, populate this field with your own @@ -399,13 +404,17 @@ class CloseJobOptions(_model_base.Model): :vartype note: str """ - disposition_code: Optional[str] = rest_field(name="dispositionCode") + disposition_code: Optional[str] = rest_field( + name="dispositionCode", visibility=["read", "create", "update", "delete", "query"] + ) """Indicates the outcome of a job, populate this field with your own custom values.""" - close_at: Optional[datetime.datetime] = rest_field(name="closeAt", format="rfc3339") + close_at: Optional[datetime.datetime] = rest_field( + name="closeAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """If not provided, worker capacity is released immediately along with a JobClosedEvent notification. If provided, worker capacity is released along with a JobClosedEvent notification at a future time in UTC.""" - note: Optional[str] = rest_field() + note: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A note that will be appended to a job's Notes collection with the current timestamp.""" @overload @@ -415,24 +424,24 @@ def __init__( disposition_code: Optional[str] = None, close_at: Optional[datetime.datetime] = None, note: Optional[str] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class CloseJobResult(_model_base.Model): +class CloseJobResult(_Model): """Response payload from closing a job.""" -class CompleteJobOptions(_model_base.Model): +class CompleteJobOptions(_Model): """Request payload for completing jobs. :ivar note: A note that will be appended to a job's Notes collection with the current @@ -440,7 +449,7 @@ class CompleteJobOptions(_model_base.Model): :vartype note: str """ - note: Optional[str] = rest_field() + note: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A note that will be appended to a job's Notes collection with the current timestamp.""" @overload @@ -448,24 +457,24 @@ def __init__( self, *, note: Optional[str] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class CompleteJobResult(_model_base.Model): +class CompleteJobResult(_Model): """Response payload from completing a job.""" -class QueueSelectorAttachment(_model_base.Model): +class QueueSelectorAttachment(_Model): """An attachment of queue selectors to resolve a queue to a job from a classification policy. You probably want to use the sub-classes and not this class directly. Known sub-classes are: @@ -473,16 +482,14 @@ class QueueSelectorAttachment(_model_base.Model): RuleEngineQueueSelectorAttachment, StaticQueueSelectorAttachment, WeightedAllocationQueueSelectorAttachment - All required parameters must be populated in order to send to server. - :ivar kind: The type discriminator describing a sub-type of QueueSelectorAttachment. Required. Known values are: "conditional", "passThrough", "ruleEngine", "static", and "weightedAllocation". :vartype kind: str or ~azure.communication.jobrouter.models.QueueSelectorAttachmentKind """ - __mapping__: Dict[str, _model_base.Model] = {} - kind: str = rest_discriminator(name="kind") + __mapping__: Dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) """The type discriminator describing a sub-type of QueueSelectorAttachment. Required. Known values are: \"conditional\", \"passThrough\", \"ruleEngine\", \"static\", and \"weightedAllocation\".""" @@ -491,16 +498,16 @@ def __init__( self, *, kind: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -508,8 +515,6 @@ class ConditionalQueueSelectorAttachment(QueueSelectorAttachment, discriminator= """Describes a set of queue selectors that will be attached if the given condition resolves to true. - All required parameters must be populated in order to send to server. - :ivar condition: The condition that must be true for the queue selectors to be attached. Required. :vartype condition: ~azure.communication.jobrouter.models.RouterRule @@ -520,11 +525,13 @@ class ConditionalQueueSelectorAttachment(QueueSelectorAttachment, discriminator= :vartype kind: str or ~azure.communication.jobrouter.models.CONDITIONAL """ - condition: "_models.RouterRule" = rest_field() + condition: "_models.RouterRule" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The condition that must be true for the queue selectors to be attached. Required.""" - queue_selectors: List["_models.RouterQueueSelector"] = rest_field(name="queueSelectors") + queue_selectors: List["_models.RouterQueueSelector"] = rest_field( + name="queueSelectors", visibility=["read", "create", "update", "delete", "query"] + ) """The queue selectors to attach. Required.""" - kind: Literal[QueueSelectorAttachmentKind.CONDITIONAL] = rest_discriminator(name="kind") # type: ignore + kind: Literal[QueueSelectorAttachmentKind.CONDITIONAL] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing the type of queue selector attachment. Required. Discriminator value for ConditionalQueueSelectorAttachment.""" @@ -534,20 +541,20 @@ def __init__( *, condition: "_models.RouterRule", queue_selectors: List["_models.RouterQueueSelector"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=QueueSelectorAttachmentKind.CONDITIONAL, **kwargs) -class WorkerSelectorAttachment(_model_base.Model): +class WorkerSelectorAttachment(_Model): """An attachment which attaches worker selectors to a job. You probably want to use the sub-classes and not this class directly. Known sub-classes are: @@ -555,16 +562,14 @@ class WorkerSelectorAttachment(_model_base.Model): RuleEngineWorkerSelectorAttachment, StaticWorkerSelectorAttachment, WeightedAllocationWorkerSelectorAttachment - All required parameters must be populated in order to send to server. - :ivar kind: The type discriminator describing a sub-type of WorkerSelectorAttachment. Required. Known values are: "conditional", "passThrough", "ruleEngine", "static", and "weightedAllocation". :vartype kind: str or ~azure.communication.jobrouter.models.WorkerSelectorAttachmentKind """ - __mapping__: Dict[str, _model_base.Model] = {} - kind: str = rest_discriminator(name="kind") + __mapping__: Dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) """The type discriminator describing a sub-type of WorkerSelectorAttachment. Required. Known values are: \"conditional\", \"passThrough\", \"ruleEngine\", \"static\", and \"weightedAllocation\".""" @@ -574,16 +579,16 @@ def __init__( self, *, kind: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -591,8 +596,6 @@ class ConditionalWorkerSelectorAttachment(WorkerSelectorAttachment, discriminato """Describes a set of worker selectors that will be attached if the given condition resolves to true. - All required parameters must be populated in order to send to server. - :ivar condition: The condition that must be true for the worker selectors to be attached. Required. :vartype condition: ~azure.communication.jobrouter.models.RouterRule @@ -603,11 +606,13 @@ class ConditionalWorkerSelectorAttachment(WorkerSelectorAttachment, discriminato :vartype kind: str or ~azure.communication.jobrouter.models.CONDITIONAL """ - condition: "_models.RouterRule" = rest_field() + condition: "_models.RouterRule" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The condition that must be true for the worker selectors to be attached. Required.""" - worker_selectors: List["_models.RouterWorkerSelector"] = rest_field(name="workerSelectors") + worker_selectors: List["_models.RouterWorkerSelector"] = rest_field( + name="workerSelectors", visibility=["read", "create", "update", "delete", "query"] + ) """The worker selectors to attach. Required.""" - kind: Literal[WorkerSelectorAttachmentKind.CONDITIONAL] = rest_discriminator(name="kind") # type: ignore + kind: Literal[WorkerSelectorAttachmentKind.CONDITIONAL] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing the type of worker selector attachment. Required. Discriminator value for ConditionalWorkerSelectorAttachment.""" @@ -617,20 +622,20 @@ def __init__( *, condition: "_models.RouterRule", worker_selectors: List["_models.RouterWorkerSelector"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=WorkerSelectorAttachmentKind.CONDITIONAL, **kwargs) -class DeclineJobOfferOptions(_model_base.Model): +class DeclineJobOfferOptions(_Model): """Request payload for declining offers. :ivar retry_offer_at: If the RetryOfferAt is not provided, then this job will not be offered @@ -641,7 +646,9 @@ class DeclineJobOfferOptions(_model_base.Model): :vartype retry_offer_at: ~datetime.datetime """ - retry_offer_at: Optional[datetime.datetime] = rest_field(name="retryOfferAt", format="rfc3339") + retry_offer_at: Optional[datetime.datetime] = rest_field( + name="retryOfferAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """If the RetryOfferAt is not provided, then this job will not be offered again to the worker who declined this job unless the worker is de-registered and re-registered. If a RetryOfferAt time is provided, then the job will be re-matched to eligible workers at the retry time in UTC. The @@ -652,24 +659,24 @@ def __init__( self, *, retry_offer_at: Optional[datetime.datetime] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class DeclineJobOfferResult(_model_base.Model): +class DeclineJobOfferResult(_Model): """Response payload from declining a job.""" -class RouterRule(_model_base.Model): +class RouterRule(_Model): """A rule of one of the following types: StaticRule: A rule providing static rules that always return the same result, regardless of input. @@ -683,15 +690,13 @@ class RouterRule(_model_base.Model): DirectMapRouterRule, ExpressionRouterRule, FunctionRouterRule, StaticRouterRule, WebhookRouterRule - All required parameters must be populated in order to send to server. - :ivar kind: The type discriminator describing a sub-type of RouterRule. Required. Known values are: "directMap", "expression", "function", "static", and "webhook". :vartype kind: str or ~azure.communication.jobrouter.models.RouterRuleKind """ - __mapping__: Dict[str, _model_base.Model] = {} - kind: str = rest_discriminator(name="kind") + __mapping__: Dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) """The type discriminator describing a sub-type of RouterRule. Required. Known values are: \"directMap\", \"expression\", \"function\", \"static\", and \"webhook\".""" @@ -700,40 +705,49 @@ def __init__( self, *, kind: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) class DirectMapRouterRule(RouterRule, discriminator="directMap"): """A rule that return the same labels as the input labels. - All required parameters must be populated in order to send to server. - :ivar kind: The type discriminator describing a sub-type of Rule. Required. Discriminator value for DirectMapRouterRule. :vartype kind: str or ~azure.communication.jobrouter.models.DIRECT_MAP """ - kind: Literal[RouterRuleKind.DIRECT_MAP] = rest_discriminator(name="kind") # type: ignore + kind: Literal[RouterRuleKind.DIRECT_MAP] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of Rule. Required. Discriminator value for DirectMapRouterRule.""" + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ -class DistributionPolicy(_model_base.Model): - """Policy governing how jobs are distributed to workers. + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, kind=RouterRuleKind.DIRECT_MAP, **kwargs) - Readonly variables are only populated by the server, and will be ignored when sending a request. - All required parameters must be populated in order to send to server. +class DistributionPolicy(_Model): + """Policy governing how jobs are distributed to workers. :ivar etag: The entity tag for this resource. Required. :vartype etag: str @@ -752,11 +766,13 @@ class DistributionPolicy(_model_base.Model): """The entity tag for this resource. Required.""" id: str = rest_field(visibility=["read"]) """Id of a distribution policy. Required.""" - name: Optional[str] = rest_field() + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Friendly name of this policy.""" - offer_expires_after_seconds: Optional[float] = rest_field(name="offerExpiresAfterSeconds") + offer_expires_after_seconds: Optional[float] = rest_field( + name="offerExpiresAfterSeconds", visibility=["read", "create", "update", "delete", "query"] + ) """Number of seconds after which any offers created under this policy will be expired.""" - mode: Optional["_models.DistributionMode"] = rest_field() + mode: Optional["_models.DistributionMode"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Mode governing the specific distribution method.""" @overload @@ -766,26 +782,22 @@ def __init__( name: Optional[str] = None, offer_expires_after_seconds: Optional[float] = None, mode: Optional["_models.DistributionMode"] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ExceptionPolicy(_model_base.Model): +class ExceptionPolicy(_Model): """A policy that defines actions to execute when exception are triggered. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar etag: The entity tag for this resource. Required. :vartype etag: str :ivar id: Id of an exception policy. Required. @@ -800,9 +812,11 @@ class ExceptionPolicy(_model_base.Model): """The entity tag for this resource. Required.""" id: str = rest_field(visibility=["read"]) """Id of an exception policy. Required.""" - name: Optional[str] = rest_field() + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Friendly name of this policy.""" - exception_rules: Optional[List["_models.ExceptionRule"]] = rest_field(name="exceptionRules") + exception_rules: Optional[List["_models.ExceptionRule"]] = rest_field( + name="exceptionRules", visibility=["read", "create", "update", "delete", "query"] + ) """A collection of exception rules on the exception policy.""" @overload @@ -811,24 +825,22 @@ def __init__( *, name: Optional[str] = None, exception_rules: Optional[List["_models.ExceptionRule"]] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ExceptionRule(_model_base.Model): +class ExceptionRule(_Model): """A rule that defines actions to execute upon a specific trigger. - All required parameters must be populated in order to send to server. - :ivar id: Id of an exception rule. Required. :vartype id: str :ivar trigger: The trigger for this exception rule. Required. @@ -837,11 +849,11 @@ class ExceptionRule(_model_base.Model): :vartype actions: list[~azure.communication.jobrouter.models.ExceptionAction] """ - id: str = rest_field() + id: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Id of an exception rule. Required.""" - trigger: "_models.ExceptionTrigger" = rest_field() + trigger: "_models.ExceptionTrigger" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The trigger for this exception rule. Required.""" - actions: List["_models.ExceptionAction"] = rest_field() + actions: List["_models.ExceptionAction"] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A collection of actions to perform once the exception is triggered. Required.""" @overload @@ -851,34 +863,32 @@ def __init__( id: str, # pylint: disable=redefined-builtin trigger: "_models.ExceptionTrigger", actions: List["_models.ExceptionAction"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class ExceptionTrigger(_model_base.Model): +class ExceptionTrigger(_Model): """Abstract base class for defining a trigger for exception rules. You probably want to use the sub-classes and not this class directly. Known sub-classes are: QueueLengthExceptionTrigger, WaitTimeExceptionTrigger - All required parameters must be populated in order to send to server. - :ivar kind: The type discriminator describing a sub-type of ExceptionTrigger. Required. Known values are: "queueLength" and "waitTime". :vartype kind: str or ~azure.communication.jobrouter.models.ExceptionTriggerKind """ - __mapping__: Dict[str, _model_base.Model] = {} - kind: str = rest_discriminator(name="kind") + __mapping__: Dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) """The type discriminator describing a sub-type of ExceptionTrigger. Required. Known values are: \"queueLength\" and \"waitTime\".""" @@ -887,24 +897,22 @@ def __init__( self, *, kind: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) class ExpressionRouterRule(RouterRule, discriminator="expression"): """A rule providing inline expression rules. - All required parameters must be populated in order to send to server. - :ivar language: The expression language to compile to and execute. "powerFx" :vartype language: str or ~azure.communication.jobrouter.models.ExpressionRouterRuleLanguage :ivar expression: An expression to evaluate. Should contain return statement with calculated @@ -915,11 +923,13 @@ class ExpressionRouterRule(RouterRule, discriminator="expression"): :vartype kind: str or ~azure.communication.jobrouter.models.EXPRESSION """ - language: Optional[Union[str, "_models.ExpressionRouterRuleLanguage"]] = rest_field() + language: Optional[Union[str, "_models.ExpressionRouterRuleLanguage"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """The expression language to compile to and execute. \"powerFx\"""" - expression: str = rest_field() + expression: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """An expression to evaluate. Should contain return statement with calculated values. Required.""" - kind: Literal[RouterRuleKind.EXPRESSION] = rest_discriminator(name="kind") # type: ignore + kind: Literal[RouterRuleKind.EXPRESSION] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of Rule. Required. Discriminator value for ExpressionRouterRule.""" @@ -929,24 +939,22 @@ def __init__( *, expression: str, language: Optional[Union[str, "_models.ExpressionRouterRuleLanguage"]] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=RouterRuleKind.EXPRESSION, **kwargs) class FunctionRouterRule(RouterRule, discriminator="function"): """A rule providing a binding to an HTTP Triggered Azure Function. - All required parameters must be populated in order to send to server. - :ivar function_uri: URL for Azure Function. Required. :vartype function_uri: str :ivar credential: Credentials used to access Azure function rule. @@ -956,11 +964,13 @@ class FunctionRouterRule(RouterRule, discriminator="function"): :vartype kind: str or ~azure.communication.jobrouter.models.FUNCTION """ - function_uri: str = rest_field(name="functionUri") + function_uri: str = rest_field(name="functionUri", visibility=["read", "create", "update", "delete", "query"]) """URL for Azure Function. Required.""" - credential: Optional["_models.FunctionRouterRuleCredential"] = rest_field() + credential: Optional["_models.FunctionRouterRuleCredential"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Credentials used to access Azure function rule.""" - kind: Literal[RouterRuleKind.FUNCTION] = rest_discriminator(name="kind") # type: ignore + kind: Literal[RouterRuleKind.FUNCTION] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of Rule. Required. Discriminator value for FunctionRouterRule.""" @@ -970,20 +980,20 @@ def __init__( *, function_uri: str, credential: Optional["_models.FunctionRouterRuleCredential"] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=RouterRuleKind.FUNCTION, **kwargs) -class FunctionRouterRuleCredential(_model_base.Model): +class FunctionRouterRuleCredential(_Model): """Credentials used to access Azure function rule. :ivar function_key: Access key scoped to a particular function. @@ -996,12 +1006,14 @@ class FunctionRouterRuleCredential(_model_base.Model): :vartype client_id: str """ - function_key: Optional[str] = rest_field(name="functionKey") + function_key: Optional[str] = rest_field( + name="functionKey", visibility=["read", "create", "update", "delete", "query"] + ) """Access key scoped to a particular function.""" - app_key: Optional[str] = rest_field(name="appKey") + app_key: Optional[str] = rest_field(name="appKey", visibility=["read", "create", "update", "delete", "query"]) """Access key scoped to a Azure Function app. This key grants access to all functions under the app.""" - client_id: Optional[str] = rest_field(name="clientId") + client_id: Optional[str] = rest_field(name="clientId", visibility=["read", "create", "update", "delete", "query"]) """Client id, when AppKey is provided In context of Azure function, this is usually the name of the key.""" @@ -1012,20 +1024,20 @@ def __init__( function_key: Optional[str] = None, app_key: Optional[str] = None, client_id: Optional[str] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class JobMatchingMode(_model_base.Model): +class JobMatchingMode(_Model): """A matching mode of one of the following types: QueueAndMatchMode: Used when matching worker to a job is required to be done right after job is queued. @@ -1036,15 +1048,13 @@ class JobMatchingMode(_model_base.Model): You probably want to use the sub-classes and not this class directly. Known sub-classes are: QueueAndMatchMode, ScheduleAndSuspendMode, SuspendMode - All required parameters must be populated in order to send to server. - :ivar kind: The type discriminator describing a sub-type of JobMatchingMode. Required. Known values are: "queueAndMatch", "scheduleAndSuspend", and "suspend". :vartype kind: str or ~azure.communication.jobrouter.models.JobMatchingModeKind """ - __mapping__: Dict[str, _model_base.Model] = {} - kind: str = rest_discriminator(name="kind") + __mapping__: Dict[str, _Model] = {} + kind: str = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) """The type discriminator describing a sub-type of JobMatchingMode. Required. Known values are: \"queueAndMatch\", \"scheduleAndSuspend\", and \"suspend\".""" @@ -1053,24 +1063,22 @@ def __init__( self, *, kind: str, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) class LongestIdleMode(DistributionMode, discriminator="longestIdle"): """Jobs are directed to the worker who has been idle longest. - All required parameters must be populated in order to send to server. - :ivar min_concurrent_offers: Governs the minimum desired number of active concurrent offers a job can have. :vartype min_concurrent_offers: int @@ -1087,7 +1095,7 @@ class LongestIdleMode(DistributionMode, discriminator="longestIdle"): :vartype kind: str or ~azure.communication.jobrouter.models.LONGEST_IDLE """ - kind: Literal[DistributionModeKind.LONGEST_IDLE] = rest_discriminator(name="kind") # type: ignore + kind: Literal[DistributionModeKind.LONGEST_IDLE] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of Mode. Required. Discriminator value for LongestIdleMode.""" @@ -1098,16 +1106,16 @@ def __init__( min_concurrent_offers: Optional[int] = None, max_concurrent_offers: Optional[int] = None, bypass_selectors: Optional[bool] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=DistributionModeKind.LONGEST_IDLE, **kwargs) @@ -1115,8 +1123,6 @@ class ManualReclassifyExceptionAction(ExceptionAction, discriminator="manualRecl """An action that manually reclassifies a job by providing the queue, priority and worker selectors. - All required parameters must be populated in order to send to server. - :ivar id: Unique Id of the exception action. :vartype id: str :ivar queue_id: Updated QueueId. @@ -1130,13 +1136,15 @@ class ManualReclassifyExceptionAction(ExceptionAction, discriminator="manualRecl :vartype kind: str or ~azure.communication.jobrouter.models.MANUAL_RECLASSIFY """ - queue_id: Optional[str] = rest_field(name="queueId") + queue_id: Optional[str] = rest_field(name="queueId", visibility=["read", "create", "update", "delete", "query"]) """Updated QueueId.""" - priority: Optional[int] = rest_field() + priority: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Updated Priority.""" - worker_selectors: Optional[List["_models.RouterWorkerSelector"]] = rest_field(name="workerSelectors") + worker_selectors: Optional[List["_models.RouterWorkerSelector"]] = rest_field( + name="workerSelectors", visibility=["read", "create", "update", "delete", "query"] + ) """Updated WorkerSelectors.""" - kind: Literal[ExceptionActionKind.MANUAL_RECLASSIFY] = rest_discriminator(name="kind") # type: ignore + kind: Literal[ExceptionActionKind.MANUAL_RECLASSIFY] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of ExceptionAction. Required. Discriminator value for ManualReclassifyExceptionAction.""" @@ -1148,22 +1156,23 @@ def __init__( queue_id: Optional[str] = None, priority: Optional[int] = None, worker_selectors: Optional[List["_models.RouterWorkerSelector"]] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=ExceptionActionKind.MANUAL_RECLASSIFY, **kwargs) -class OAuth2WebhookClientCredential(_model_base.Model): +class OAuth2WebhookClientCredential(_Model): """OAuth2.0 Credentials used to Contoso's Authorization server. Reference: - https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/. + `https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ + `_. :ivar client_id: ClientId for Contoso Authorization server. :vartype client_id: str @@ -1171,9 +1180,11 @@ class OAuth2WebhookClientCredential(_model_base.Model): :vartype client_secret: str """ - client_id: Optional[str] = rest_field(name="clientId") + client_id: Optional[str] = rest_field(name="clientId", visibility=["read", "create", "update", "delete", "query"]) """ClientId for Contoso Authorization server.""" - client_secret: Optional[str] = rest_field(name="clientSecret") + client_secret: Optional[str] = rest_field( + name="clientSecret", visibility=["read", "create", "update", "delete", "query"] + ) """Client secret for Contoso Authorization server.""" @overload @@ -1182,16 +1193,16 @@ def __init__( *, client_id: Optional[str] = None, client_secret: Optional[str] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) @@ -1199,8 +1210,6 @@ class PassThroughQueueSelectorAttachment(QueueSelectorAttachment, discriminator= """Attaches a queue selector where the value is passed through from a job's label with the same key. - All required parameters must be populated in order to send to server. - :ivar key: The label key to query against. Required. :vartype key: str :ivar label_operator: Describes how the value of the label is compared to the value pass @@ -1212,13 +1221,15 @@ class PassThroughQueueSelectorAttachment(QueueSelectorAttachment, discriminator= :vartype kind: str or ~azure.communication.jobrouter.models.PASS_THROUGH """ - key: str = rest_field() + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The label key to query against. Required.""" - label_operator: Union[str, "_models.LabelOperator"] = rest_field(name="labelOperator") + label_operator: Union[str, "_models.LabelOperator"] = rest_field( + name="labelOperator", visibility=["read", "create", "update", "delete", "query"] + ) """Describes how the value of the label is compared to the value pass through. Required. Known values are: \"equal\", \"notEqual\", \"lessThan\", \"lessThanOrEqual\", \"greaterThan\", and \"greaterThanOrEqual\".""" - kind: Literal[QueueSelectorAttachmentKind.PASS_THROUGH] = rest_discriminator(name="kind") # type: ignore + kind: Literal[QueueSelectorAttachmentKind.PASS_THROUGH] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing the type of queue selector attachment. Required. Discriminator value for PassThroughQueueSelectorAttachment.""" @@ -1228,16 +1239,16 @@ def __init__( *, key: str, label_operator: Union[str, "_models.LabelOperator"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=QueueSelectorAttachmentKind.PASS_THROUGH, **kwargs) @@ -1245,8 +1256,6 @@ class PassThroughWorkerSelectorAttachment(WorkerSelectorAttachment, discriminato """Attaches a worker selector where the value is passed through from a job's label with the same key. - All required parameters must be populated in order to send to server. - :ivar key: The label key to query against. Required. :vartype key: str :ivar label_operator: Describes how the value of the label is compared to the value pass @@ -1261,15 +1270,19 @@ class PassThroughWorkerSelectorAttachment(WorkerSelectorAttachment, discriminato :vartype kind: str or ~azure.communication.jobrouter.models.PASS_THROUGH """ - key: str = rest_field() + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The label key to query against. Required.""" - label_operator: Union[str, "_models.LabelOperator"] = rest_field(name="labelOperator") + label_operator: Union[str, "_models.LabelOperator"] = rest_field( + name="labelOperator", visibility=["read", "create", "update", "delete", "query"] + ) """Describes how the value of the label is compared to the value pass through. Required. Known values are: \"equal\", \"notEqual\", \"lessThan\", \"lessThanOrEqual\", \"greaterThan\", and \"greaterThanOrEqual\".""" - expires_after_seconds: Optional[float] = rest_field(name="expiresAfterSeconds") + expires_after_seconds: Optional[float] = rest_field( + name="expiresAfterSeconds", visibility=["read", "create", "update", "delete", "query"] + ) """Describes how long the attached label selector is valid in seconds.""" - kind: Literal[WorkerSelectorAttachmentKind.PASS_THROUGH] = rest_discriminator(name="kind") # type: ignore + kind: Literal[WorkerSelectorAttachmentKind.PASS_THROUGH] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing the type of worker selector attachment. Required. Discriminator value for PassThroughWorkerSelectorAttachment.""" @@ -1280,16 +1293,16 @@ def __init__( key: str, label_operator: Union[str, "_models.LabelOperator"], expires_after_seconds: Optional[float] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=WorkerSelectorAttachmentKind.PASS_THROUGH, **kwargs) @@ -1297,23 +1310,34 @@ class QueueAndMatchMode(JobMatchingMode, discriminator="queueAndMatch"): """Describes a matching mode where matching worker to a job is automatically started after job is queued successfully. - All required parameters must be populated in order to send to server. - :ivar kind: The type discriminator describing QueueAndMatchMode. Required. Discriminator value for QueueAndMatchMode. :vartype kind: str or ~azure.communication.jobrouter.models.QUEUE_AND_MATCH """ - kind: Literal[JobMatchingModeKind.QUEUE_AND_MATCH] = rest_discriminator(name="kind") # type: ignore + kind: Literal[JobMatchingModeKind.QUEUE_AND_MATCH] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing QueueAndMatchMode. Required. Discriminator value for QueueAndMatchMode.""" + @overload + def __init__( + self, + ) -> None: ... + + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, kind=JobMatchingModeKind.QUEUE_AND_MATCH, **kwargs) + class QueueLengthExceptionTrigger(ExceptionTrigger, discriminator="queueLength"): """Trigger for an exception action on exceeding queue length. - All required parameters must be populated in order to send to server. - :ivar threshold: Threshold of number of jobs ahead in the queue to for this trigger to fire. Required. :vartype threshold: int @@ -1322,9 +1346,9 @@ class QueueLengthExceptionTrigger(ExceptionTrigger, discriminator="queueLength") :vartype kind: str or ~azure.communication.jobrouter.models.QUEUE_LENGTH """ - threshold: int = rest_field() + threshold: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Threshold of number of jobs ahead in the queue to for this trigger to fire. Required.""" - kind: Literal[ExceptionTriggerKind.QUEUE_LENGTH] = rest_discriminator(name="kind") # type: ignore + kind: Literal[ExceptionTriggerKind.QUEUE_LENGTH] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of ExceptionTrigger. Required. Discriminator value for QueueLengthExceptionTrigger.""" @@ -1333,25 +1357,23 @@ def __init__( self, *, threshold: int, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=ExceptionTriggerKind.QUEUE_LENGTH, **kwargs) -class QueueWeightedAllocation(_model_base.Model): +class QueueWeightedAllocation(_Model): """Contains the weight percentage and queue selectors to be applied if selected for weighted distributions. - All required parameters must be populated in order to send to server. - :ivar weight: The percentage of this weight, expressed as a fraction of 1. Required. :vartype weight: float :ivar queue_selectors: A collection of queue selectors that will be applied if this allocation @@ -1359,9 +1381,11 @@ class QueueWeightedAllocation(_model_base.Model): :vartype queue_selectors: list[~azure.communication.jobrouter.models.RouterQueueSelector] """ - weight: float = rest_field() + weight: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The percentage of this weight, expressed as a fraction of 1. Required.""" - queue_selectors: List["_models.RouterQueueSelector"] = rest_field(name="queueSelectors") + queue_selectors: List["_models.RouterQueueSelector"] = rest_field( + name="queueSelectors", visibility=["read", "create", "update", "delete", "query"] + ) """A collection of queue selectors that will be applied if this allocation is selected. Required.""" @overload @@ -1370,24 +1394,22 @@ def __init__( *, weight: float, queue_selectors: List["_models.RouterQueueSelector"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) class ReclassifyExceptionAction(ExceptionAction, discriminator="reclassify"): """An action that modifies labels on a job and then reclassifies it. - All required parameters must be populated in order to send to server. - :ivar id: Unique Id of the exception action. :vartype id: str :ivar classification_policy_id: The new classification policy that will determine queue, @@ -1401,12 +1423,16 @@ class ReclassifyExceptionAction(ExceptionAction, discriminator="reclassify"): :vartype kind: str or ~azure.communication.jobrouter.models.RECLASSIFY """ - classification_policy_id: Optional[str] = rest_field(name="classificationPolicyId") + classification_policy_id: Optional[str] = rest_field( + name="classificationPolicyId", visibility=["read", "create", "update", "delete", "query"] + ) """The new classification policy that will determine queue, priority and worker selectors.""" - labels_to_upsert: Optional[Dict[str, Any]] = rest_field(name="labelsToUpsert") + labels_to_upsert: Optional[Dict[str, Any]] = rest_field( + name="labelsToUpsert", visibility=["read", "create", "update", "delete", "query"] + ) """Dictionary containing the labels to update (or add if not existing) in key-value pairs. Values must be primitive values - number, string, boolean.""" - kind: Literal[ExceptionActionKind.RECLASSIFY] = rest_discriminator(name="kind") # type: ignore + kind: Literal[ExceptionActionKind.RECLASSIFY] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of ExceptionAction. Required. Discriminator value for ReclassifyExceptionAction.""" @@ -1417,24 +1443,24 @@ def __init__( id: Optional[str] = None, # pylint: disable=redefined-builtin classification_policy_id: Optional[str] = None, labels_to_upsert: Optional[Dict[str, Any]] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=ExceptionActionKind.RECLASSIFY, **kwargs) -class ReclassifyJobOptions(_model_base.Model): +class ReclassifyJobOptions(_Model): """Request payload for reclassifying jobs.""" -class ReclassifyJobResult(_model_base.Model): +class ReclassifyJobResult(_Model): """Response payload from reclassifying a job.""" @@ -1442,8 +1468,6 @@ class RoundRobinMode(DistributionMode, discriminator="roundRobin"): """Jobs are distributed in order to workers, starting with the worker that is after the last worker to receive a job. - All required parameters must be populated in order to send to server. - :ivar min_concurrent_offers: Governs the minimum desired number of active concurrent offers a job can have. :vartype min_concurrent_offers: int @@ -1460,7 +1484,7 @@ class RoundRobinMode(DistributionMode, discriminator="roundRobin"): :vartype kind: str or ~azure.communication.jobrouter.models.ROUND_ROBIN """ - kind: Literal[DistributionModeKind.ROUND_ROBIN] = rest_discriminator(name="kind") # type: ignore + kind: Literal[DistributionModeKind.ROUND_ROBIN] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of Mode. Required. Discriminator value for RoundRobinMode.""" @@ -1471,41 +1495,44 @@ def __init__( min_concurrent_offers: Optional[int] = None, max_concurrent_offers: Optional[int] = None, bypass_selectors: Optional[bool] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=DistributionModeKind.ROUND_ROBIN, **kwargs) -class RouterChannel(_model_base.Model): +class RouterChannel(_Model): """Represents the capacity a job in this channel will consume from a worker. - All required parameters must be populated in order to send to server. - :ivar channel_id: Id of a channel. Required. :vartype channel_id: str :ivar capacity_cost_per_job: The amount of capacity that an instance of a job of this channel will consume of the total worker capacity. Required. :vartype capacity_cost_per_job: int :ivar max_number_of_jobs: The maximum number of jobs that can be supported concurrently for - this channel. + this channel. Value must be greater than zero. :vartype max_number_of_jobs: int """ - channel_id: str = rest_field(name="channelId") + channel_id: str = rest_field(name="channelId", visibility=["read", "create", "update", "delete", "query"]) """Id of a channel. Required.""" - capacity_cost_per_job: int = rest_field(name="capacityCostPerJob") + capacity_cost_per_job: int = rest_field( + name="capacityCostPerJob", visibility=["read", "create", "update", "delete", "query"] + ) """The amount of capacity that an instance of a job of this channel will consume of the total worker capacity. Required.""" - max_number_of_jobs: Optional[int] = rest_field(name="maxNumberOfJobs") - """The maximum number of jobs that can be supported concurrently for this channel.""" + max_number_of_jobs: Optional[int] = rest_field( + name="maxNumberOfJobs", visibility=["read", "create", "update", "delete", "query"] + ) + """The maximum number of jobs that can be supported concurrently for this channel. Value must be + greater than zero.""" @overload def __init__( @@ -1514,26 +1541,22 @@ def __init__( channel_id: str, capacity_cost_per_job: int, max_number_of_jobs: Optional[int] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RouterJob(_model_base.Model): # pylint: disable=too-many-instance-attributes +class RouterJob(_Model): """A unit of work to be routed. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar etag: The entity tag for this resource. Required. :vartype etag: str :ivar id: Id of a job. Required. @@ -1552,7 +1575,7 @@ class RouterJob(_model_base.Model): # pylint: disable=too-many-instance-attribu :vartype classification_policy_id: str :ivar queue_id: Id of a queue that this job is queued to. :vartype queue_id: str - :ivar priority: Priority of this job. + :ivar priority: Priority of this job. Value must be between -100 to 100. :vartype priority: int :ivar disposition_code: Reason code for cancelled or closed jobs. :vartype disposition_code: str @@ -1585,7 +1608,9 @@ class RouterJob(_model_base.Model): # pylint: disable=too-many-instance-attribu """The entity tag for this resource. Required.""" id: str = rest_field(visibility=["read"]) """Id of a job. Required.""" - channel_reference: Optional[str] = rest_field(name="channelReference") + channel_reference: Optional[str] = rest_field( + name="channelReference", visibility=["read", "create", "update", "delete", "query"] + ) """Reference to an external parent context, eg. call ID.""" status: Optional[Union[str, "_models.RouterJobStatus"]] = rest_field(visibility=["read"]) """The status of the job. Known values are: \"pendingClassification\", \"queued\", \"assigned\", @@ -1593,18 +1618,22 @@ class RouterJob(_model_base.Model): # pylint: disable=too-many-instance-attribu \"pendingSchedule\", \"scheduled\", \"scheduleFailed\", and \"waitingForActivation\".""" enqueued_at: Optional[datetime.datetime] = rest_field(name="enqueuedAt", visibility=["read"], format="rfc3339") """Timestamp a job was queued in UTC.""" - channel_id: Optional[str] = rest_field(name="channelId") + channel_id: Optional[str] = rest_field(name="channelId", visibility=["read", "create", "update", "delete", "query"]) """The channel identifier. eg. voice, chat, etc.""" - classification_policy_id: Optional[str] = rest_field(name="classificationPolicyId") + classification_policy_id: Optional[str] = rest_field( + name="classificationPolicyId", visibility=["read", "create", "update", "delete", "query"] + ) """Id of a classification policy used for classifying this job.""" - queue_id: Optional[str] = rest_field(name="queueId") + queue_id: Optional[str] = rest_field(name="queueId", visibility=["read", "create", "update", "delete", "query"]) """Id of a queue that this job is queued to.""" - priority: Optional[int] = rest_field() - """Priority of this job.""" - disposition_code: Optional[str] = rest_field(name="dispositionCode") + priority: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) + """Priority of this job. Value must be between -100 to 100.""" + disposition_code: Optional[str] = rest_field( + name="dispositionCode", visibility=["read", "create", "update", "delete", "query"] + ) """Reason code for cancelled or closed jobs.""" requested_worker_selectors: Optional[List["_models.RouterWorkerSelector"]] = rest_field( - name="requestedWorkerSelectors" + name="requestedWorkerSelectors", visibility=["read", "create", "update", "delete", "query"] ) """A collection of manually specified worker selectors, which a worker must satisfy in order to process this job.""" @@ -1613,19 +1642,23 @@ class RouterJob(_model_base.Model): # pylint: disable=too-many-instance-attribu ) """A collection of worker selectors attached by a classification policy, which a worker must satisfy in order to process this job.""" - labels: Optional[Dict[str, Any]] = rest_field() + labels: Optional[Dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean.""" assignments: Optional[Dict[str, "_models.RouterJobAssignment"]] = rest_field(visibility=["read"]) """A collection of the assignments of the job. Key is AssignmentId.""" - tags: Optional[Dict[str, Any]] = rest_field() + tags: Optional[Dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A set of non-identifying attributes attached to this job. Values must be primitive values - number, string, boolean.""" - notes: Optional[List["_models.RouterJobNote"]] = rest_field() + notes: Optional[List["_models.RouterJobNote"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Notes attached to a job, sorted by timestamp.""" scheduled_at: Optional[datetime.datetime] = rest_field(name="scheduledAt", visibility=["read"], format="rfc3339") """If set, job will be scheduled to be enqueued at a given time.""" - matching_mode: Optional["_models.JobMatchingMode"] = rest_field(name="matchingMode") + matching_mode: Optional["_models.JobMatchingMode"] = rest_field( + name="matchingMode", visibility=["read", "create", "update", "delete", "query"] + ) """If provided, will determine how job matching will be carried out. Default mode: QueueAndMatchMode.""" @@ -1644,26 +1677,22 @@ def __init__( tags: Optional[Dict[str, Any]] = None, notes: Optional[List["_models.RouterJobNote"]] = None, matching_mode: Optional["_models.JobMatchingMode"] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RouterJobAssignment(_model_base.Model): +class RouterJobAssignment(_Model): """Assignment details of a job to a worker. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar assignment_id: Id of a job assignment. Required. :vartype assignment_id: str :ivar worker_id: Id of the Worker assigned to the job. @@ -1678,13 +1707,19 @@ class RouterJobAssignment(_model_base.Model): assignment_id: str = rest_field(name="assignmentId", visibility=["read"]) """Id of a job assignment. Required.""" - worker_id: Optional[str] = rest_field(name="workerId") + worker_id: Optional[str] = rest_field(name="workerId", visibility=["read", "create", "update", "delete", "query"]) """Id of the Worker assigned to the job.""" - assigned_at: datetime.datetime = rest_field(name="assignedAt", format="rfc3339") + assigned_at: datetime.datetime = rest_field( + name="assignedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """Timestamp when the job was assigned to a worker in UTC. Required.""" - completed_at: Optional[datetime.datetime] = rest_field(name="completedAt", format="rfc3339") + completed_at: Optional[datetime.datetime] = rest_field( + name="completedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """Timestamp when the job was marked as completed after being assigned in UTC.""" - closed_at: Optional[datetime.datetime] = rest_field(name="closedAt", format="rfc3339") + closed_at: Optional[datetime.datetime] = rest_field( + name="closedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """Timestamp when the job was marked as closed after being completed in UTC.""" @overload @@ -1695,24 +1730,22 @@ def __init__( worker_id: Optional[str] = None, completed_at: Optional[datetime.datetime] = None, closed_at: Optional[datetime.datetime] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RouterJobNote(_model_base.Model): +class RouterJobNote(_Model): """A note attached to a job. - All required parameters must be populated in order to send to server. - :ivar message: The message contained in the note. Required. :vartype message: str :ivar added_at: The time at which the note was added in UTC. If not provided, will default to @@ -1720,9 +1753,11 @@ class RouterJobNote(_model_base.Model): :vartype added_at: ~datetime.datetime """ - message: str = rest_field() + message: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The message contained in the note. Required.""" - added_at: Optional[datetime.datetime] = rest_field(name="addedAt", format="rfc3339") + added_at: Optional[datetime.datetime] = rest_field( + name="addedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """The time at which the note was added in UTC. If not provided, will default to the current time.""" @overload @@ -1731,26 +1766,22 @@ def __init__( *, message: str, added_at: Optional[datetime.datetime] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RouterJobOffer(_model_base.Model): +class RouterJobOffer(_Model): """An offer of a job to a worker. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar offer_id: Id of an offer. Required. :vartype offer_id: str :ivar job_id: Id of the job. Required. @@ -1765,13 +1796,17 @@ class RouterJobOffer(_model_base.Model): offer_id: str = rest_field(name="offerId", visibility=["read"]) """Id of an offer. Required.""" - job_id: str = rest_field(name="jobId") + job_id: str = rest_field(name="jobId", visibility=["read", "create", "update", "delete", "query"]) """Id of the job. Required.""" - capacity_cost: int = rest_field(name="capacityCost") + capacity_cost: int = rest_field(name="capacityCost", visibility=["read", "create", "update", "delete", "query"]) """The capacity cost consumed by the job offer. Required.""" - offered_at: Optional[datetime.datetime] = rest_field(name="offeredAt", format="rfc3339") + offered_at: Optional[datetime.datetime] = rest_field( + name="offeredAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """Timestamp when the offer was created in UTC.""" - expires_at: Optional[datetime.datetime] = rest_field(name="expiresAt", format="rfc3339") + expires_at: Optional[datetime.datetime] = rest_field( + name="expiresAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """Timestamp when the offer will expire in UTC.""" @overload @@ -1782,24 +1817,22 @@ def __init__( capacity_cost: int, offered_at: Optional[datetime.datetime] = None, expires_at: Optional[datetime.datetime] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RouterJobPositionDetails(_model_base.Model): +class RouterJobPositionDetails(_Model): """Position and estimated wait time for a job. - All required parameters must be populated in order to send to server. - :ivar job_id: Id of the job these details are about. Required. :vartype job_id: str :ivar position: Position of the job in question within that queue. Required. @@ -1813,15 +1846,17 @@ class RouterJobPositionDetails(_model_base.Model): :vartype estimated_wait_time_minutes: float """ - job_id: str = rest_field(name="jobId") + job_id: str = rest_field(name="jobId", visibility=["read", "create", "update", "delete", "query"]) """Id of the job these details are about. Required.""" - position: int = rest_field() + position: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Position of the job in question within that queue. Required.""" - queue_id: str = rest_field(name="queueId") + queue_id: str = rest_field(name="queueId", visibility=["read", "create", "update", "delete", "query"]) """Id of the queue this job is enqueued in. Required.""" - queue_length: int = rest_field(name="queueLength") + queue_length: int = rest_field(name="queueLength", visibility=["read", "create", "update", "delete", "query"]) """Length of the queue: total number of enqueued jobs. Required.""" - estimated_wait_time_minutes: float = rest_field(name="estimatedWaitTimeMinutes") + estimated_wait_time_minutes: float = rest_field( + name="estimatedWaitTimeMinutes", visibility=["read", "create", "update", "delete", "query"] + ) """Estimated wait time of the job rounded up to the nearest minute. Required.""" @overload @@ -1833,26 +1868,22 @@ def __init__( queue_id: str, queue_length: int, estimated_wait_time_minutes: float, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RouterQueue(_model_base.Model): +class RouterQueue(_Model): """A queue that can contain jobs to be routed. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar etag: The entity tag for this resource. Required. :vartype etag: str :ivar id: Id of a queue. Required. @@ -1874,14 +1905,18 @@ class RouterQueue(_model_base.Model): """The entity tag for this resource. Required.""" id: str = rest_field(visibility=["read"]) """Id of a queue. Required.""" - name: Optional[str] = rest_field() + name: Optional[str] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Friendly name of this queue.""" - distribution_policy_id: Optional[str] = rest_field(name="distributionPolicyId") + distribution_policy_id: Optional[str] = rest_field( + name="distributionPolicyId", visibility=["read", "create", "update", "delete", "query"] + ) """Id of a distribution policy that will determine how a job is distributed to workers.""" - labels: Optional[Dict[str, Any]] = rest_field() + labels: Optional[Dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean.""" - exception_policy_id: Optional[str] = rest_field(name="exceptionPolicyId") + exception_policy_id: Optional[str] = rest_field( + name="exceptionPolicyId", visibility=["read", "create", "update", "delete", "query"] + ) """Id of an exception policy that determines various job escalation rules.""" @overload @@ -1892,24 +1927,22 @@ def __init__( distribution_policy_id: Optional[str] = None, labels: Optional[Dict[str, Any]] = None, exception_policy_id: Optional[str] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RouterQueueSelector(_model_base.Model): +class RouterQueueSelector(_Model): """Describes a condition that must be met against a set of labels for queue selection. - All required parameters must be populated in order to send to server. - :ivar key: The label key to query against. Required. :vartype key: str :ivar label_operator: Describes how the value of the label is compared to the value defined on @@ -1921,13 +1954,15 @@ class RouterQueueSelector(_model_base.Model): :vartype value: any """ - key: str = rest_field() + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The label key to query against. Required.""" - label_operator: Union[str, "_models.LabelOperator"] = rest_field(name="labelOperator") + label_operator: Union[str, "_models.LabelOperator"] = rest_field( + name="labelOperator", visibility=["read", "create", "update", "delete", "query"] + ) """Describes how the value of the label is compared to the value defined on the label selector. Required. Known values are: \"equal\", \"notEqual\", \"lessThan\", \"lessThanOrEqual\", \"greaterThan\", and \"greaterThanOrEqual\".""" - value: Optional[Any] = rest_field() + value: Optional[Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean.""" @@ -1938,24 +1973,22 @@ def __init__( key: str, label_operator: Union[str, "_models.LabelOperator"], value: Optional[Any] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RouterQueueStatistics(_model_base.Model): +class RouterQueueStatistics(_Model): """Statistics for the queue. - All required parameters must be populated in order to send to server. - :ivar queue_id: Id of the queue these details are about. Required. :vartype queue_id: str :ivar length: Length of the queue: total number of enqueued jobs. Required. @@ -1968,14 +2001,18 @@ class RouterQueueStatistics(_model_base.Model): :vartype longest_job_wait_time_minutes: float """ - queue_id: str = rest_field(name="queueId") + queue_id: str = rest_field(name="queueId", visibility=["read", "create", "update", "delete", "query"]) """Id of the queue these details are about. Required.""" - length: int = rest_field() + length: int = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Length of the queue: total number of enqueued jobs. Required.""" - estimated_wait_time_minutes: Optional[Dict[str, float]] = rest_field(name="estimatedWaitTimeMinutes") + estimated_wait_time_minutes: Optional[Dict[str, float]] = rest_field( + name="estimatedWaitTimeMinutes", visibility=["read", "create", "update", "delete", "query"] + ) """The estimated wait time of this queue rounded up to the nearest minute, grouped by job priority.""" - longest_job_wait_time_minutes: Optional[float] = rest_field(name="longestJobWaitTimeMinutes") + longest_job_wait_time_minutes: Optional[float] = rest_field( + name="longestJobWaitTimeMinutes", visibility=["read", "create", "update", "delete", "query"] + ) """The wait time of the job that has been enqueued in this queue for the longest.""" @overload @@ -1986,26 +2023,22 @@ def __init__( length: int, estimated_wait_time_minutes: Optional[Dict[str, float]] = None, longest_job_wait_time_minutes: Optional[float] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RouterWorker(_model_base.Model): # pylint: disable=too-many-instance-attributes +class RouterWorker(_Model): """An entity for jobs to be routed to. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar etag: The entity tag for this resource. Required. :vartype etag: str :ivar id: Id of a worker. Required. @@ -2045,17 +2078,19 @@ class RouterWorker(_model_base.Model): # pylint: disable=too-many-instance-attr """Id of a worker. Required.""" state: Optional[Union[str, "_models.RouterWorkerState"]] = rest_field(visibility=["read"]) """Current state of a worker. Known values are: \"active\", \"draining\", and \"inactive\".""" - queues: Optional[List[str]] = rest_field() + queues: Optional[List[str]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Collection of queue(s) that this worker can receive work from.""" - capacity: Optional[int] = rest_field() + capacity: Optional[int] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The total capacity score this worker has to manage multiple concurrent jobs.""" - labels: Optional[Dict[str, Any]] = rest_field() + labels: Optional[Dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A set of key/value pairs that are identifying attributes used by the rules engines to make decisions. Values must be primitive values - number, string, boolean.""" - tags: Optional[Dict[str, Any]] = rest_field() + tags: Optional[Dict[str, Any]] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A set of non-identifying attributes attached to this worker. Values must be primitive values - number, string, boolean.""" - channels: Optional[List["_models.RouterChannel"]] = rest_field() + channels: Optional[List["_models.RouterChannel"]] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """Collection of channel(s) this worker can handle and their impact on the workers capacity.""" offers: Optional[List["_models.RouterJobOffer"]] = rest_field(visibility=["read"]) """A list of active offers issued to this worker.""" @@ -2066,9 +2101,13 @@ class RouterWorker(_model_base.Model): # pylint: disable=too-many-instance-attr load_ratio: Optional[float] = rest_field(name="loadRatio", visibility=["read"]) """A value indicating the workers capacity. A value of '1' means all capacity is consumed. A value of '0' means no capacity is currently consumed.""" - available_for_offers: Optional[bool] = rest_field(name="availableForOffers") + available_for_offers: Optional[bool] = rest_field( + name="availableForOffers", visibility=["read", "create", "update", "delete", "query"] + ) """A flag indicating this worker is open to receive offers or not.""" - max_concurrent_offers: Optional[int] = rest_field(name="maxConcurrentOffers") + max_concurrent_offers: Optional[int] = rest_field( + name="maxConcurrentOffers", visibility=["read", "create", "update", "delete", "query"] + ) """If this is set, the worker will only receive up to this many new offers at a time.""" @overload @@ -2082,24 +2121,22 @@ def __init__( channels: Optional[List["_models.RouterChannel"]] = None, available_for_offers: Optional[bool] = None, max_concurrent_offers: Optional[int] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RouterWorkerAssignment(_model_base.Model): +class RouterWorkerAssignment(_Model): """The assignment for a worker to a job. - All required parameters must be populated in order to send to server. - :ivar assignment_id: Id of the assignment. Required. :vartype assignment_id: str :ivar job_id: Id of the job assigned. Required. @@ -2111,13 +2148,15 @@ class RouterWorkerAssignment(_model_base.Model): :vartype assigned_at: ~datetime.datetime """ - assignment_id: str = rest_field(name="assignmentId") + assignment_id: str = rest_field(name="assignmentId", visibility=["read", "create", "update", "delete", "query"]) """Id of the assignment. Required.""" - job_id: str = rest_field(name="jobId") + job_id: str = rest_field(name="jobId", visibility=["read", "create", "update", "delete", "query"]) """Id of the job assigned. Required.""" - capacity_cost: int = rest_field(name="capacityCost") + capacity_cost: int = rest_field(name="capacityCost", visibility=["read", "create", "update", "delete", "query"]) """The amount of capacity this assignment has consumed on the worker. Required.""" - assigned_at: datetime.datetime = rest_field(name="assignedAt", format="rfc3339") + assigned_at: datetime.datetime = rest_field( + name="assignedAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """The assignment time of the job in UTC. Required.""" @overload @@ -2128,26 +2167,22 @@ def __init__( job_id: str, capacity_cost: int, assigned_at: datetime.datetime, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class RouterWorkerSelector(_model_base.Model): +class RouterWorkerSelector(_Model): """Describes a condition that must be met against a set of labels for worker selection. - Readonly variables are only populated by the server, and will be ignored when sending a request. - - All required parameters must be populated in order to send to server. - :ivar key: The label key to query against. Required. :vartype key: str :ivar label_operator: Describes how the value of the label is compared to the value defined on @@ -2167,18 +2202,22 @@ class RouterWorkerSelector(_model_base.Model): :vartype expires_at: ~datetime.datetime """ - key: str = rest_field() + key: str = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The label key to query against. Required.""" - label_operator: Union[str, "_models.LabelOperator"] = rest_field(name="labelOperator") + label_operator: Union[str, "_models.LabelOperator"] = rest_field( + name="labelOperator", visibility=["read", "create", "update", "delete", "query"] + ) """Describes how the value of the label is compared to the value defined on the worker selector. Required. Known values are: \"equal\", \"notEqual\", \"lessThan\", \"lessThanOrEqual\", \"greaterThan\", and \"greaterThanOrEqual\".""" - value: Optional[Any] = rest_field() + value: Optional[Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The value to compare against the actual label value with the given operator. Values must be primitive values - number, string, boolean.""" - expires_after_seconds: Optional[float] = rest_field(name="expiresAfterSeconds") + expires_after_seconds: Optional[float] = rest_field( + name="expiresAfterSeconds", visibility=["read", "create", "update", "delete", "query"] + ) """Describes how long this label selector is valid in seconds.""" - expedite: Optional[bool] = rest_field() + expedite: Optional[bool] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """Pushes a job to the front of the queue as long as this selector is active.""" status: Optional[Union[str, "_models.RouterWorkerSelectorStatus"]] = rest_field(visibility=["read"]) """Status of the worker selector. Known values are: \"active\" and \"expired\".""" @@ -2194,24 +2233,22 @@ def __init__( value: Optional[Any] = None, expires_after_seconds: Optional[float] = None, expedite: Optional[bool] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) class RuleEngineQueueSelectorAttachment(QueueSelectorAttachment, discriminator="ruleEngine"): """Attaches queue selectors to a job when the RouterRule is resolved. - All required parameters must be populated in order to send to server. - :ivar rule: A RouterRule that resolves a collection of queue selectors to attach. Required. :vartype rule: ~azure.communication.jobrouter.models.RouterRule :ivar kind: The type discriminator describing the type of queue selector attachment. Required. @@ -2219,9 +2256,9 @@ class RuleEngineQueueSelectorAttachment(QueueSelectorAttachment, discriminator=" :vartype kind: str or ~azure.communication.jobrouter.models.RULE_ENGINE """ - rule: "_models.RouterRule" = rest_field() + rule: "_models.RouterRule" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A RouterRule that resolves a collection of queue selectors to attach. Required.""" - kind: Literal[QueueSelectorAttachmentKind.RULE_ENGINE] = rest_discriminator(name="kind") # type: ignore + kind: Literal[QueueSelectorAttachmentKind.RULE_ENGINE] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing the type of queue selector attachment. Required. Discriminator value for RuleEngineQueueSelectorAttachment.""" @@ -2230,24 +2267,22 @@ def __init__( self, *, rule: "_models.RouterRule", - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=QueueSelectorAttachmentKind.RULE_ENGINE, **kwargs) class RuleEngineWorkerSelectorAttachment(WorkerSelectorAttachment, discriminator="ruleEngine"): """Attaches worker selectors to a job when a RouterRule is resolved. - All required parameters must be populated in order to send to server. - :ivar rule: A RouterRule that resolves a collection of worker selectors to attach. Required. :vartype rule: ~azure.communication.jobrouter.models.RouterRule :ivar kind: The type discriminator describing the type of worker selector attachment. Required. @@ -2255,9 +2290,9 @@ class RuleEngineWorkerSelectorAttachment(WorkerSelectorAttachment, discriminator :vartype kind: str or ~azure.communication.jobrouter.models.RULE_ENGINE """ - rule: "_models.RouterRule" = rest_field() + rule: "_models.RouterRule" = rest_field(visibility=["read", "create", "update", "delete", "query"]) """A RouterRule that resolves a collection of worker selectors to attach. Required.""" - kind: Literal[WorkerSelectorAttachmentKind.RULE_ENGINE] = rest_discriminator(name="kind") # type: ignore + kind: Literal[WorkerSelectorAttachmentKind.RULE_ENGINE] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing the type of worker selector attachment. Required. Discriminator value for RuleEngineWorkerSelectorAttachment.""" @@ -2266,16 +2301,16 @@ def __init__( self, *, rule: "_models.RouterRule", - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=WorkerSelectorAttachmentKind.RULE_ENGINE, **kwargs) @@ -2283,8 +2318,6 @@ class ScheduleAndSuspendMode(JobMatchingMode, discriminator="scheduleAndSuspend" """Describes a matching mode used for scheduling jobs to be queued at a future time. At the specified time, matching worker to a job will not start automatically. - All required parameters must be populated in order to send to server. - :ivar schedule_at: Requested schedule time. Required. :vartype schedule_at: ~datetime.datetime :ivar kind: The type discriminator describing ScheduleAndSuspendMode. Required. Discriminator @@ -2292,9 +2325,11 @@ class ScheduleAndSuspendMode(JobMatchingMode, discriminator="scheduleAndSuspend" :vartype kind: str or ~azure.communication.jobrouter.models.SCHEDULE_AND_SUSPEND """ - schedule_at: datetime.datetime = rest_field(name="scheduleAt", format="rfc3339") + schedule_at: datetime.datetime = rest_field( + name="scheduleAt", visibility=["read", "create", "update", "delete", "query"], format="rfc3339" + ) """Requested schedule time. Required.""" - kind: Literal[JobMatchingModeKind.SCHEDULE_AND_SUSPEND] = rest_discriminator(name="kind") # type: ignore + kind: Literal[JobMatchingModeKind.SCHEDULE_AND_SUSPEND] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing ScheduleAndSuspendMode. Required. Discriminator value for ScheduleAndSuspendMode.""" @@ -2303,28 +2338,28 @@ def __init__( self, *, schedule_at: datetime.datetime, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=JobMatchingModeKind.SCHEDULE_AND_SUSPEND, **kwargs) -class ScoringRuleOptions(_model_base.Model): +class ScoringRuleOptions(_Model): """Encapsulates all options that can be passed as parameters for scoring rule with BestWorkerMode. :ivar batch_size: Set batch size when 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured. :vartype batch_size: int :ivar scoring_parameters: List of extra parameters from a job that will be sent as part of the - payload to scoring rule. If not set, a job's labels (sent in the payload as ``job``\ ) and a - job's worker selectors (sent in the payload as ``selectors``\ ) are added to the payload of the + payload to scoring rule. If not set, a job's labels (sent in the payload as ``job``) and a + job's worker selectors (sent in the payload as ``selectors``) are added to the payload of the scoring rule by default. Note: Worker labels are always sent with scoring payload. :vartype scoring_parameters: list[str or ~azure.communication.jobrouter.models.ScoringRuleParameterSelector] @@ -2337,20 +2372,24 @@ class ScoringRuleOptions(_model_base.Model): :vartype descending_order: bool """ - batch_size: Optional[int] = rest_field(name="batchSize") + batch_size: Optional[int] = rest_field(name="batchSize", visibility=["read", "create", "update", "delete", "query"]) """Set batch size when 'isBatchScoringEnabled' is set to true. Defaults to 20 if not configured.""" scoring_parameters: Optional[List[Union[str, "_models.ScoringRuleParameterSelector"]]] = rest_field( - name="scoringParameters" + name="scoringParameters", visibility=["read", "create", "update", "delete", "query"] ) """List of extra parameters from a job that will be sent as part of the payload to scoring rule. - If not set, a job's labels (sent in the payload as ``job``\ ) and a job's worker selectors - (sent in the payload as ``selectors``\ ) are added to the payload of the scoring rule by - default. Note: Worker labels are always sent with scoring payload.""" - is_batch_scoring_enabled: Optional[bool] = rest_field(name="isBatchScoringEnabled") + If not set, a job's labels (sent in the payload as ``job``) and a job's worker selectors (sent + in the payload as ``selectors``) are added to the payload of the scoring rule by default. Note: + Worker labels are always sent with scoring payload.""" + is_batch_scoring_enabled: Optional[bool] = rest_field( + name="isBatchScoringEnabled", visibility=["read", "create", "update", "delete", "query"] + ) """If set to true, will score workers in batches, and the parameter name of the worker labels will be sent as ``workers``. By default, set to false and the parameter name for the worker labels will be sent as ``worker``. Note: If enabled, use 'batchSize' to set batch size.""" - descending_order: Optional[bool] = rest_field(name="descendingOrder") + descending_order: Optional[bool] = rest_field( + name="descendingOrder", visibility=["read", "create", "update", "delete", "query"] + ) """If false, will sort scores by ascending order. By default, set to true.""" @overload @@ -2361,24 +2400,22 @@ def __init__( scoring_parameters: Optional[List[Union[str, "_models.ScoringRuleParameterSelector"]]] = None, is_batch_scoring_enabled: Optional[bool] = None, descending_order: Optional[bool] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) class StaticQueueSelectorAttachment(QueueSelectorAttachment, discriminator="static"): """Describes a queue selector that will be attached to a job. - All required parameters must be populated in order to send to server. - :ivar queue_selector: The queue selector to attach. Required. :vartype queue_selector: ~azure.communication.jobrouter.models.RouterQueueSelector :ivar kind: The type discriminator describing the type of queue selector attachment. Required. @@ -2386,9 +2423,11 @@ class StaticQueueSelectorAttachment(QueueSelectorAttachment, discriminator="stat :vartype kind: str or ~azure.communication.jobrouter.models.STATIC """ - queue_selector: "_models.RouterQueueSelector" = rest_field(name="queueSelector") + queue_selector: "_models.RouterQueueSelector" = rest_field( + name="queueSelector", visibility=["read", "create", "update", "delete", "query"] + ) """The queue selector to attach. Required.""" - kind: Literal[QueueSelectorAttachmentKind.STATIC] = rest_discriminator(name="kind") # type: ignore + kind: Literal[QueueSelectorAttachmentKind.STATIC] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing the type of queue selector attachment. Required. Discriminator value for StaticQueueSelectorAttachment.""" @@ -2397,24 +2436,22 @@ def __init__( self, *, queue_selector: "_models.RouterQueueSelector", - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=QueueSelectorAttachmentKind.STATIC, **kwargs) class StaticRouterRule(RouterRule, discriminator="static"): """A rule providing static rules that always return the same result, regardless of input. - All required parameters must be populated in order to send to server. - :ivar value: The static value this rule always returns. Values must be primitive values - number, string, boolean. :vartype value: any @@ -2423,10 +2460,10 @@ class StaticRouterRule(RouterRule, discriminator="static"): :vartype kind: str or ~azure.communication.jobrouter.models.STATIC """ - value: Optional[Any] = rest_field() + value: Optional[Any] = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The static value this rule always returns. Values must be primitive values - number, string, boolean.""" - kind: Literal[RouterRuleKind.STATIC] = rest_discriminator(name="kind") # type: ignore + kind: Literal[RouterRuleKind.STATIC] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of Rule. Required. Discriminator value for StaticRouterRule.""" @@ -2435,24 +2472,22 @@ def __init__( self, *, value: Optional[Any] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=RouterRuleKind.STATIC, **kwargs) class StaticWorkerSelectorAttachment(WorkerSelectorAttachment, discriminator="static"): """Describes a worker selector that will be attached to a job. - All required parameters must be populated in order to send to server. - :ivar worker_selector: The worker selector to attach. Required. :vartype worker_selector: ~azure.communication.jobrouter.models.RouterWorkerSelector :ivar kind: The type discriminator describing the type of worker selector attachment. Required. @@ -2460,9 +2495,11 @@ class StaticWorkerSelectorAttachment(WorkerSelectorAttachment, discriminator="st :vartype kind: str or ~azure.communication.jobrouter.models.STATIC """ - worker_selector: "_models.RouterWorkerSelector" = rest_field(name="workerSelector") + worker_selector: "_models.RouterWorkerSelector" = rest_field( + name="workerSelector", visibility=["read", "create", "update", "delete", "query"] + ) """The worker selector to attach. Required.""" - kind: Literal[WorkerSelectorAttachmentKind.STATIC] = rest_discriminator(name="kind") # type: ignore + kind: Literal[WorkerSelectorAttachmentKind.STATIC] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing the type of worker selector attachment. Required. Discriminator value for StaticWorkerSelectorAttachment.""" @@ -2471,34 +2508,47 @@ def __init__( self, *, worker_selector: "_models.RouterWorkerSelector", - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=WorkerSelectorAttachmentKind.STATIC, **kwargs) class SuspendMode(JobMatchingMode, discriminator="suspend"): """Describes a matching mode where matching worker to a job is suspended. - All required parameters must be populated in order to send to server. - :ivar kind: The type discriminator describing SuspendMode. Required. Discriminator value for SuspendMode. :vartype kind: str or ~azure.communication.jobrouter.models.SUSPEND """ - kind: Literal[JobMatchingModeKind.SUSPEND] = rest_discriminator(name="kind") # type: ignore + kind: Literal[JobMatchingModeKind.SUSPEND] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing SuspendMode. Required. Discriminator value for SuspendMode.""" + @overload + def __init__( + self, + ) -> None: ... -class UnassignJobOptions(_model_base.Model): + @overload + def __init__(self, mapping: Mapping[str, Any]) -> None: + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None: + super().__init__(*args, kind=JobMatchingModeKind.SUSPEND, **kwargs) + + +class UnassignJobOptions(_Model): """Request payload for unassigning a job. :ivar suspend_matching: If SuspendMatching is true, then a job is not queued for re-matching @@ -2506,7 +2556,9 @@ class UnassignJobOptions(_model_base.Model): :vartype suspend_matching: bool """ - suspend_matching: Optional[bool] = rest_field(name="suspendMatching") + suspend_matching: Optional[bool] = rest_field( + name="suspendMatching", visibility=["read", "create", "update", "delete", "query"] + ) """If SuspendMatching is true, then a job is not queued for re-matching with a worker.""" @overload @@ -2514,33 +2566,33 @@ def __init__( self, *, suspend_matching: Optional[bool] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) -class UnassignJobResult(_model_base.Model): +class UnassignJobResult(_Model): """Response payload after a job has been successfully unassigned. - All required parameters must be populated in order to send to server. - :ivar job_id: Id of an unassigned job. Required. :vartype job_id: str :ivar unassignment_count: The number of times a job is unassigned. At a maximum 3. Required. :vartype unassignment_count: int """ - job_id: str = rest_field(name="jobId") + job_id: str = rest_field(name="jobId", visibility=["read", "create", "update", "delete", "query"]) """Id of an unassigned job. Required.""" - unassignment_count: int = rest_field(name="unassignmentCount") + unassignment_count: int = rest_field( + name="unassignmentCount", visibility=["read", "create", "update", "delete", "query"] + ) """The number of times a job is unassigned. At a maximum 3. Required.""" @overload @@ -2549,24 +2601,22 @@ def __init__( *, job_id: str, unassignment_count: int, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) class WaitTimeExceptionTrigger(ExceptionTrigger, discriminator="waitTime"): """Trigger for an exception action on exceeding wait time. - All required parameters must be populated in order to send to server. - :ivar threshold_seconds: Threshold for wait time for this trigger. Required. :vartype threshold_seconds: float :ivar kind: The type discriminator describing a sub-type of ExceptionTrigger. Required. @@ -2574,9 +2624,11 @@ class WaitTimeExceptionTrigger(ExceptionTrigger, discriminator="waitTime"): :vartype kind: str or ~azure.communication.jobrouter.models.WAIT_TIME """ - threshold_seconds: float = rest_field(name="thresholdSeconds") + threshold_seconds: float = rest_field( + name="thresholdSeconds", visibility=["read", "create", "update", "delete", "query"] + ) """Threshold for wait time for this trigger. Required.""" - kind: Literal[ExceptionTriggerKind.WAIT_TIME] = rest_discriminator(name="kind") # type: ignore + kind: Literal[ExceptionTriggerKind.WAIT_TIME] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of ExceptionTrigger. Required. Discriminator value for WaitTimeExceptionTrigger.""" @@ -2585,28 +2637,27 @@ def __init__( self, *, threshold_seconds: float, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=ExceptionTriggerKind.WAIT_TIME, **kwargs) class WebhookRouterRule(RouterRule, discriminator="webhook"): """A rule providing a binding to an external web server. - All required parameters must be populated in order to send to server. - :ivar authorization_server_uri: Uri for Authorization Server. :vartype authorization_server_uri: str :ivar client_credential: OAuth2.0 Credentials used to Contoso's Authorization server. - Reference: https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/. + Reference: `https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ + `_. :vartype client_credential: ~azure.communication.jobrouter.models.OAuth2WebhookClientCredential :ivar webhook_uri: Uri for Contoso's Web Server. :vartype webhook_uri: str @@ -2615,14 +2666,21 @@ class WebhookRouterRule(RouterRule, discriminator="webhook"): :vartype kind: str or ~azure.communication.jobrouter.models.WEBHOOK """ - authorization_server_uri: Optional[str] = rest_field(name="authorizationServerUri") + authorization_server_uri: Optional[str] = rest_field( + name="authorizationServerUri", visibility=["read", "create", "update", "delete", "query"] + ) """Uri for Authorization Server.""" - client_credential: Optional["_models.OAuth2WebhookClientCredential"] = rest_field(name="clientCredential") + client_credential: Optional["_models.OAuth2WebhookClientCredential"] = rest_field( + name="clientCredential", visibility=["read", "create", "update", "delete", "query"] + ) """OAuth2.0 Credentials used to Contoso's Authorization server. Reference: - https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/.""" - webhook_uri: Optional[str] = rest_field(name="webhookUri") + `https://www.oauth.com/oauth2-servers/access-tokens/client-credentials/ + `_.""" + webhook_uri: Optional[str] = rest_field( + name="webhookUri", visibility=["read", "create", "update", "delete", "query"] + ) """Uri for Contoso's Web Server.""" - kind: Literal[RouterRuleKind.WEBHOOK] = rest_discriminator(name="kind") # type: ignore + kind: Literal[RouterRuleKind.WEBHOOK] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing a sub-type of Rule. Required. Discriminator value for WebhookRouterRule.""" @@ -2633,16 +2691,16 @@ def __init__( authorization_server_uri: Optional[str] = None, client_credential: Optional["_models.OAuth2WebhookClientCredential"] = None, webhook_uri: Optional[str] = None, - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=RouterRuleKind.WEBHOOK, **kwargs) @@ -2652,8 +2710,6 @@ class WeightedAllocationQueueSelectorAttachment( """Describes multiple sets of queue selectors, of which one will be selected and attached according to a weighting. - All required parameters must be populated in order to send to server. - :ivar allocations: A collection of percentage based weighted allocations. Required. :vartype allocations: list[~azure.communication.jobrouter.models.QueueWeightedAllocation] :ivar kind: The type discriminator describing the type of queue selector attachment. Required. @@ -2661,9 +2717,11 @@ class WeightedAllocationQueueSelectorAttachment( :vartype kind: str or ~azure.communication.jobrouter.models.WEIGHTED_ALLOCATION """ - allocations: List["_models.QueueWeightedAllocation"] = rest_field() + allocations: List["_models.QueueWeightedAllocation"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """A collection of percentage based weighted allocations. Required.""" - kind: Literal[QueueSelectorAttachmentKind.WEIGHTED_ALLOCATION] = rest_discriminator(name="kind") # type: ignore + kind: Literal[QueueSelectorAttachmentKind.WEIGHTED_ALLOCATION] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing the type of queue selector attachment. Required. Discriminator value for WeightedAllocationQueueSelectorAttachment.""" @@ -2672,16 +2730,16 @@ def __init__( self, *, allocations: List["_models.QueueWeightedAllocation"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=QueueSelectorAttachmentKind.WEIGHTED_ALLOCATION, **kwargs) @@ -2691,8 +2749,6 @@ class WeightedAllocationWorkerSelectorAttachment( """Describes multiple sets of worker selectors, of which one will be selected and attached according to a weighting. - All required parameters must be populated in order to send to server. - :ivar allocations: A collection of percentage based weighted allocations. Required. :vartype allocations: list[~azure.communication.jobrouter.models.WorkerWeightedAllocation] :ivar kind: The type discriminator describing the type of worker selector attachment. Required. @@ -2700,9 +2756,11 @@ class WeightedAllocationWorkerSelectorAttachment( :vartype kind: str or ~azure.communication.jobrouter.models.WEIGHTED_ALLOCATION """ - allocations: List["_models.WorkerWeightedAllocation"] = rest_field() + allocations: List["_models.WorkerWeightedAllocation"] = rest_field( + visibility=["read", "create", "update", "delete", "query"] + ) """A collection of percentage based weighted allocations. Required.""" - kind: Literal[WorkerSelectorAttachmentKind.WEIGHTED_ALLOCATION] = rest_discriminator(name="kind") # type: ignore + kind: Literal[WorkerSelectorAttachmentKind.WEIGHTED_ALLOCATION] = rest_discriminator(name="kind", visibility=["read", "create", "update", "delete", "query"]) # type: ignore """The type discriminator describing the type of worker selector attachment. Required. Discriminator value for WeightedAllocationWorkerSelectorAttachment.""" @@ -2711,25 +2769,23 @@ def __init__( self, *, allocations: List["_models.WorkerWeightedAllocation"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, kind=WorkerSelectorAttachmentKind.WEIGHTED_ALLOCATION, **kwargs) -class WorkerWeightedAllocation(_model_base.Model): +class WorkerWeightedAllocation(_Model): """Contains the weight percentage and worker selectors to be applied if selected for weighted distributions. - All required parameters must be populated in order to send to server. - :ivar weight: The percentage of this weight, expressed as a fraction of 1. Required. :vartype weight: float :ivar worker_selectors: A collection of worker selectors that will be applied if this @@ -2737,9 +2793,11 @@ class WorkerWeightedAllocation(_model_base.Model): :vartype worker_selectors: list[~azure.communication.jobrouter.models.RouterWorkerSelector] """ - weight: float = rest_field() + weight: float = rest_field(visibility=["read", "create", "update", "delete", "query"]) """The percentage of this weight, expressed as a fraction of 1. Required.""" - worker_selectors: List["_models.RouterWorkerSelector"] = rest_field(name="workerSelectors") + worker_selectors: List["_models.RouterWorkerSelector"] = rest_field( + name="workerSelectors", visibility=["read", "create", "update", "delete", "query"] + ) """A collection of worker selectors that will be applied if this allocation is selected. Required.""" @overload @@ -2748,14 +2806,14 @@ def __init__( *, weight: float, worker_selectors: List["_models.RouterWorkerSelector"], - ): ... + ) -> None: ... @overload - def __init__(self, mapping: Mapping[str, Any]): + def __init__(self, mapping: Mapping[str, Any]) -> None: """ :param mapping: raw JSON to initialize the model. :type mapping: Mapping[str, Any] """ - def __init__(self, *args: Any, **kwargs: Any) -> None: # pylint: disable=useless-super-delegation + def __init__(self, *args: Any, **kwargs: Any) -> None: super().__init__(*args, **kwargs) diff --git a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_patch.py b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_patch.py index f7dd32510333..8bcb627aa475 100644 --- a/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_patch.py +++ b/sdk/communication/azure-communication-jobrouter/azure/communication/jobrouter/models/_patch.py @@ -1,7 +1,8 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_create_classification_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_create_classification_policy.py new file mode 100644 index 000000000000..f00b0141b928 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_create_classification_policy.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python classification_policies_create_classification_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_classification_policy( + classification_policy_id="90eb00c4-234e-4df7-a231-ef7895518384", + resource={ + "fallbackQueueId": "MainQueue", + "name": "Main", + "prioritizationRule": {"kind": "static", "value": "2"}, + "queueSelectorAttachments": [ + { + "condition": {"expression": "1 = 1", "kind": "expression", "language": "powerFx"}, + "kind": "conditional", + "queueSelectors": [{"key": "foo", "labelOperator": "equal", "value": "bar"}], + } + ], + }, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/ClassificationPolicies_CreateClassificationPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_delete_classification_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_delete_classification_policy.py new file mode 100644 index 000000000000..da85aa439118 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_delete_classification_policy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python classification_policies_delete_classification_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + client.delete_classification_policy( + classification_policy_id="MainClassificationPolicy", + ) + + +# x-ms-original-file: 2024-01-18-preview/ClassificationPolicies_DeleteClassificationPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_get_classification_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_get_classification_policy.py new file mode 100644 index 000000000000..752a134fa646 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_get_classification_policy.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python classification_policies_get_classification_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_classification_policy( + classification_policy_id="MainClassificationPolicy", + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/ClassificationPolicies_GetClassificationPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_list_classification_policies_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_list_classification_policies_with_page_size.py new file mode 100644 index 000000000000..e46632313420 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_list_classification_policies_with_page_size.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python classification_policies_list_classification_policies_with_page_size.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_classification_policies() + for item in response: + print(item) + + +# x-ms-original-file: 2024-01-18-preview/ClassificationPolicies_ListClassificationPoliciesWithPageSize.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_update_classification_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_update_classification_policy.py new file mode 100644 index 000000000000..fdd22b1977e8 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/classification_policies_update_classification_policy.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python classification_policies_update_classification_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_classification_policy( + classification_policy_id="90eb00c4-234e-4df7-a231-ef7895518384", + resource={"name": "MainUpdate"}, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/ClassificationPolicies_UpdateClassificationPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_create_distribution_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_create_distribution_policy.py new file mode 100644 index 000000000000..6941ef04aa6d --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_create_distribution_policy.py @@ -0,0 +1,52 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python distribution_policies_create_distribution_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_distribution_policy( + distribution_policy_id="d9033d56-659c-437a-b5b7-4f3b14301dd4", + resource={ + "mode": { + "bypassSelectors": False, + "kind": "longestIdle", + "maxConcurrentOffers": 5, + "minConcurrentOffers": 1, + }, + "name": "Main", + "offerExpiresAfterSeconds": 300, + }, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/DistributionPolicies_CreateDistributionPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_delete_distribution_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_delete_distribution_policy.py new file mode 100644 index 000000000000..be1a4c29cc45 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_delete_distribution_policy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python distribution_policies_delete_distribution_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + client.delete_distribution_policy( + distribution_policy_id="MainDistributionPolicy", + ) + + +# x-ms-original-file: 2024-01-18-preview/DistributionPolicies_DeleteDistributionPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_get_distribution_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_get_distribution_policy.py new file mode 100644 index 000000000000..5825a90ce2f4 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_get_distribution_policy.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python distribution_policies_get_distribution_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_distribution_policy( + distribution_policy_id="MainDistributionPolicy", + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/DistributionPolicies_GetDistributionPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_list_distribution_policies_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_list_distribution_policies_with_page_size.py new file mode 100644 index 000000000000..0f8d445fd3c8 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_list_distribution_policies_with_page_size.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python distribution_policies_list_distribution_policies_with_page_size.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_distribution_policies() + for item in response: + print(item) + + +# x-ms-original-file: 2024-01-18-preview/DistributionPolicies_ListDistributionPoliciesWithPageSize.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_update_distribution_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_update_distribution_policy.py new file mode 100644 index 000000000000..c28e03a281ac --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/distribution_policies_update_distribution_policy.py @@ -0,0 +1,52 @@ +# pylint: disable=line-too-long,useless-suppression +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python distribution_policies_update_distribution_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_distribution_policy( + distribution_policy_id="d9033d56-659c-437a-b5b7-4f3b14301dd4", + resource={ + "mode": { + "bypassSelectors": False, + "kind": "longestIdle", + "maxConcurrentOffers": 5, + "minConcurrentOffers": 1, + }, + "name": "Main", + "offerExpiresAfterSeconds": 300, + }, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/DistributionPolicies_UpdateDistributionPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_create_exception_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_create_exception_policy.py new file mode 100644 index 000000000000..52a7d6f4e9e0 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_create_exception_policy.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python exception_policies_create_exception_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_exception_policy( + exception_policy_id="cf1cda69-6f41-45ac-b252-213293f1b1cb", + resource={ + "exceptionRules": [ + { + "actions": [ + {"classificationPolicyId": "Main", "kind": "reclassify", "labelsToUpsert": {"escalated": True}} + ], + "id": "MaxWaitTimeExceeded", + "trigger": {"kind": "waitTime", "thresholdSeconds": 20}, + } + ], + "name": "Main", + }, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/ExceptionPolicies_CreateExceptionPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_delete_exception_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_delete_exception_policy.py new file mode 100644 index 000000000000..3b279adb3a3f --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_delete_exception_policy.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python exception_policies_delete_exception_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + client.delete_exception_policy( + exception_policy_id="MainExceptionPolicy", + ) + + +# x-ms-original-file: 2024-01-18-preview/ExceptionPolicies_DeleteExceptionPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_get_exception_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_get_exception_policy.py new file mode 100644 index 000000000000..102658fc1669 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_get_exception_policy.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python exception_policies_get_exception_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_exception_policy( + exception_policy_id="MainExceptionPolicy", + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/ExceptionPolicies_GetExceptionPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_list_exception_policies_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_list_exception_policies_with_page_size.py new file mode 100644 index 000000000000..d023c95f58c3 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_list_exception_policies_with_page_size.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python exception_policies_list_exception_policies_with_page_size.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_exception_policies() + for item in response: + print(item) + + +# x-ms-original-file: 2024-01-18-preview/ExceptionPolicies_ListExceptionPoliciesWithPageSize.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_update_exception_policy.py b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_update_exception_policy.py new file mode 100644 index 000000000000..e1e3832037cc --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/exception_policies_update_exception_policy.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python exception_policies_update_exception_policy.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_exception_policy( + exception_policy_id="cf1cda69-6f41-45ac-b252-213293f1b1cb", + resource={ + "exceptionRules": [ + { + "actions": [ + {"classificationPolicyId": "Main", "kind": "reclassify", "labelsToUpsert": {"escalated": True}} + ], + "id": "MaxWaitTimeExceeded", + "trigger": {"kind": "waitTime", "thresholdSeconds": 20}, + } + ], + "name": "Main test", + }, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/ExceptionPolicies_UpdateExceptionPolicy.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_job.py new file mode 100644 index 000000000000..6add0342bdc6 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_job.py @@ -0,0 +1,50 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python jobs_create_job.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_job( + job_id="JobId", + resource={ + "channelId": "CustomChatChannel", + "channelReference": "1d5896f3-8b54-40be-82d3-910323f5e2af", + "labels": {}, + "matchingMode": {"kind": "queueAndMatch"}, + "priority": 5, + "queueId": "MainQueue", + "requestedWorkerSelectors": [{"key": "Sales", "labelOperator": "equal", "value": True}], + }, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Jobs_CreateJob.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_scheduled_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_scheduled_job.py new file mode 100644 index 000000000000..b45711ffa95c --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_create_scheduled_job.py @@ -0,0 +1,50 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python jobs_create_scheduled_job.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_job( + job_id="JobId", + resource={ + "channelId": "CustomChatChannel", + "channelReference": "1d5896f3-8b54-40be-82d3-910323f5e2af", + "labels": {}, + "matchingMode": {"kind": "scheduleAndSuspend", "scheduleAt": "2023-05-26T23:22:12.0774222+00:00"}, + "priority": 5, + "queueId": "MainQueue", + "requestedWorkerSelectors": [{"key": "Sales", "labelOperator": "equal", "value": True}], + }, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Jobs_CreateScheduledJob.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_delete_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_delete_job.py new file mode 100644 index 000000000000..5b741808fccb --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_delete_job.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python jobs_delete_job.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + client.delete_job( + job_id="8780b28c-7079-4de1-9143-4d369289e958", + ) + + +# x-ms-original-file: 2024-01-18-preview/Jobs_DeleteJob.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_in_queue_position.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_in_queue_position.py new file mode 100644 index 000000000000..a28389de7f19 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_in_queue_position.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python jobs_get_in_queue_position.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_queue_position( + job_id="8780b28c-7079-4de1-9143-4d369289e958", + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Jobs_GetInQueuePosition.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_job.py new file mode 100644 index 000000000000..b2eb19a8d876 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_job.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python jobs_get_job.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_job( + job_id="8780b28c-7079-4de1-9143-4d369289e958", + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Jobs_GetJob.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_jobs_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_jobs_with_page_size.py new file mode 100644 index 000000000000..144a37830740 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_get_jobs_with_page_size.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python jobs_get_jobs_with_page_size.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_jobs() + for item in response: + print(item) + + +# x-ms-original-file: 2024-01-18-preview/Jobs_GetJobsWithPageSize.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_unassign_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_unassign_job.py new file mode 100644 index 000000000000..80e12df1931d --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_unassign_job.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python jobs_unassign_job.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.unassign_job( + job_id="8780b28c-7079-4de1-9143-4d369289e958", + assignment_id="1d5896f3-8b54-40be-82d3-910323f5e2af", + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Jobs_UnassignJob.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_update_job.py b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_update_job.py new file mode 100644 index 000000000000..cc980d1bc2df --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/jobs_update_job.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python jobs_update_job.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_job( + job_id="8780b28c-7079-4de1-9143-4d369289e958", + resource={"channelReference": "1d5896f3-8b54-40be-82d3-910323f5e2af"}, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Jobs_UpdateJob.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/offers_accept_job_offer.py b/sdk/communication/azure-communication-jobrouter/generated_samples/offers_accept_job_offer.py new file mode 100644 index 000000000000..a98e063e6f07 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/offers_accept_job_offer.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python offers_accept_job_offer.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.accept_job_offer( + worker_id="DefaultWorker", + offer_id="1d5896f3-8b54-40be-82d3-910323f5e2af", + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Offers_AcceptJobOffer.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_create_queue.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_create_queue.py new file mode 100644 index 000000000000..15aa786bb444 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_create_queue.py @@ -0,0 +1,47 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python queues_create_queue.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_queue( + queue_id="QueueId", + resource={ + "distributionPolicyId": "MainDistributionPolicy", + "exceptionPolicyId": "MainExceptionPolicy", + "labels": {}, + "name": "Main", + }, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Queues_CreateQueue.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_delete_queue.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_delete_queue.py new file mode 100644 index 000000000000..dc7fceef2cee --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_delete_queue.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python queues_delete_queue.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + client.delete_queue( + queue_id="MainQueue", + ) + + +# x-ms-original-file: 2024-01-18-preview/Queues_DeleteQueue.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue.py new file mode 100644 index 000000000000..0f6240532de8 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python queues_get_queue.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_queue( + queue_id="MainQueue", + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Queues_GetQueue.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue_statistics.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue_statistics.py new file mode 100644 index 000000000000..3bb76e465507 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_get_queue_statistics.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python queues_get_queue_statistics.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_queue_statistics( + queue_id="MainQueue", + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Queues_GetQueueStatistics.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_list_queues_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_list_queues_with_page_size.py new file mode 100644 index 000000000000..65a9324da228 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_list_queues_with_page_size.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python queues_list_queues_with_page_size.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_queues() + for item in response: + print(item) + + +# x-ms-original-file: 2024-01-18-preview/Queues_ListQueuesWithPageSize.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/queues_update_queue.py b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_update_queue.py new file mode 100644 index 000000000000..e42329d8e308 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/queues_update_queue.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterAdministrationClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python queues_update_queue.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_queue( + queue_id="MainQueue", + resource={"distributionPolicyId": "MainDistributionPolicy", "name": "Main"}, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Queues_UpdateQueue.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker.py new file mode 100644 index 000000000000..1813482afc26 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker.py @@ -0,0 +1,52 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python workers_create_worker.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_worker( + worker_id="WorkerId", + resource={ + "availableForOffers": False, + "capacity": 10, + "channels": [ + {"capacityCostPerJob": 11, "channelId": "CustomChatChannel", "maxNumberOfJobs": 4}, + {"capacityCostPerJob": 10, "channelId": "CustomVoiceChannel", "maxNumberOfJobs": 1}, + ], + "labels": {}, + "queues": ["MainQueue"], + "tags": {}, + }, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Workers_CreateWorker.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker_with_max_concurrent_offers.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker_with_max_concurrent_offers.py new file mode 100644 index 000000000000..c7ef71335180 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_create_worker_with_max_concurrent_offers.py @@ -0,0 +1,53 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python workers_create_worker_with_max_concurrent_offers.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_worker( + worker_id="WorkerId", + resource={ + "availableForOffers": False, + "capacity": 10, + "channels": [ + {"capacityCostPerJob": 11, "channelId": "CustomChatChannel", "maxNumberOfJobs": 4}, + {"capacityCostPerJob": 10, "channelId": "CustomVoiceChannel", "maxNumberOfJobs": 1}, + ], + "labels": {}, + "maxConcurrentOffers": 1, + "queues": ["MainQueue"], + "tags": {}, + }, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Workers_CreateWorkerWithMaxConcurrentOffers.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_delete_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_delete_worker.py new file mode 100644 index 000000000000..dc435dc5cf00 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_delete_worker.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python workers_delete_worker.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + client.delete_worker( + worker_id="DefaultWorker", + ) + + +# x-ms-original-file: 2024-01-18-preview/Workers_DeleteWorker.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_active_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_active_worker.py new file mode 100644 index 000000000000..06ffb8981363 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_active_worker.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python workers_deregister_active_worker.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_worker( + worker_id="WorkerId", + resource={"availableForOffers": False, "capacity": 10}, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Workers_DeregisterActiveWorker.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_inactive_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_inactive_worker.py new file mode 100644 index 000000000000..edee03e21dbe --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_deregister_inactive_worker.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python workers_deregister_inactive_worker.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_worker( + worker_id="WorkerId", + resource={"availableForOffers": False, "capacity": 10}, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Workers_DeregisterInactiveWorker.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_available_workers_by_channel.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_available_workers_by_channel.py new file mode 100644 index 000000000000..80bb2a32046c --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_available_workers_by_channel.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python workers_get_available_workers_by_channel.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_workers() + for item in response: + print(item) + + +# x-ms-original-file: 2024-01-18-preview/Workers_GetAvailableWorkersByChannel.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_worker.py new file mode 100644 index 000000000000..49d13dea53e7 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_worker.py @@ -0,0 +1,41 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python workers_get_worker.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.get_worker( + worker_id="DefaultWorker", + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Workers_GetWorker.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_workers_with_page_size.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_workers_with_page_size.py new file mode 100644 index 000000000000..d07f5b02a460 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_get_workers_with_page_size.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python workers_get_workers_with_page_size.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.list_workers() + for item in response: + print(item) + + +# x-ms-original-file: 2024-01-18-preview/Workers_GetWorkersWithPageSize.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_register_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_register_worker.py new file mode 100644 index 000000000000..ef0c70f5c283 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_register_worker.py @@ -0,0 +1,42 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python workers_register_worker.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_worker( + worker_id="WorkerId", + resource={"availableForOffers": True, "capacity": 10}, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Workers_RegisterWorker.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_samples/workers_update_worker.py b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_update_worker.py new file mode 100644 index 000000000000..600aef2ea2e0 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_samples/workers_update_worker.py @@ -0,0 +1,52 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from azure.identity import DefaultAzureCredential + +from azure.communication.jobrouter import JobRouterClient + +""" +# PREREQUISITES + pip install azure-identity + pip install azure-communication-jobrouter +# USAGE + python workers_update_worker.py + + Before run the sample, please set the values of the client ID, tenant ID and client secret + of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID, + AZURE_CLIENT_SECRET. For more info about how to get the value, please see: + https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal +""" + + +def main(): + client = JobRouterAdministrationClient( + endpoint="https://contoso.westus.communications.azure.com", + credential=DefaultAzureCredential(), + ) + + response = client.upsert_worker( + worker_id="WorkerId", + resource={ + "availableForOffers": False, + "capacity": 10, + "channels": [ + {"capacityCostPerJob": 11, "channelId": "CustomChatChannel", "maxNumberOfJobs": 4}, + {"capacityCostPerJob": 10, "channelId": "CustomVoiceChannel", "maxNumberOfJobs": 1}, + ], + "labels": {}, + "queues": ["MainQueue", "SecondaryQueue"], + "tags": {}, + }, + ) + print(response) + + +# x-ms-original-file: 2024-01-18-preview/Workers_UpdateWorker.json +if __name__ == "__main__": + main() diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/conftest.py b/sdk/communication/azure-communication-jobrouter/generated_tests/conftest.py new file mode 100644 index 000000000000..b3c392dc74f6 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_tests/conftest.py @@ -0,0 +1,56 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + jobrouteradministration_subscription_id = os.environ.get( + "JOBROUTERADMINISTRATION_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + jobrouteradministration_tenant_id = os.environ.get( + "JOBROUTERADMINISTRATION_TENANT_ID", "00000000-0000-0000-0000-000000000000" + ) + jobrouteradministration_client_id = os.environ.get( + "JOBROUTERADMINISTRATION_CLIENT_ID", "00000000-0000-0000-0000-000000000000" + ) + jobrouteradministration_client_secret = os.environ.get( + "JOBROUTERADMINISTRATION_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer( + regex=jobrouteradministration_subscription_id, value="00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=jobrouteradministration_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=jobrouteradministration_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer( + regex=jobrouteradministration_client_secret, value="00000000-0000-0000-0000-000000000000" + ) + + jobrouter_subscription_id = os.environ.get("JOBROUTER_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000") + jobrouter_tenant_id = os.environ.get("JOBROUTER_TENANT_ID", "00000000-0000-0000-0000-000000000000") + jobrouter_client_id = os.environ.get("JOBROUTER_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + jobrouter_client_secret = os.environ.get("JOBROUTER_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=jobrouter_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=jobrouter_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=jobrouter_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=jobrouter_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router.py b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router.py new file mode 100644 index 000000000000..aaa2a1f47af8 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router.py @@ -0,0 +1,216 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import JobRouterClientTestBase, JobRouterPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestJobRouter(JobRouterClientTestBase): + @JobRouterPreparer() + @recorded_by_proxy + def test_upsert_job(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.upsert_job( + job_id="str", + resource={ + "etag": "str", + "id": "str", + "assignments": { + "str": { + "assignedAt": "2020-02-20 00:00:00", + "assignmentId": "str", + "closedAt": "2020-02-20 00:00:00", + "completedAt": "2020-02-20 00:00:00", + "workerId": "str", + } + }, + "attachedWorkerSelectors": [ + { + "key": "str", + "labelOperator": "str", + "expedite": bool, + "expiresAfterSeconds": 0.0, + "expiresAt": "2020-02-20 00:00:00", + "status": "str", + "value": {}, + } + ], + "channelId": "str", + "channelReference": "str", + "classificationPolicyId": "str", + "dispositionCode": "str", + "enqueuedAt": "2020-02-20 00:00:00", + "labels": {"str": {}}, + "matchingMode": "job_matching_mode", + "notes": [{"message": "str", "addedAt": "2020-02-20 00:00:00"}], + "priority": 0, + "queueId": "str", + "requestedWorkerSelectors": [ + { + "key": "str", + "labelOperator": "str", + "expedite": bool, + "expiresAfterSeconds": 0.0, + "expiresAt": "2020-02-20 00:00:00", + "status": "str", + "value": {}, + } + ], + "scheduledAt": "2020-02-20 00:00:00", + "status": "str", + "tags": {"str": {}}, + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy + def test_get_job(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.get_job( + job_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy + def test_delete_job(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.delete_job( + job_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy + def test_list_jobs(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.list_jobs() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy + def test_get_queue_position(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.get_queue_position( + job_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy + def test_unassign_job(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.unassign_job( + job_id="str", + assignment_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy + def test_accept_job_offer(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.accept_job_offer( + worker_id="str", + offer_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy + def test_get_queue_statistics(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.get_queue_statistics( + queue_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy + def test_upsert_worker(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.upsert_worker( + worker_id="str", + resource={ + "etag": "str", + "id": "str", + "assignedJobs": [ + {"assignedAt": "2020-02-20 00:00:00", "assignmentId": "str", "capacityCost": 0, "jobId": "str"} + ], + "availableForOffers": bool, + "capacity": 0, + "channels": [{"capacityCostPerJob": 0, "channelId": "str", "maxNumberOfJobs": 0}], + "labels": {"str": {}}, + "loadRatio": 0.0, + "maxConcurrentOffers": 0, + "offers": [ + { + "capacityCost": 0, + "jobId": "str", + "offerId": "str", + "expiresAt": "2020-02-20 00:00:00", + "offeredAt": "2020-02-20 00:00:00", + } + ], + "queues": ["str"], + "state": "str", + "tags": {"str": {}}, + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy + def test_get_worker(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.get_worker( + worker_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy + def test_delete_worker(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.delete_worker( + worker_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy + def test_list_workers(self, jobrouter_endpoint): + client = self.create_client(endpoint=jobrouter_endpoint) + response = client.list_workers() + result = [r for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration.py b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration.py new file mode 100644 index 000000000000..e90e18a13de3 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration.py @@ -0,0 +1,211 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils import recorded_by_proxy +from testpreparer import JobRouterAdministrationClientTestBase, JobRouterAdministrationPreparer + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestJobRouterAdministration(JobRouterAdministrationClientTestBase): + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_upsert_distribution_policy(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.upsert_distribution_policy( + distribution_policy_id="str", + resource={ + "etag": "str", + "id": "str", + "mode": "distribution_mode", + "name": "str", + "offerExpiresAfterSeconds": 0.0, + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_get_distribution_policy(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.get_distribution_policy( + distribution_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_list_distribution_policies(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.list_distribution_policies() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_delete_distribution_policy(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.delete_distribution_policy( + distribution_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_upsert_classification_policy(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.upsert_classification_policy( + classification_policy_id="str", + resource={ + "etag": "str", + "id": "str", + "fallbackQueueId": "str", + "name": "str", + "prioritizationRule": "router_rule", + "queueSelectorAttachments": ["queue_selector_attachment"], + "workerSelectorAttachments": ["worker_selector_attachment"], + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_get_classification_policy(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.get_classification_policy( + classification_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_list_classification_policies(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.list_classification_policies() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_delete_classification_policy(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.delete_classification_policy( + classification_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_upsert_exception_policy(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.upsert_exception_policy( + exception_policy_id="str", + resource={ + "etag": "str", + "id": "str", + "exceptionRules": [{"actions": ["exception_action"], "id": "str", "trigger": "exception_trigger"}], + "name": "str", + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_get_exception_policy(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.get_exception_policy( + exception_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_list_exception_policies(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.list_exception_policies() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_delete_exception_policy(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.delete_exception_policy( + exception_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_upsert_queue(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.upsert_queue( + queue_id="str", + resource={ + "etag": "str", + "id": "str", + "distributionPolicyId": "str", + "exceptionPolicyId": "str", + "labels": {"str": {}}, + "name": "str", + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_get_queue(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.get_queue( + queue_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_list_queues(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.list_queues() + result = [r for r in response] + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy + def test_delete_queue(self, jobrouteradministration_endpoint): + client = self.create_client(endpoint=jobrouteradministration_endpoint) + response = client.delete_queue( + queue_id="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration_async.py b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration_async.py new file mode 100644 index 000000000000..83edbf45af8a --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_administration_async.py @@ -0,0 +1,212 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import JobRouterAdministrationPreparer +from testpreparer_async import JobRouterAdministrationClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestJobRouterAdministrationAsync(JobRouterAdministrationClientTestBaseAsync): + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_upsert_distribution_policy(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.upsert_distribution_policy( + distribution_policy_id="str", + resource={ + "etag": "str", + "id": "str", + "mode": "distribution_mode", + "name": "str", + "offerExpiresAfterSeconds": 0.0, + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_get_distribution_policy(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.get_distribution_policy( + distribution_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_list_distribution_policies(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = client.list_distribution_policies() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_delete_distribution_policy(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.delete_distribution_policy( + distribution_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_upsert_classification_policy(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.upsert_classification_policy( + classification_policy_id="str", + resource={ + "etag": "str", + "id": "str", + "fallbackQueueId": "str", + "name": "str", + "prioritizationRule": "router_rule", + "queueSelectorAttachments": ["queue_selector_attachment"], + "workerSelectorAttachments": ["worker_selector_attachment"], + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_get_classification_policy(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.get_classification_policy( + classification_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_list_classification_policies(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = client.list_classification_policies() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_delete_classification_policy(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.delete_classification_policy( + classification_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_upsert_exception_policy(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.upsert_exception_policy( + exception_policy_id="str", + resource={ + "etag": "str", + "id": "str", + "exceptionRules": [{"actions": ["exception_action"], "id": "str", "trigger": "exception_trigger"}], + "name": "str", + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_get_exception_policy(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.get_exception_policy( + exception_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_list_exception_policies(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = client.list_exception_policies() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_delete_exception_policy(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.delete_exception_policy( + exception_policy_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_upsert_queue(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.upsert_queue( + queue_id="str", + resource={ + "etag": "str", + "id": "str", + "distributionPolicyId": "str", + "exceptionPolicyId": "str", + "labels": {"str": {}}, + "name": "str", + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_get_queue(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.get_queue( + queue_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_list_queues(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = client.list_queues() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @JobRouterAdministrationPreparer() + @recorded_by_proxy_async + async def test_delete_queue(self, jobrouteradministration_endpoint): + client = self.create_async_client(endpoint=jobrouteradministration_endpoint) + response = await client.delete_queue( + queue_id="str", + ) + + # please add some check logic here by yourself + # ... diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_async.py b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_async.py new file mode 100644 index 000000000000..f3271f5ebd47 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_tests/test_job_router_async.py @@ -0,0 +1,217 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import pytest +from devtools_testutils.aio import recorded_by_proxy_async +from testpreparer import JobRouterPreparer +from testpreparer_async import JobRouterClientTestBaseAsync + + +@pytest.mark.skip("you may need to update the auto-generated test case before run it") +class TestJobRouterAsync(JobRouterClientTestBaseAsync): + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_upsert_job(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = await client.upsert_job( + job_id="str", + resource={ + "etag": "str", + "id": "str", + "assignments": { + "str": { + "assignedAt": "2020-02-20 00:00:00", + "assignmentId": "str", + "closedAt": "2020-02-20 00:00:00", + "completedAt": "2020-02-20 00:00:00", + "workerId": "str", + } + }, + "attachedWorkerSelectors": [ + { + "key": "str", + "labelOperator": "str", + "expedite": bool, + "expiresAfterSeconds": 0.0, + "expiresAt": "2020-02-20 00:00:00", + "status": "str", + "value": {}, + } + ], + "channelId": "str", + "channelReference": "str", + "classificationPolicyId": "str", + "dispositionCode": "str", + "enqueuedAt": "2020-02-20 00:00:00", + "labels": {"str": {}}, + "matchingMode": "job_matching_mode", + "notes": [{"message": "str", "addedAt": "2020-02-20 00:00:00"}], + "priority": 0, + "queueId": "str", + "requestedWorkerSelectors": [ + { + "key": "str", + "labelOperator": "str", + "expedite": bool, + "expiresAfterSeconds": 0.0, + "expiresAt": "2020-02-20 00:00:00", + "status": "str", + "value": {}, + } + ], + "scheduledAt": "2020-02-20 00:00:00", + "status": "str", + "tags": {"str": {}}, + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_get_job(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = await client.get_job( + job_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_delete_job(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = await client.delete_job( + job_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_list_jobs(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = client.list_jobs() + result = [r async for r in response] + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_get_queue_position(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = await client.get_queue_position( + job_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_unassign_job(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = await client.unassign_job( + job_id="str", + assignment_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_accept_job_offer(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = await client.accept_job_offer( + worker_id="str", + offer_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_get_queue_statistics(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = await client.get_queue_statistics( + queue_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_upsert_worker(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = await client.upsert_worker( + worker_id="str", + resource={ + "etag": "str", + "id": "str", + "assignedJobs": [ + {"assignedAt": "2020-02-20 00:00:00", "assignmentId": "str", "capacityCost": 0, "jobId": "str"} + ], + "availableForOffers": bool, + "capacity": 0, + "channels": [{"capacityCostPerJob": 0, "channelId": "str", "maxNumberOfJobs": 0}], + "labels": {"str": {}}, + "loadRatio": 0.0, + "maxConcurrentOffers": 0, + "offers": [ + { + "capacityCost": 0, + "jobId": "str", + "offerId": "str", + "expiresAt": "2020-02-20 00:00:00", + "offeredAt": "2020-02-20 00:00:00", + } + ], + "queues": ["str"], + "state": "str", + "tags": {"str": {}}, + }, + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_get_worker(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = await client.get_worker( + worker_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_delete_worker(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = await client.delete_worker( + worker_id="str", + ) + + # please add some check logic here by yourself + # ... + + @JobRouterPreparer() + @recorded_by_proxy_async + async def test_list_workers(self, jobrouter_endpoint): + client = self.create_async_client(endpoint=jobrouter_endpoint) + response = client.list_workers() + result = [r async for r in response] + # please add some check logic here by yourself + # ... diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer.py b/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer.py new file mode 100644 index 000000000000..35fbaa1375aa --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer.py @@ -0,0 +1,44 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from azure.communication.jobrouter import JobRouterAdministrationClient, JobRouterClient +from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer +import functools + + +class JobRouterAdministrationClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(JobRouterAdministrationClient) + return self.create_client_from_credential( + JobRouterAdministrationClient, + credential=credential, + endpoint=endpoint, + ) + + +JobRouterAdministrationPreparer = functools.partial( + PowerShellPreparer, + "jobrouteradministration", + jobrouteradministration_endpoint="https://fake_jobrouteradministration_endpoint.com", +) + + +class JobRouterClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(JobRouterClient) + return self.create_client_from_credential( + JobRouterClient, + credential=credential, + endpoint=endpoint, + ) + + +JobRouterPreparer = functools.partial( + PowerShellPreparer, "jobrouter", jobrouter_endpoint="https://fake_jobrouter_endpoint.com" +) diff --git a/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer_async.py b/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer_async.py new file mode 100644 index 000000000000..d84cf1c088f6 --- /dev/null +++ b/sdk/communication/azure-communication-jobrouter/generated_tests/testpreparer_async.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from azure.communication.jobrouter.aio import JobRouterAdministrationClient, JobRouterClient +from devtools_testutils import AzureRecordedTestCase + + +class JobRouterAdministrationClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(JobRouterAdministrationClient, is_async=True) + return self.create_client_from_credential( + JobRouterAdministrationClient, + credential=credential, + endpoint=endpoint, + ) + + +class JobRouterClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(JobRouterClient, is_async=True) + return self.create_client_from_credential( + JobRouterClient, + credential=credential, + endpoint=endpoint, + ) diff --git a/sdk/communication/azure-communication-jobrouter/setup.py b/sdk/communication/azure-communication-jobrouter/setup.py index 98cb6119670a..af5255b5d4fb 100644 --- a/sdk/communication/azure-communication-jobrouter/setup.py +++ b/sdk/communication/azure-communication-jobrouter/setup.py @@ -5,7 +5,7 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -# coding: utf-8 + import os import re @@ -29,7 +29,7 @@ setup( name=PACKAGE_NAME, version=version, - description="Microsoft {} Client Library for Python".format(PACKAGE_PPRINT_NAME), + description="Microsoft Corporation {} Client Library for Python".format(PACKAGE_PPRINT_NAME), long_description=open("README.md", "r").read(), long_description_content_type="text/markdown", license="MIT License", @@ -42,7 +42,6 @@ "Programming Language :: Python", "Programming Language :: Python :: 3 :: Only", "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", @@ -67,5 +66,5 @@ "azure-core>=1.30.0", "typing-extensions>=4.6.0", ], - python_requires=">=3.8", + python_requires=">=3.9", ) diff --git a/sdk/communication/azure-communication-jobrouter/tests/_shared/communication_service_preparer.py b/sdk/communication/azure-communication-jobrouter/tests/_shared/communication_service_preparer.py index 2502a4713a88..e552ff83a69a 100644 --- a/sdk/communication/azure-communication-jobrouter/tests/_shared/communication_service_preparer.py +++ b/sdk/communication/azure-communication-jobrouter/tests/_shared/communication_service_preparer.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # ------------------------------------ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. diff --git a/sdk/communication/azure-communication-jobrouter/tests/_validators.py b/sdk/communication/azure-communication-jobrouter/tests/_validators.py index c9d8827793c9..78d1c33a3a63 100644 --- a/sdk/communication/azure-communication-jobrouter/tests/_validators.py +++ b/sdk/communication/azure-communication-jobrouter/tests/_validators.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding: utf-8 # ------------------------------------------------------------------------- diff --git a/sdk/communication/azure-communication-jobrouter/tests/test_router_job_async.py b/sdk/communication/azure-communication-jobrouter/tests/test_router_job_async.py index 7f4e9d46f517..a37f5abf9e9c 100644 --- a/sdk/communication/azure-communication-jobrouter/tests/test_router_job_async.py +++ b/sdk/communication/azure-communication-jobrouter/tests/test_router_job_async.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # coding: utf-8 # ------------------------------------------------------------------------- diff --git a/sdk/communication/azure-communication-jobrouter/tsp-location.yaml b/sdk/communication/azure-communication-jobrouter/tsp-location.yaml index 81316b5b2ed6..8f1e550f2543 100644 --- a/sdk/communication/azure-communication-jobrouter/tsp-location.yaml +++ b/sdk/communication/azure-communication-jobrouter/tsp-location.yaml @@ -1,5 +1,4 @@ -repo: Azure/azure-rest-api-specs -additionalDirectories: [] directory: specification/communication/Communication.JobRouter -commit: 1c04f51cbfa195fe177239cf63d00d3539006800 - +commit: 726419b7eba57b9b5888ca11e055c8f82dcaae58 +repo: Azure/azure-rest-api-specs +additionalDirectories: