diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/__init__.py b/sdk/confidentialledger/azure-confidentialledger/azure/__init__.py index 8db66d3d0f0f..d55ccad1f573 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/__init__.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/__init__.py @@ -1 +1 @@ -__path__ = __import__("pkgutil").extend_path(__path__, __name__) +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/__init__.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/__init__.py index 7a7b8cfc1b1b..3045fed24d95 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/__init__.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/__init__.py @@ -5,20 +5,28 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._client import ConfidentialLedgerClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ConfidentialLedgerClient # type: ignore from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ["ConfidentialLedgerClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__ = [ + "ConfidentialLedgerClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_client.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_client.py index e3e1ea0641a8..6154fc38688c 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_client.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_client.py @@ -7,46 +7,59 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, TYPE_CHECKING +from typing import Any +from typing_extensions import Self from azure.core import PipelineClient +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from ._configuration import ConfidentialLedgerClientConfiguration from ._operations import ConfidentialLedgerClientOperationsMixin from ._serialization import Deserializer, Serializer -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - -class ConfidentialLedgerClient( - ConfidentialLedgerClientOperationsMixin -): # pylint: disable=client-accepts-api-version-keyword +class ConfidentialLedgerClient(ConfidentialLedgerClientOperationsMixin): """The ConfidentialLedgerClient writes and retrieves ledger entries against the Confidential Ledger service. - :param ledger_endpoint: The Confidential Ledger URL, for example + :param endpoint: The Confidential Ledger URL, for example https://contoso.confidentialledger.azure.com. Required. - :type ledger_endpoint: str - :keyword api_version: Api Version. Default value is "2022-05-13". Note that overriding this - default value may result in unsupported behavior. + :type endpoint: str + :keyword api_version: Api Version. Default value is "2024-08-22-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, ledger_endpoint: str, **kwargs: Any + self, endpoint: str, **kwargs: Any ) -> None: - _endpoint = "{ledgerEndpoint}" - self._config = ConfidentialLedgerClientConfiguration(ledger_endpoint=ledger_endpoint, **kwargs) - self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) + _endpoint = "{endpoint}" + self._config = ConfidentialLedgerClientConfiguration(endpoint=endpoint, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -66,23 +79,18 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: request_copy = deepcopy(request) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - def close(self): - # type: () -> None + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> ConfidentialLedgerClient + def __enter__(self) -> Self: self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_configuration.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_configuration.py index 3436c18050cb..4237ff1f5c83 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_configuration.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_configuration.py @@ -8,48 +8,44 @@ from typing import Any -from azure.core.configuration import Configuration from azure.core.pipeline import policies from ._version import VERSION -class ConfidentialLedgerClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class ConfidentialLedgerClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for ConfidentialLedgerClient. Note that all parameters used to create this instance are saved as instance attributes. - :param ledger_endpoint: The Confidential Ledger URL, for example + :param endpoint: The Confidential Ledger URL, for example https://contoso.confidentialledger.azure.com. Required. - :type ledger_endpoint: str - :keyword api_version: Api Version. Default value is "2022-05-13". Note that overriding this - default value may result in unsupported behavior. + :type endpoint: str + :keyword api_version: Api Version. Default value is "2024-08-22-preview". Note that overriding + this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, ledger_endpoint: str, **kwargs: Any) -> None: - super(ConfidentialLedgerClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2022-05-13") # type: str + def __init__(self, endpoint: str, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2024-08-22-preview") - if ledger_endpoint is None: - raise ValueError("Parameter 'ledger_endpoint' must not be None.") + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") - self.ledger_endpoint = ledger_endpoint + self.endpoint = endpoint self.api_version = api_version kwargs.setdefault("sdk_moniker", "confidentialledger/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> None + def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) 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") diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/__init__.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/__init__.py index a07d13d30393..9e343eef1ebf 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/__init__.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/__init__.py @@ -5,15 +5,21 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import ConfidentialLedgerClientOperationsMixin +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ConfidentialLedgerClientOperationsMixin # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ConfidentialLedgerClientOperationsMixin", ] -__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/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/_operations.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/_operations.py index b71c2dc195fd..e579f9d969ba 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/_operations.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/_operations.py @@ -6,15 +6,17 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, Callable, Dict, IO, Iterable, Optional, TypeVar, Union, cast, overload -from urllib.parse import parse_qs, urljoin, urlparse +from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.exceptions import ( ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, + ResourceNotModifiedError, map_error, ) from azure.core.paging import ItemPaged @@ -24,12 +26,12 @@ from azure.core.utils import case_insensitive_dict from .._serialization import Serializer -from .._vendor import MixinABC, _format_url_section +from .._vendor import ConfidentialLedgerClientMixinABC if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -38,11 +40,11 @@ _SERIALIZER.client_side_validation = False -def build_get_constitution_request(**kwargs: Any) -> HttpRequest: +def build_confidential_ledger_get_constitution_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -57,11 +59,13 @@ def build_get_constitution_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_consortium_members_request(**kwargs: Any) -> HttpRequest: +def build_confidential_ledger_list_consortium_members_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -76,11 +80,11 @@ def build_list_consortium_members_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_enclave_quotes_request(**kwargs: Any) -> HttpRequest: +def build_confidential_ledger_get_enclave_quotes_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -95,11 +99,11 @@ def build_get_enclave_quotes_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_collections_request(**kwargs: Any) -> HttpRequest: +def build_confidential_ledger_list_collections_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -114,17 +118,17 @@ def build_list_collections_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_list_ledger_entries_request( +def build_confidential_ledger_list_ledger_entries_request( # pylint: disable=name-too-long *, collection_id: Optional[str] = None, from_transaction_id: Optional[str] = None, to_transaction_id: Optional[str] = None, - **kwargs: Any + **kwargs: Any, ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -145,13 +149,14 @@ def build_list_ledger_entries_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_ledger_entry_request(**kwargs: Any) -> HttpRequest: +def build_confidential_ledger_create_ledger_entry_request( # pylint: disable=name-too-long + *, collection_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - collection_id = kwargs.pop("collection_id", _params.pop("collectionId", None)) # type: Optional[str] - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -170,13 +175,13 @@ def build_create_ledger_entry_request(**kwargs: Any) -> HttpRequest: return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_ledger_entry_request( +def build_confidential_ledger_get_ledger_entry_request( # pylint: disable=name-too-long transaction_id: str, *, collection_id: Optional[str] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -185,7 +190,7 @@ def build_get_ledger_entry_request( "transactionId": _SERIALIZER.url("transaction_id", transaction_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -198,11 +203,13 @@ def build_get_ledger_entry_request( return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_receipt_request(transaction_id: str, **kwargs: Any) -> HttpRequest: +def build_confidential_ledger_get_receipt_request( # pylint: disable=name-too-long + transaction_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -211,7 +218,7 @@ def build_get_receipt_request(transaction_id: str, **kwargs: Any) -> HttpRequest "transactionId": _SERIALIZER.url("transaction_id", transaction_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -222,11 +229,13 @@ def build_get_receipt_request(transaction_id: str, **kwargs: Any) -> HttpRequest return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_transaction_status_request(transaction_id: str, **kwargs: Any) -> HttpRequest: +def build_confidential_ledger_get_transaction_status_request( # pylint: disable=name-too-long + transaction_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -235,7 +244,7 @@ def build_get_transaction_status_request(transaction_id: str, **kwargs: Any) -> "transactionId": _SERIALIZER.url("transaction_id", transaction_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -246,11 +255,13 @@ def build_get_transaction_status_request(transaction_id: str, **kwargs: Any) -> return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_current_ledger_entry_request(*, collection_id: Optional[str] = None, **kwargs: Any) -> HttpRequest: +def build_confidential_ledger_get_current_ledger_entry_request( # pylint: disable=name-too-long + *, collection_id: Optional[str] = None, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -267,11 +278,51 @@ def build_get_current_ledger_entry_request(*, collection_id: Optional[str] = Non return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_delete_user_request(user_id: str, **kwargs: Any) -> HttpRequest: +def build_confidential_ledger_list_users_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _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-08-22-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/app/users" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_confidential_ledger_list_ledger_users_request(**kwargs: Any) -> HttpRequest: # pylint: disable=name-too-long + _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-08-22-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/app/ledgerUsers" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_confidential_ledger_delete_user_request( # pylint: disable=name-too-long + user_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -280,7 +331,7 @@ def build_delete_user_request(user_id: str, **kwargs: Any) -> HttpRequest: "userId": _SERIALIZER.url("user_id", user_id, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -291,11 +342,13 @@ def build_delete_user_request(user_id: str, **kwargs: Any) -> HttpRequest: return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) -def build_get_user_request(user_id: str, **kwargs: Any) -> HttpRequest: +def build_confidential_ledger_get_user_request( # pylint: disable=name-too-long + user_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -304,7 +357,7 @@ def build_get_user_request(user_id: str, **kwargs: Any) -> HttpRequest: "userId": _SERIALIZER.url("user_id", user_id, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -315,12 +368,14 @@ def build_get_user_request(user_id: str, **kwargs: Any) -> HttpRequest: return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -def build_create_or_update_user_request(user_id: str, **kwargs: Any) -> HttpRequest: +def build_confidential_ledger_create_or_update_user_request( # pylint: disable=name-too-long + user_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -329,7 +384,7 @@ def build_create_or_update_user_request(user_id: str, **kwargs: Any) -> HttpRequ "userId": _SERIALIZER.url("user_id", user_id, "str", skip_quote=True), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -342,320 +397,1718 @@ def build_create_or_update_user_request(user_id: str, **kwargs: Any) -> HttpRequ return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) -class ConfidentialLedgerClientOperationsMixin(MixinABC): - @distributed_trace - def get_constitution(self, **kwargs: Any) -> JSON: - """Gets the constitution used for governance. - - The constitution is a script that assesses and applies proposals from consortium members. +def build_confidential_ledger_delete_ledger_user_request( # pylint: disable=name-too-long + user_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :return: JSON object - :rtype: JSON - :raises ~azure.core.exceptions.HttpResponseError: + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) + accept = _headers.pop("Accept", "application/json") - Example: - .. code-block:: python + # Construct URL + _url = "/app/ledgerUsers/{userId}" + path_format_arguments = { + "userId": _SERIALIZER.url("user_id", user_id, "str", skip_quote=True), + } - # response body for status code(s): 200 - response == { - "digest": "str", # SHA256 digest of the constitution script. Required. - "script": "str" # Contents of the constitution. Required. - } - """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop("error_map", {}) or {}) + _url: str = _url.format(**path_format_arguments) # type: ignore - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - request = build_get_constitution_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), - } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response +def build_confidential_ledger_get_ledger_user_request( # pylint: disable=name-too-long + user_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) + accept = _headers.pop("Accept", "application/json") - if response.content: - deserialized = response.json() - else: - deserialized = None + # Construct URL + _url = "/app/ledgerUsers/{userId}" + path_format_arguments = { + "userId": _SERIALIZER.url("user_id", user_id, "str", skip_quote=True), + } - if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + _url: str = _url.format(**path_format_arguments) # type: ignore - return cast(JSON, deserialized) + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - @distributed_trace - def list_consortium_members(self, **kwargs: Any) -> Iterable[JSON]: - """Lists the consortium members. + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - Consortium members can manage the Confidential Ledger. + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] - :raises ~azure.core.exceptions.HttpResponseError: - Example: - .. code-block:: python +def build_confidential_ledger_create_or_update_ledger_user_request( # pylint: disable=name-too-long + user_id: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - # response body for status code(s): 200 - response == { - "certificate": "str", # PEM-encoded certificate associated with the member. - Required. - "id": "str" # Identifier assigned to the member. Required. - } - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) + accept = _headers.pop("Accept", "application/json") - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + # Construct URL + _url = "/app/ledgerUsers/{userId}" + path_format_arguments = { + "userId": _SERIALIZER.url("user_id", user_id, "str", skip_quote=True), + } - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop("error_map", {}) or {}) + _url: str = _url.format(**path_format_arguments) # type: ignore - def prepare_request(next_link=None): - if not next_link: + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - request = build_list_consortium_members_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), - } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - else: - # make call to next link with the client's api-version - _parsed_next_link = urlparse(next_link) - _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) - path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), - } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - return request - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["members"] - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.get("nextLink", None), iter(list_of_elem) +def build_confidential_ledger_get_user_defined_endpoint_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - def get_next(next_link=None): - request = prepare_request(next_link) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) + accept = _headers.pop("Accept", "application/json") - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response + # Construct URL + _url = "/app/userDefinedEndpoints" - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - return pipeline_response + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return ItemPaged(get_next, extract_data) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - @distributed_trace - def get_enclave_quotes(self, **kwargs: Any) -> JSON: - """Gets quotes for all nodes of the Confidential Ledger. - A quote is an SGX enclave measurement that can be used to verify the validity of a node and its - enclave. +def build_confidential_ledger_create_user_defined_endpoint_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :return: JSON object - :rtype: JSON - :raises ~azure.core.exceptions.HttpResponseError: + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) + accept = _headers.pop("Accept", "application/json") - Example: - .. code-block:: python + # Construct URL + _url = "/app/userDefinedEndpoints" - # response body for status code(s): 200 - response == { - "currentNodeId": "str", # Id of the Confidential Ledger node responding to - the request. Required. - "enclaveQuotes": { - "str": { - "mrenclave": "str", # Optional. MRENCLAVE value of the code - running in the enclave. - "nodeId": "str", # ID assigned to this node. Required. - "quoteVersion": "str", # Version of the quote presented. - Required. - "raw": "str" # Raw SGX quote, parsable by tools like Open - Enclave's oeverify. Required. - } - } - } - """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop("error_map", {}) or {}) + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - request = build_get_enclave_quotes_request( - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), - } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) +def build_confidential_ledger_get_runtime_options_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - response = pipeline_response.http_response + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) + accept = _headers.pop("Accept", "application/json") - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + # Construct URL + _url = "/app/userDefinedEndpoints/runTimeOptions" - if response.content: - deserialized = response.json() - else: - deserialized = None + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - return cast(JSON, deserialized) + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - @distributed_trace - def list_collections(self, **kwargs: Any) -> Iterable[JSON]: - """Retrieves a list of collection ids present in the Confidential Ledger. - Collection ids are user-created collections of ledger entries. +def build_confidential_ledger_update_runtime_options_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] - :raises ~azure.core.exceptions.HttpResponseError: + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) + accept = _headers.pop("Accept", "application/json") - Example: - .. code-block:: python + # Construct URL + _url = "/app/userDefinedEndpoints/runTimeOptions" - # response body for status code(s): 200 - response == { - "collectionId": "str" # Required. - } - """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} - error_map.update(kwargs.pop("error_map", {}) or {}) + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - def prepare_request(next_link=None): - if not next_link: - request = build_list_collections_request( - api_version=self._config.api_version, +def build_confidential_ledger_get_user_defined_endpoints_module_request( # pylint: disable=name-too-long + *, module: 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-08-22-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/app/userDefinedEndpoints/modules" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["module"] = _SERIALIZER.query("module", module, "str", skip_quote=True) + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_confidential_ledger_get_user_defined_role_request( # pylint: disable=name-too-long + *, role_name: 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-08-22-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/app/roles" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["roleName"] = _SERIALIZER.query("role_name", role_name, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_confidential_ledger_create_user_defined_role_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/app/roles" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + 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="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_confidential_ledger_update_user_defined_role_request( # pylint: disable=name-too-long + **kwargs: Any, +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/app/roles" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + 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="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_confidential_ledger_delete_user_defined_role_request( # pylint: disable=name-too-long + *, role_name: 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-08-22-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/app/roles" + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + _params["roleName"] = _SERIALIZER.query("role_name", role_name, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +class ConfidentialLedgerClientOperationsMixin( # pylint: disable=too-many-public-methods + ConfidentialLedgerClientMixinABC +): + + @distributed_trace + def get_constitution(self, **kwargs: Any) -> JSON: + """Gets the constitution used for governance. + + The constitution is a script that assesses and applies proposals from consortium members. + + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "digest": "str", + "script": "str" + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_constitution_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace + def list_consortium_members(self, **kwargs: Any) -> Iterable[JSON]: + """Lists the consortium members. + + Consortium members can manage the Confidential Ledger. + + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "certificate": "str", + "id": "str" + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_confidential_ledger_list_consortium_members_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "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 + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["members"] + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get_enclave_quotes(self, **kwargs: Any) -> JSON: + """Gets quotes for all nodes of the Confidential Ledger. + + A quote is an SGX enclave measurement that can be used to verify the validity of a node and its + enclave. + + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "currentNodeId": "str", + "enclaveQuotes": { + "str": { + "nodeId": "str", + "quoteVersion": "str", + "raw": "str", + "mrenclave": "str" + } + } + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_enclave_quotes_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace + def list_collections(self, **kwargs: Any) -> Iterable[JSON]: + """Retrieves a list of collection ids present in the Confidential Ledger. + + Collection ids are user-created collections of ledger entries. + + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "collectionId": "str" + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_confidential_ledger_list_collections_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "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 + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["collections"] + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_ledger_entries( + self, + *, + collection_id: Optional[str] = None, + from_transaction_id: Optional[str] = None, + to_transaction_id: Optional[str] = None, + **kwargs: Any, + ) -> Iterable[JSON]: + """Gets ledger entries from a collection corresponding to a range. + + A collection id may optionally be specified. Only entries in the specified (or default) + collection will be returned. + + :keyword collection_id: The collection id. Default value is None. + :paramtype collection_id: str + :keyword from_transaction_id: Specify the first transaction ID in a range. Default value is + None. + :paramtype from_transaction_id: str + :keyword to_transaction_id: Specify the last transaction ID in a range. Default value is None. + :paramtype to_transaction_id: str + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "contents": "str", + "collectionId": "str", + "transactionId": "str" + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_confidential_ledger_list_ledger_entries_request( + collection_id=collection_id, + from_transaction_id=from_transaction_id, + to_transaction_id=to_transaction_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "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 + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["entries"] + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @overload + def create_ledger_entry( + self, entry: JSON, *, collection_id: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + ) -> JSON: + """Writes a ledger entry. + + A collection id may optionally be specified. + + :param entry: Ledger entry. Required. + :type entry: JSON + :keyword collection_id: The collection id. Default value is None. + :paramtype collection_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + entry = { + "contents": "str", + "collectionId": "str", + "transactionId": "str" + } + + # response body for status code(s): 200 + response == { + "collectionId": "str" + } + """ + + @overload + def create_ledger_entry( + self, + entry: IO[bytes], + *, + collection_id: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any, + ) -> JSON: + """Writes a ledger entry. + + A collection id may optionally be specified. + + :param entry: Ledger entry. Required. + :type entry: IO[bytes] + :keyword collection_id: The collection id. Default value is None. + :paramtype collection_id: str + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "collectionId": "str" + } + """ + + @distributed_trace + def create_ledger_entry( + self, entry: Union[JSON, IO[bytes]], *, collection_id: Optional[str] = None, **kwargs: Any + ) -> JSON: + """Writes a ledger entry. + + A collection id may optionally be specified. + + :param entry: Ledger entry. Is either a JSON type or a IO[bytes] type. Required. + :type entry: JSON or IO[bytes] + :keyword collection_id: The collection id. Default value is None. + :paramtype collection_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + entry = { + "contents": "str", + "collectionId": "str", + "transactionId": "str" + } + + # response body for status code(s): 200 + response == { + "collectionId": "str" + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(entry, (IOBase, bytes)): + _content = entry + else: + _json = entry + + _request = build_confidential_ledger_create_ledger_entry_request( + collection_id=collection_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + response_headers = {} + response_headers["x-ms-ccf-transaction-id"] = self._deserialize( + "str", response.headers.get("x-ms-ccf-transaction-id") + ) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace + def get_ledger_entry(self, transaction_id: str, *, collection_id: Optional[str] = None, **kwargs: Any) -> JSON: + """Gets the ledger entry at the specified transaction id. A collection id may optionally be + specified to indicate the collection from which to fetch the value. + + To return older ledger entries, the relevant sections of the ledger must be read from disk and + validated. To prevent blocking within the enclave, the response will indicate whether the entry + is ready and part of the response, or if the loading is still ongoing. + + :param transaction_id: Identifies a write transaction. Required. + :type transaction_id: str + :keyword collection_id: The collection id. Default value is None. + :paramtype collection_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "state": "str", + "entry": { + "contents": "str", + "collectionId": "str", + "transactionId": "str" + } + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_ledger_entry_request( + transaction_id=transaction_id, + collection_id=collection_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace + def get_receipt(self, transaction_id: str, **kwargs: Any) -> JSON: + """Gets a receipt certifying ledger contents at a particular transaction id. + + Gets a receipt certifying ledger contents at a particular transaction id. + + :param transaction_id: Identifies a write transaction. Required. + :type transaction_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "state": "str", + "transactionId": "str", + "applicationClaims": [ + { + "kind": "str", + "digest": { + "protocol": "str", + "value": "str" + }, + "ledgerEntry": { + "protocol": "str", + "collectionId": "str", + "contents": "str", + "secretKey": "str" + } + } + ], + "receipt": { + "nodeId": "str", + "proof": [ + { + "left": "str", + "right": "str" + } + ], + "signature": "str", + "cert": "str", + "leaf": "str", + "leafComponents": { + "claimsDigest": "str", + "commitEvidence": "str", + "writeSetDigest": "str" + }, + "root": "str", + "serviceEndorsements": [ + "str" + ] + } + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_receipt_request( + transaction_id=transaction_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace + def get_transaction_status(self, transaction_id: str, **kwargs: Any) -> JSON: + """Gets the status of an entry identified by a transaction id. + + Gets the status of an entry identified by a transaction id. + + :param transaction_id: Identifies a write transaction. Required. + :type transaction_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "state": "str", + "transactionId": "str" + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_transaction_status_request( + transaction_id=transaction_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace + def get_current_ledger_entry(self, *, collection_id: Optional[str] = None, **kwargs: Any) -> JSON: + """Gets the current value available in the ledger. + + A collection id may optionally be specified. + + :keyword collection_id: The collection id. Default value is None. + :paramtype collection_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "contents": "str", + "collectionId": "str", + "transactionId": "str" + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_current_ledger_entry_request( + collection_id=collection_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace + def list_users(self, **kwargs: Any) -> Iterable[JSON]: + """Gets details on a list of users. + + All users' object IDs and single role per user will be returned. + + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "assignedRole": "str", + "userId": "str" + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_confidential_ledger_list_users_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "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 + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["ledgerUsers"] + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def list_ledger_users(self, **kwargs: Any) -> Iterable[JSON]: + """Gets details on a list of users. + + All users' object IDs and multiple roles will be returned. + + :return: An iterator like instance of JSON object + :rtype: ~azure.core.paging.ItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "assignedRoles": [ + "str" + ], + "userId": "str" + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_confidential_ledger_list_ledger_users_request( + api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version - _parsed_next_link = urlparse(next_link) - _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["collections"] + list_of_elem = deserialized["ledgerUsers"] if cls: - list_of_elem = cls(list_of_elem) - return deserialized.get("nextLink", None), iter(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, iter(list_of_elem) def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def delete_user(self, user_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Deletes a user from the Confidential Ledger. + + Deletes a user from the Confidential Ledger. + + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_delete_user_request( + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + 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 + + @distributed_trace + def get_user(self, user_id: str, **kwargs: Any) -> JSON: + """Gets a user. + + Gets a user. + + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "assignedRole": "str", + "userId": "str" + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_user_request( + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @overload + def create_or_update_user( + self, user_id: str, user_details: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any + ) -> JSON: + """Adds a user or updates a user's fields. + + A JSON merge patch is applied for existing users. + + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :param user_details: Details about a Confidential Ledger user. Required. + :type user_details: 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 + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + user_details = { + "assignedRole": "str", + "userId": "str" + } + + # response body for status code(s): 200 + response == { + "assignedRole": "str", + "userId": "str" + } + """ + + @overload + def create_or_update_user( + self, + user_id: str, + user_details: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any, + ) -> JSON: + """Adds a user or updates a user's fields. + + A JSON merge patch is applied for existing users. + + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :param user_details: Details about a Confidential Ledger user. Required. + :type user_details: 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 + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "assignedRole": "str", + "userId": "str" + } + """ + + @distributed_trace + def create_or_update_user(self, user_id: str, user_details: Union[JSON, IO[bytes]], **kwargs: Any) -> JSON: + """Adds a user or updates a user's fields. + + A JSON merge patch is applied for existing users. + + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :param user_details: Details about a Confidential Ledger user. Is either a JSON type or a + IO[bytes] type. Required. + :type user_details: JSON or IO[bytes] + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + user_details = { + "assignedRole": "str", + "userId": "str" + } + + # response body for status code(s): 200 + response == { + "assignedRole": "str", + "userId": "str" + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + content_type = content_type or "application/merge-patch+json" + _json = None + _content = None + if isinstance(user_details, (IOBase, bytes)): + _content = user_details + else: + _json = user_details + + _request = build_confidential_ledger_create_or_update_user_request( + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace + def delete_ledger_user(self, user_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Deletes a user with multiple roles from the Confidential Ledger. + + Deletes a user with multiple roles from the Confidential Ledger. + + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_delete_ledger_user_request( + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + response = pipeline_response.http_response - return pipeline_response + if response.status_code not in [204]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) - return ItemPaged(get_next, extract_data) + if cls: + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace - def list_ledger_entries( - self, - *, - collection_id: Optional[str] = None, - from_transaction_id: Optional[str] = None, - to_transaction_id: Optional[str] = None, - **kwargs: Any - ) -> Iterable[JSON]: - """Gets ledger entries from a collection corresponding to a range. + def get_ledger_user(self, user_id: str, **kwargs: Any) -> JSON: + """Gets a user with multiple roles. - A collection id may optionally be specified. Only entries in the specified (or default) - collection will be returned. + Gets a user with multiple roles. - :keyword collection_id: The collection id. Default value is None. - :paramtype collection_id: str - :keyword from_transaction_id: Specify the first transaction ID in a range. Default value is - None. - :paramtype from_transaction_id: str - :keyword to_transaction_id: Specify the last transaction ID in a range. Default value is None. - :paramtype to_transaction_id: str - :return: An iterator like instance of JSON object - :rtype: ~azure.core.paging.ItemPaged[JSON] + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :return: JSON object + :rtype: JSON :raises ~azure.core.exceptions.HttpResponseError: Example: @@ -663,91 +2116,77 @@ def list_ledger_entries( # response body for status code(s): 200 response == { - "collectionId": "str", # Optional. - "contents": "str", # Contents of the ledger entry. Required. - "transactionId": "str" # Optional. A unique identifier for the state of the - ledger. If returned as part of a LedgerEntry, it indicates the state from which - the entry was read. + "assignedRoles": [ + "str" + ], + "userId": "str" } """ - _headers = kwargs.pop("headers", {}) or {} - _params = kwargs.pop("params", {}) or {} - - cls = kwargs.pop("cls", None) # type: ClsType[JSON] - - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) - def prepare_request(next_link=None): - if not next_link: - - request = build_list_ledger_entries_request( - collection_id=collection_id, - from_transaction_id=from_transaction_id, - to_transaction_id=to_transaction_id, - api_version=self._config.api_version, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), - } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} - else: - # make call to next link with the client's api-version - _parsed_next_link = urlparse(next_link) - _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) - _next_request_params["api-version"] = self._config.api_version - request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) - path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), - } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + cls: ClsType[JSON] = kwargs.pop("cls", None) - return request + _request = build_confidential_ledger_get_ledger_user_request( + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized["entries"] - if cls: - list_of_elem = cls(list_of_elem) - return deserialized.get("nextLink", None), iter(list_of_elem) + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) - def get_next(next_link=None): - request = prepare_request(next_link) + response = pipeline_response.http_response - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs - ) - response = pipeline_response.http_response + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) - if response.status_code not in [200]: - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) + if response.content: + deserialized = response.json() + else: + deserialized = None - return pipeline_response + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return ItemPaged(get_next, extract_data) + return cast(JSON, deserialized) # type: ignore @overload - def create_ledger_entry( - self, entry: JSON, *, collection_id: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + def create_or_update_ledger_user( + self, + user_id: str, + user_multiple_roles: JSON, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any, ) -> JSON: - """Writes a ledger entry. + """Adds a user or updates a user's fields. - A collection id may optionally be specified. + A JSON merge patch is applied for existing users. - :param entry: Ledger entry. Required. - :type entry: JSON - :keyword collection_id: The collection id. Default value is None. - :paramtype collection_id: str + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :param user_multiple_roles: Details about a Confidential Ledger user with multiple roles. + Required. + :type user_multiple_roles: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/json". + Default value is "application/merge-patch+json". :paramtype content_type: str :return: JSON object :rtype: JSON @@ -757,34 +2196,42 @@ def create_ledger_entry( .. code-block:: python # JSON input template you can fill out and use as your body input. - entry = { - "collectionId": "str", # Optional. - "contents": "str", # Contents of the ledger entry. Required. - "transactionId": "str" # Optional. A unique identifier for the state of the - ledger. If returned as part of a LedgerEntry, it indicates the state from which - the entry was read. + user_multiple_roles = { + "assignedRoles": [ + "str" + ], + "userId": "str" } # response body for status code(s): 200 response == { - "collectionId": "str" # Required. + "assignedRoles": [ + "str" + ], + "userId": "str" } """ @overload - def create_ledger_entry( - self, entry: IO, *, collection_id: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + def create_or_update_ledger_user( + self, + user_id: str, + user_multiple_roles: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any, ) -> JSON: - """Writes a ledger entry. + """Adds a user or updates a user's fields. - A collection id may optionally be specified. + A JSON merge patch is applied for existing users. - :param entry: Ledger entry. Required. - :type entry: IO - :keyword collection_id: The collection id. Default value is None. - :paramtype collection_id: str + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :param user_multiple_roles: Details about a Confidential Ledger user with multiple roles. + Required. + :type user_multiple_roles: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/json". + Default value is "application/merge-patch+json". :paramtype content_type: str :return: JSON object :rtype: JSON @@ -795,25 +2242,26 @@ def create_ledger_entry( # response body for status code(s): 200 response == { - "collectionId": "str" # Required. + "assignedRoles": [ + "str" + ], + "userId": "str" } """ @distributed_trace - def create_ledger_entry( - self, entry: Union[JSON, IO], *, collection_id: Optional[str] = None, **kwargs: Any + def create_or_update_ledger_user( + self, user_id: str, user_multiple_roles: Union[JSON, IO[bytes]], **kwargs: Any ) -> JSON: - """Writes a ledger entry. + """Adds a user or updates a user's fields. - A collection id may optionally be specified. + A JSON merge patch is applied for existing users. - :param entry: Ledger entry. Is either a model type or a IO type. Required. - :type entry: JSON or IO - :keyword collection_id: The collection id. Default value is None. - :paramtype collection_id: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :param user_multiple_roles: Details about a Confidential Ledger user with multiple roles. Is + either a JSON type or a IO[bytes] type. Required. + :type user_multiple_roles: JSON or IO[bytes] :return: JSON object :rtype: JSON :raises ~azure.core.exceptions.HttpResponseError: @@ -821,30 +2269,46 @@ def create_ledger_entry( Example: .. code-block:: python + # JSON input template you can fill out and use as your body input. + user_multiple_roles = { + "assignedRoles": [ + "str" + ], + "userId": "str" + } + # response body for status code(s): 200 response == { - "collectionId": "str" # Required. + "assignedRoles": [ + "str" + ], + "userId": "str" } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) - content_type = content_type or "application/json" + content_type = content_type or "application/merge-patch+json" _json = None _content = None - if isinstance(entry, (IO, bytes)): - _content = entry + if isinstance(user_multiple_roles, (IOBase, bytes)): + _content = user_multiple_roles else: - _json = entry + _json = user_multiple_roles - request = build_create_ledger_entry_request( - collection_id=collection_id, + _request = build_confidential_ledger_create_or_update_ledger_user_request( + user_id=user_id, content_type=content_type, api_version=self._config.api_version, json=_json, @@ -853,14 +2317,13 @@ def create_ledger_entry( params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -869,34 +2332,22 @@ def create_ledger_entry( map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - response_headers = {} - response_headers["x-ms-ccf-transaction-id"] = self._deserialize( - "str", response.headers.get("x-ms-ccf-transaction-id") - ) - if response.content: deserialized = response.json() else: deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore @distributed_trace - def get_ledger_entry(self, transaction_id: str, *, collection_id: Optional[str] = None, **kwargs: Any) -> JSON: - """Gets the ledger entry at the specified transaction id. A collection id may optionally be - specified to indicate the collection from which to fetch the value. + def get_user_defined_endpoint(self, **kwargs: Any) -> JSON: + """Gets a user defined endpoint. - To return older ledger entries, the relevant sections of the ledger must be read from disk and - validated. To prevent blocking within the enclave, the response will indicate whether the entry - is ready and part of the response, or if the loading is still ongoing. + Returns the user defined endpoint in the ACL instance. - :param transaction_id: Identifies a write transaction. Required. - :type transaction_id: str - :keyword collection_id: The collection id. Default value is None. - :paramtype collection_id: str :return: JSON object :rtype: JSON :raises ~azure.core.exceptions.HttpResponseError: @@ -906,42 +2357,101 @@ def get_ledger_entry(self, transaction_id: str, *, collection_id: Optional[str] # response body for status code(s): 200 response == { - "entry": { - "collectionId": "str", # Optional. The ledger entry found as a - result of the query. This is only available if the query is in Ready state. - "contents": "str", # Contents of the ledger entry. Required. - "transactionId": "str" # Optional. A unique identifier for the state - of the ledger. If returned as part of a LedgerEntry, it indicates the state - from which the entry was read. + "metadata": { + "endpoints": { + "str": { + "delete": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "get": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "patch": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "put": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + } + } + } }, - "state": "str" # State of a ledger query. Required. Known values are: - "Loading" and "Ready". + "modules": {} } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_ledger_entry_request( - transaction_id=transaction_id, - collection_id=collection_id, + _request = build_confidential_ledger_get_user_defined_endpoint_request( api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -956,78 +2466,307 @@ def get_ledger_entry(self, transaction_id: str, *, collection_id: Optional[str] deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @overload + def create_user_defined_endpoint( + self, bundle: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Creates a user defined endpoint. + + Creates the user defined endpoint in the ACL instance. + + :param bundle: bundle parameter description. Required. + :type bundle: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + bundle = { + "metadata": { + "endpoints": { + "str": { + "delete": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "get": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "patch": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "put": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + } + } + } + }, + "modules": {} + } + """ + + @overload + def create_user_defined_endpoint( + self, bundle: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Creates a user defined endpoint. + + Creates the user defined endpoint in the ACL instance. - return cast(JSON, deserialized) + :param bundle: bundle parameter description. Required. + :type bundle: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ @distributed_trace - def get_receipt(self, transaction_id: str, **kwargs: Any) -> JSON: - """Gets a receipt certifying ledger contents at a particular transaction id. + def create_user_defined_endpoint( # pylint: disable=inconsistent-return-statements + self, bundle: Union[JSON, IO[bytes]], **kwargs: Any + ) -> None: + """Creates a user defined endpoint. - Gets a receipt certifying ledger contents at a particular transaction id. + Creates the user defined endpoint in the ACL instance. - :param transaction_id: Identifies a write transaction. Required. - :type transaction_id: str - :return: JSON object - :rtype: JSON + :param bundle: bundle parameter description. Is either a JSON type or a IO[bytes] type. + Required. + :type bundle: JSON or IO[bytes] + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: Example: .. code-block:: python - # response body for status code(s): 200 - response == { - "receipt": { - "cert": "str", # Optional. - "leaf": "str", # Optional. - "leafComponents": { - "claimsDigest": "str", # Optional. - "commitEvidence": "str", # Optional. - "writeSetDigest": "str" # Optional. - }, - "nodeId": "str", # Required. - "proof": [ - { - "left": "str", # Optional. Required. - "right": "str" # Optional. Required. + # JSON input template you can fill out and use as your body input. + bundle = { + "metadata": { + "endpoints": { + "str": { + "delete": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "get": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "patch": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "put": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + } } - ], - "root": "str", # Optional. - "serviceEndorsements": [ - "str" # Optional. - ], - "signature": "str" # Required. + } }, - "state": "str", # State of a ledger query. Required. Known values are: - "Loading" and "Ready". - "transactionId": "str" # A unique identifier for the state of the ledger. If - returned as part of a LedgerEntry, it indicates the state from which the entry - was read. Required. + "modules": {} + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(bundle, (IOBase, bytes)): + _content = bundle + else: + _json = bundle + + _request = build_confidential_ledger_create_user_defined_endpoint_request( + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + 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 + + @distributed_trace + def get_runtime_options(self, **kwargs: Any) -> JSON: + """Runtime options for user defined endpoints. + + It returns the runtime options. + + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_receipt_request( - transaction_id=transaction_id, + _request = build_confidential_ledger_get_runtime_options_request( api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1042,18 +2781,91 @@ def get_receipt(self, transaction_id: str, **kwargs: Any) -> JSON: deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @overload + def update_runtime_options( + self, js_runtime_options: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> JSON: + """Runtime options for user defined endpoints. + + Updates the runtime options. + + :param js_runtime_options: JS runtime options. Required. + :type js_runtime_options: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + js_runtime_options = { + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool + } + + # response body for status code(s): 200 + response == { + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool + } + """ + + @overload + def update_runtime_options( + self, js_runtime_options: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> JSON: + """Runtime options for user defined endpoints. + + Updates the runtime options. + + :param js_runtime_options: JS runtime options. Required. + :type js_runtime_options: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python - return cast(JSON, deserialized) + # response body for status code(s): 200 + response == { + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool + } + """ @distributed_trace - def get_transaction_status(self, transaction_id: str, **kwargs: Any) -> JSON: - """Gets the status of an entry identified by a transaction id. + def update_runtime_options(self, js_runtime_options: Union[JSON, IO[bytes]], **kwargs: Any) -> JSON: + """Runtime options for user defined endpoints. - Gets the status of an entry identified by a transaction id. + Updates the runtime options. - :param transaction_id: Identifies a write transaction. Required. - :type transaction_id: str + :param js_runtime_options: JS runtime options. Is either a JSON type or a IO[bytes] type. + Required. + :type js_runtime_options: JSON or IO[bytes] :return: JSON object :rtype: JSON :raises ~azure.core.exceptions.HttpResponseError: @@ -1061,38 +2873,64 @@ def get_transaction_status(self, transaction_id: str, **kwargs: Any) -> JSON: Example: .. code-block:: python + # JSON input template you can fill out and use as your body input. + js_runtime_options = { + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool + } + # response body for status code(s): 200 response == { - "state": "str", # Represents the state of the transaction. Required. Known - values are: "Committed" and "Pending". - "transactionId": "str" # A unique identifier for the state of the ledger. If - returned as part of a LedgerEntry, it indicates the state from which the entry - was read. Required. + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_transaction_status_request( - transaction_id=transaction_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(js_runtime_options, (IOBase, bytes)): + _content = js_runtime_options + else: + _json = js_runtime_options + + _request = build_confidential_ledger_update_runtime_options_request( + content_type=content_type, api_version=self._config.api_version, + json=_json, + content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1107,18 +2945,18 @@ def get_transaction_status(self, transaction_id: str, **kwargs: Any) -> JSON: deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore @distributed_trace - def get_current_ledger_entry(self, *, collection_id: Optional[str] = None, **kwargs: Any) -> JSON: - """Gets the current value available in the ledger. + def get_user_defined_endpoints_module(self, *, module: str, **kwargs: Any) -> JSON: + """Module for user defined endpoints. - A collection id may optionally be specified. + It gets the module for the user defined endpoint. - :keyword collection_id: The collection id. Default value is None. - :paramtype collection_id: str + :keyword module: module name of the user defined endpoint. Required. + :paramtype module: str :return: JSON object :rtype: JSON :raises ~azure.core.exceptions.HttpResponseError: @@ -1128,36 +2966,37 @@ def get_current_ledger_entry(self, *, collection_id: Optional[str] = None, **kwa # response body for status code(s): 200 response == { - "collectionId": "str", # Optional. - "contents": "str", # Contents of the ledger entry. Required. - "transactionId": "str" # Optional. A unique identifier for the state of the - ledger. If returned as part of a LedgerEntry, it indicates the state from which - the entry was read. + "module": "str", + "name": "str" } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_current_ledger_entry_request( - collection_id=collection_id, + _request = build_confidential_ledger_get_user_defined_endpoints_module_request( + module=module, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1172,102 +3011,181 @@ def get_current_ledger_entry(self, *, collection_id: Optional[str] = None, **kwa deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore @distributed_trace - def delete_user(self, user_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements - """Deletes a user from the Confidential Ledger. + def get_user_defined_role(self, *, role_name: str, **kwargs: Any) -> List[JSON]: + """Gets role actions for user defined roles. - Deletes a user from the Confidential Ledger. + user defined roles allow users to define and manage app specific AuthZ policy. - :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. - :type user_id: str - :return: None - :rtype: None + :keyword role_name: user defined role name. Required. + :paramtype role_name: str + :return: list of JSON object + :rtype: list[JSON] :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == [ + { + "roleActions": [ + "str" + ], + "roleName": "str" + } + ] """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[None] + cls: ClsType[List[JSON]] = kwargs.pop("cls", None) - request = build_delete_user_request( - user_id=user_id, + _request = build_confidential_ledger_get_user_defined_role_request( + role_name=role_name, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response - if response.status_code not in [204]: + if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) + if response.content: + deserialized = response.json() + else: + deserialized = None + if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, cast(List[JSON], deserialized), {}) # type: ignore - @distributed_trace - def get_user(self, user_id: str, **kwargs: Any) -> JSON: - """Gets a user. + return cast(List[JSON], deserialized) # type: ignore - Gets a user. + @overload + def create_user_defined_role( + self, roles: List[JSON], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Creates new roles and their actions. - :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. - :type user_id: str - :return: JSON object - :rtype: JSON + User defined roles allow users to define and manage app specific AuthZ policy. + + :param roles: user defined role. Required. + :type roles: list[JSON] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: Example: .. code-block:: python - # response body for status code(s): 200 - response == { - "assignedRole": "str", # Represents an assignable role. Required. Known - values are: "Administrator", "Contributor", and "Reader". - "userId": "str" # Optional. Identifier for the user. This must either be an - AAD object id or a certificate fingerprint. - } + # JSON input template you can fill out and use as your body input. + roles = [ + { + "roleActions": [ + "str" + ], + "roleName": "str" + } + ] + """ + + @overload + def create_user_defined_role( + self, roles: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Creates new roles and their actions. + + User defined roles allow users to define and manage app specific AuthZ policy. + + :param roles: user defined role. Required. + :type roles: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create_user_defined_role( # pylint: disable=inconsistent-return-statements + self, roles: Union[List[JSON], IO[bytes]], **kwargs: Any + ) -> None: + """Creates new roles and their actions. + + User defined roles allow users to define and manage app specific AuthZ policy. + + :param roles: user defined role. Is either a [JSON] type or a IO[bytes] type. Required. + :type roles: list[JSON] or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) - _headers = kwargs.pop("headers", {}) or {} + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_get_user_request( - user_id=user_id, + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(roles, (IOBase, bytes)): + _content = roles + else: + _json = roles + + _request = build_confidential_ledger_create_user_defined_role_request( + content_type=content_type, api_version=self._config.api_version, + json=_json, + content=_content, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1276,134 +3194,98 @@ def get_user(self, user_id: str, **kwargs: Any) -> JSON: map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - if response.content: - deserialized = response.json() - else: - deserialized = None - if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) - - return cast(JSON, deserialized) + return cls(pipeline_response, None, {}) # type: ignore @overload - def create_or_update_user( - self, user_id: str, user_details: JSON, *, content_type: str = "application/merge-patch+json", **kwargs: Any - ) -> JSON: - """Adds a user or updates a user's fields. + def update_user_defined_role( + self, roles: List[JSON], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Patch replaces the allowed action on existing roles,if the desire is to remove an existing + action, the role must be deleted and recreated. - A JSON merge patch is applied for existing users. + User defined roles allow users to define and manage app specific AuthZ policy. - :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. - :type user_id: str - :param user_details: Details about a Confidential Ledger user. Required. - :type user_details: JSON + :param roles: user defined role. Required. + :type roles: list[JSON] :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is "application/merge-patch+json". + Default value is "application/json". :paramtype content_type: str - :return: JSON object - :rtype: JSON + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: Example: .. code-block:: python # JSON input template you can fill out and use as your body input. - user_details = { - "assignedRole": "str", # Represents an assignable role. Required. Known - values are: "Administrator", "Contributor", and "Reader". - "userId": "str" # Optional. Identifier for the user. This must either be an - AAD object id or a certificate fingerprint. - } - - # response body for status code(s): 200 - response == { - "assignedRole": "str", # Represents an assignable role. Required. Known - values are: "Administrator", "Contributor", and "Reader". - "userId": "str" # Optional. Identifier for the user. This must either be an - AAD object id or a certificate fingerprint. - } + roles = [ + { + "roleActions": [ + "str" + ], + "roleName": "str" + } + ] """ @overload - def create_or_update_user( - self, user_id: str, user_details: IO, *, content_type: str = "application/merge-patch+json", **kwargs: Any - ) -> JSON: - """Adds a user or updates a user's fields. + def update_user_defined_role( + self, roles: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Patch replaces the allowed action on existing roles,if the desire is to remove an existing + action, the role must be deleted and recreated. - A JSON merge patch is applied for existing users. + User defined roles allow users to define and manage app specific AuthZ policy. - :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. - :type user_id: str - :param user_details: Details about a Confidential Ledger user. Required. - :type user_details: IO + :param roles: user defined role. Required. + :type roles: IO[bytes] :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is "application/merge-patch+json". + Default value is "application/json". :paramtype content_type: str - :return: JSON object - :rtype: JSON + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "assignedRole": "str", # Represents an assignable role. Required. Known - values are: "Administrator", "Contributor", and "Reader". - "userId": "str" # Optional. Identifier for the user. This must either be an - AAD object id or a certificate fingerprint. - } """ @distributed_trace - def create_or_update_user(self, user_id: str, user_details: Union[JSON, IO], **kwargs: Any) -> JSON: - """Adds a user or updates a user's fields. + def update_user_defined_role( # pylint: disable=inconsistent-return-statements + self, roles: Union[List[JSON], IO[bytes]], **kwargs: Any + ) -> None: + """Patch replaces the allowed action on existing roles,if the desire is to remove an existing + action, the role must be deleted and recreated. - A JSON merge patch is applied for existing users. + User defined roles allow users to define and manage app specific AuthZ policy. - :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. - :type user_id: str - :param user_details: Details about a Confidential Ledger user. Is either a model type or a IO - type. Required. - :type user_details: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: - 'application/merge-patch+json'. Default value is None. - :paramtype content_type: str - :return: JSON object - :rtype: JSON + :param roles: user defined role. Is either a [JSON] type or a IO[bytes] type. Required. + :type roles: list[JSON] or IO[bytes] + :return: None + :rtype: None :raises ~azure.core.exceptions.HttpResponseError: - - Example: - .. code-block:: python - - # response body for status code(s): 200 - response == { - "assignedRole": "str", # Represents an assignable role. Required. Known - values are: "Administrator", "Contributor", and "Reader". - "userId": "str" # Optional. Identifier for the user. This must either be an - AAD object id or a certificate fingerprint. - } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) - content_type = content_type or "application/merge-patch+json" + content_type = content_type or "application/json" _json = None _content = None - if isinstance(user_details, (IO, bytes)): - _content = user_details + if isinstance(roles, (IOBase, bytes)): + _content = roles else: - _json = user_details + _json = roles - request = build_create_or_update_user_request( - user_id=user_id, + _request = build_confidential_ledger_update_user_defined_role_request( content_type=content_type, api_version=self._config.api_version, json=_json, @@ -1412,14 +3294,13 @@ def create_or_update_user(self, user_id: str, user_details: Union[JSON, IO], **k params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1428,12 +3309,57 @@ def create_or_update_user(self, user_id: str, user_details: Union[JSON, IO], **k map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response) - if response.content: - deserialized = response.json() - else: - deserialized = None - if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, None, {}) # type: ignore + + @distributed_trace + def delete_user_defined_role( # pylint: disable=inconsistent-return-statements + self, *, role_name: str, **kwargs: Any + ) -> None: + """Deletes user defined roles. + + A user defined role allows the users to create and manage their own role actions using the API. + + :keyword role_name: user defined role name. Required. + :paramtype role_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) - return cast(JSON, deserialized) + _request = build_confidential_ledger_delete_user_defined_role_request( + role_name=role_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + 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 diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/_patch.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/_patch.py index 25faf541c186..5ae0cf278c80 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/_patch.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_operations/_patch.py @@ -2,6 +2,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ + + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize @@ -66,7 +68,6 @@ def _evaluate_response(self, response: JSON) -> None: def _give_up_not_found_error(self, exception: ResourceNotFoundError) -> bool: if exception.error is not None and exception.error.code == "InvalidTransactionId": return True - return False def status(self) -> str: @@ -78,7 +79,6 @@ def finished(self) -> bool: def resource(self): if self._deserialization_callback: return self._deserialization_callback(self._latest_response) - return self._latest_response @@ -105,16 +105,13 @@ def run(self) -> None: except ResourceNotFoundError as not_found_exception: # We'll allow some instances of resource not found to account for replication # delay if session stickiness is lost. + self._not_found_count += 1 - not_retryable = ( - not self._retry_not_found or - self._give_up_not_found_error(not_found_exception) - ) + not_retryable = not self._retry_not_found or self._give_up_not_found_error(not_found_exception) - if not_retryable or self._not_found_count >=3: + if not_retryable or self._not_found_count >= 3: raise - if not self.finished(): time.sleep(self._polling_interval_s) except Exception: @@ -155,7 +152,6 @@ def operation() -> JSON: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling - return LROPoller(self._client, initial_response, lambda x: x, polling_method) def begin_get_receipt(self, transaction_id: str, **kwargs: Any) -> LROPoller[JSON]: @@ -184,7 +180,6 @@ def operation() -> JSON: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling - return LROPoller(self._client, initial_response, lambda x: x, polling_method) def begin_create_ledger_entry( @@ -209,11 +204,13 @@ def begin_create_ledger_entry( """ # Pop arguments that are unexpected in the pipeline. + polling = kwargs.pop("polling", True) # type: Union[bool, PollingMethod] lro_delay = kwargs.pop("polling_interval", 0.5) # Pop the custom deserializer, if any, so we know the format of the response and can # retrieve the transactionId. Serialize the response later. + cls = kwargs.pop("cls", None) # type: ClsType[JSON] kwargs["cls"] = lambda pipeline_response, json_response, headers: ( pipeline_response, @@ -230,6 +227,7 @@ def begin_create_ledger_entry( # Delete the cls because it should only apply to the create_ledger_entry response, not the # wait_for_commit call. + del kwargs["cls"] transaction_id = post_result["transactionId"] # type: ignore @@ -243,7 +241,6 @@ def begin_create_ledger_entry( ) else: kwargs["_create_ledger_entry_response"] = post_result - return self.begin_wait_for_commit(transaction_id, **kwargs) def begin_wait_for_commit( @@ -266,8 +263,11 @@ def begin_wait_for_commit( # If this poller was called from begin_create_ledger_entry, we should return the # create_ledger_entry response, not the transaction status. + post_result = kwargs.pop("_create_ledger_entry_response", None) - deserialization_callback = lambda x: x if post_result is None else post_result # pylint: disable=unnecessary-lambda-assignment + deserialization_callback = lambda x: ( + x if post_result is None else post_result + ) # pylint: disable=unnecessary-lambda-assignment def operation() -> JSON: return super(ConfidentialLedgerClientOperationsMixin, self).get_transaction_status( @@ -279,18 +279,16 @@ def operation() -> JSON: except ResourceNotFoundError: if polling is False or polling is None: raise - # This method allows for temporary resource not found errors, which may occur if session # stickiness is lost and there is replication lag. - initial_response = {} + initial_response = {} if polling is True: polling_method = cast(PollingMethod, StatePollingMethod(operation, "Committed", lro_delay, True)) elif polling is False: polling_method = cast(PollingMethod, NoPolling()) else: polling_method = polling - return LROPoller(self._client, initial_response, deserialization_callback, polling_method) def create_ledger_entry( diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_patch.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_patch.py index 399b716b05f7..15297e7a4128 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_patch.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_patch.py @@ -2,6 +2,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ + + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize @@ -80,6 +82,7 @@ def __init__( ) -> None: # Remove some kwargs first so that there aren't unexpected kwargs passed to # get_ledger_identity. + if isinstance(credential, ConfidentialLedgerCertificateCredential): auth_policy = None else: @@ -88,30 +91,31 @@ def __init__( "authentication_policy", policies.BearerTokenCredentialPolicy(credential, *credential_scopes, **kwargs), ) - if os.path.isfile(ledger_certificate_path) is False: # We'll need to fetch the TLS certificate. + identity_service_client = ConfidentialLedgerCertificateClient(**kwargs) # Ledger URIs are of the form https://.confidential-ledger.azure.com. + ledger_id = endpoint.replace("https://", "").split(".")[0] ledger_cert = identity_service_client.get_ledger_identity(ledger_id, **kwargs) with open(ledger_certificate_path, "w", encoding="utf-8") as outfile: outfile.write(ledger_cert["ledgerTlsCertificate"]) - # For ConfidentialLedgerCertificateCredential, pass the path to the certificate down to the # PipelineCLient. + if isinstance(credential, ConfidentialLedgerCertificateCredential): kwargs["connection_cert"] = kwargs.get("connection_cert", credential.certificate_path) - # The auto-generated client has authentication disabled so we can customize authentication. # If the credential is the typical TokenCredential, then construct the authentication policy # the normal way. + else: kwargs["authentication_policy"] = auth_policy - # Customize the underlying client to use a self-signed TLS certificate. + kwargs["connection_verify"] = kwargs.get("connection_verify", ledger_certificate_path) super().__init__(endpoint, **kwargs) diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_serialization.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_serialization.py index 648f84cc4e65..b24ab2885450 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_serialization.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_serialization.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -24,7 +25,7 @@ # # -------------------------------------------------------------------------- -# pylint: skip-file +# pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode import calendar @@ -37,23 +38,37 @@ import re import sys import codecs +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + TypeVar, + MutableMapping, + Type, + List, +) try: from urllib import quote # type: ignore except ImportError: - from urllib.parse import quote # type: ignore + from urllib.parse import quote import xml.etree.ElementTree as ET -import isodate +import isodate # type: ignore -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping +ModelType = TypeVar("ModelType", bound="Model") +JSON = MutableMapping[str, Any] class RawDeserializer: @@ -65,8 +80,7 @@ class RawDeserializer: CONTEXT_NAME = "deserialized_data" @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: """Decode data according to content-type. Accept a stream of data as well, but will be load at once in memory for now. @@ -76,6 +90,8 @@ def deserialize_from_text(cls, data, content_type=None): :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 @@ -97,7 +113,7 @@ def deserialize_from_text(cls, data, content_type=None): 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: @@ -109,7 +125,7 @@ def deserialize_from_text(cls, data, content_type=None): pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # It might be because the server has an issue, and returned JSON with # content-type XML.... # So let's try a JSON load, and if it's still broken @@ -128,17 +144,23 @@ def _json_attemp(data): # The function hack is because Py2.7 messes up with exception # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") + 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 - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: """Deserialize from HTTP response. 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 @@ -156,13 +178,6 @@ def deserialize_from_http_generics(cls, body_bytes, headers): return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - _LOGGER = logging.getLogger(__name__) try: @@ -175,20 +190,35 @@ class UTC(datetime.tzinfo): """Time Zone info for handling UTC""" def utcoffset(self, dt): - """UTF offset for UTC is 0.""" + """UTF offset for UTC is 0. + + :param datetime.datetime dt: The datetime + :returns: The offset + :rtype: datetime.timedelta + """ return datetime.timedelta(0) def tzname(self, dt): - """Timestamp representation.""" + """Timestamp representation. + + :param datetime.datetime dt: The datetime + :returns: The timestamp representation + :rtype: str + """ return "Z" def dst(self, dt): - """No daylight saving for UTC.""" + """No daylight saving for UTC. + + :param datetime.datetime dt: The datetime + :returns: The daylight saving time + :rtype: datetime.timedelta + """ return datetime.timedelta(hours=1) try: - from datetime import timezone as _FixedOffset + from datetime import timezone as _FixedOffset # type: ignore except ImportError: # Python 2.7 class _FixedOffset(datetime.tzinfo): # type: ignore @@ -197,7 +227,7 @@ class _FixedOffset(datetime.tzinfo): # type: ignore :param datetime.timedelta offset: offset in timedelta format """ - def __init__(self, offset): + def __init__(self, offset) -> None: self.__offset = offset def utcoffset(self, dt): @@ -219,31 +249,33 @@ def __getinitargs__(self): try: from datetime import timezone - TZ_UTC = timezone.utc # type: ignore + TZ_UTC = timezone.utc except ImportError: TZ_UTC = UTC() # type: ignore _FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[Dict[str, Any]] = {} + 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): @@ -290,43 +329,57 @@ def __init__(self, **kwargs): else: setattr(self, k, kwargs[k]) - def __eq__(self, other): - """Compare objects by comparing all attributes.""" + def __eq__(self, other: Any) -> bool: + """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): - """Compare objects by comparing all attributes.""" + def __ne__(self, other: Any) -> bool: + """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): + def __str__(self) -> str: return str(self.__dict__) @classmethod - def enable_additional_properties_sending(cls): + def enable_additional_properties_sending(cls) -> None: cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} @classmethod - def is_xml_model(cls): + def is_xml_model(cls) -> bool: try: - cls._xml_map + cls._xml_map # type: ignore except AttributeError: return False return True @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 + xml_map = cls._xml_map # type: ignore except AttributeError: xml_map = {} return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - def serialize(self, keep_readonly=False, **kwargs): - """Return the JSON that would be sent to azure from this model. + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -337,10 +390,17 @@ def serialize(self, keep_readonly=False, **kwargs): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) - def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer, **kwargs): - """Return a dict that can be JSONify using json.dump. + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. Advanced usage might optionally use a callback as parameter: @@ -366,12 +426,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) + 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): @@ -381,25 +444,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, data, content_type=None): + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: """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 + :rtype: ModelType """ deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod - def from_dict(cls, data, key_extractors=None, content_type=None): + def from_dict( + cls: Type[ModelType], + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> ModelType: """Parse a dict using given key extractor return a model. By default consider key @@ -407,13 +476,15 @@ def from_dict(cls, data, key_extractors=None, content_type=None): 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 + :rtype: ModelType """ deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( - [ + deserializer.key_extractors = ( # type: ignore + [ # type: ignore attribute_key_case_insensitive_extractor, rest_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, @@ -421,7 +492,7 @@ def from_dict(cls, data, key_extractors=None, content_type=None): if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -429,21 +500,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: @@ -453,7 +528,7 @@ def _classify(cls, response, objects): return cls flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) try: - return objects[flatten_mapping_type[subtype_value]] + return objects[flatten_mapping_type[subtype_value]] # type: ignore except KeyError: _LOGGER.warning( "Subtype value %s has no mapping, use base class %s.", @@ -482,11 +557,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"} @@ -521,7 +598,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -537,17 +614,20 @@ def __init__(self, classes=None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} 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. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -573,12 +653,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"] == "": @@ -605,62 +687,63 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if xml_desc.get("attr", False): if xml_ns: ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore continue if xml_desc.get("text", False): - serialized.text = new_attr + serialized.text = new_attr # type: ignore continue if isinstance(new_attr, list): - serialized.extend(new_attr) + 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 new_attr.tag = "}".join([splitted_tag[0], xml_name]) else: new_attr.tag = xml_name - serialized.append(new_attr) + serialized.append(new_attr) # type: ignore else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} _new_attr = new_attr _serialized = serialized - for k in keys: + for k in keys: # type: ignore if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore _serialized = _serialized[k] - except ValueError: - continue + except ValueError as err: + if isinstance(err, SerializationError): + raise except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized + raise SerializationError(msg) from err + 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 + :returns: The serialized request body """ # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) try: is_xml_model_serialization = kwargs["is_xml"] except KeyError: @@ -675,7 +758,7 @@ def body(self, data, data_type, **kwargs): # We're not able to deal with additional properties for now. deserializer.additional_properties_detection = False if is_xml_model_serialization: - deserializer.key_extractors = [ + deserializer.key_extractors = [ # type: ignore attribute_key_case_insensitive_extractor, ] else: @@ -684,18 +767,20 @@ 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_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from err return self._serialize(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 + :returns: The serialized URL path :raises: TypeError if serialization fails. :raises: ValueError if data is None """ @@ -706,30 +791,30 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) + 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. - :rtype: str + :rtype: str, list :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 if data_type.startswith("["): internal_data_type = data_type[1:-1] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -739,19 +824,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 + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -760,30 +846,31 @@ 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. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") try: + if data is CoreNull: + return None 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 @@ -798,12 +885,11 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) + raise SerializationError(msg.format(data, data_type)) from err + 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 @@ -819,23 +905,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 @@ -843,14 +932,13 @@ def serialize_unicode(cls, data): pass try: - if isinstance(data, unicode): + if isinstance(data, unicode): # type: ignore # Don't change it, JSON and XML ElementTree are totally able # to serialize correctly u'' strings 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. @@ -860,13 +948,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'. + Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -878,9 +966,14 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): for d in data: try: serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized.append(None) + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + if div: serialized = ["" if s is None else str(s) for s in serialized] serialized = div.join(serialized) @@ -916,16 +1009,17 @@ 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 = {} for key, value in attr.items(): try: serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized[self.serialize_unicode(key)] = None if "xml" in serialization_ctxt: @@ -940,7 +1034,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 @@ -948,6 +1042,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 @@ -958,7 +1053,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) if obj_type is _long_type: return self.serialize_long(attr) - if obj_type is unicode_str: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -972,7 +1067,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: @@ -1001,58 +1096,63 @@ def serialize_enum(attr, enum_obj=None): except AttributeError: result = attr try: - enum_obj(result) + enum_obj(result) # type: ignore return result - except ValueError: - for enum_value in enum_obj: + 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) @@ -1060,11 +1160,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) @@ -1074,30 +1175,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. + :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], @@ -1110,12 +1213,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. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1135,19 +1239,20 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + 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 + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1155,16 +1260,17 @@ 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 while "." in key: - dict_keys = _FLATTEN.split(key) + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1173,14 +1279,15 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) 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 @@ -1194,7 +1301,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1202,17 +1308,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) @@ -1245,11 +1363,11 @@ def _extract_name_from_internal_type(internal_type): xml_name = internal_type_xml_map.get("name", internal_type.__name__) xml_ns = internal_type_xml_map.get("ns", None) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) 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 @@ -1269,7 +1387,7 @@ def xml_key_extractor(attr, attr_desc, data): # Integrate namespace if necessary xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) # If it's an attribute, that's simple if xml_desc.get("attr", False): @@ -1301,22 +1419,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( # pylint: disable=line-too-long + 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: @@ -1324,7 +1441,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. @@ -1333,9 +1450,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=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1355,7 +1472,7 @@ def __init__(self, classes=None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1373,11 +1490,12 @@ def __call__(self, target_obj, response_data, content_type=None): :param str content_type: Swagger "produces" if available. :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 @@ -1386,12 +1504,13 @@ def _deserialize(self, target_obj, data): :param object data: Object to deserialize. :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) @@ -1408,15 +1527,15 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + 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 + 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"... @@ -1444,11 +1563,10 @@ def _deserialize(self, target_obj, data): value = self.deserialize_data(raw_value, attr_desc["type"]) d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + 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: @@ -1474,22 +1592,24 @@ def _classify_target(self, target, data): Once classification has been determined, initialize object. :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :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 - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + 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__ + return target, target.__class__.__name__ # type: ignore def failsafe_deserialize(self, target_obj, data, content_type=None): """Ignores any errors encountered in deserialization, @@ -1499,13 +1619,15 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): a deserialization error. :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :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: - _LOGGER.warning( + except: # pylint: disable=bare-except + _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) return None @@ -1522,10 +1644,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", {}) @@ -1542,31 +1666,42 @@ def _unpack_content(raw_data, content_type=None): if hasattr(raw_data, "_content_consumed"): return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore return raw_data 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) - raise DeserializationError(msg + str(err)) + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1575,15 +1710,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. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1597,7 +1733,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) @@ -1616,15 +1756,15 @@ def deserialize_data(self, data, data_type): except (ValueError, TypeError, AttributeError) as err: msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) + raise DeserializationError(msg) from err + 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: @@ -1641,6 +1781,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): @@ -1651,11 +1792,12 @@ 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. """ @@ -1664,7 +1806,7 @@ def deserialize_object(self, attr, **kwargs): if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1690,11 +1832,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 @@ -1702,6 +1843,7 @@ 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. """ @@ -1713,24 +1855,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, basestring): + 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): @@ -1738,6 +1879,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, @@ -1747,12 +1889,11 @@ def deserialize_unicode(data): # Consider this is real string try: - if isinstance(data, unicode): + if isinstance(data, unicode): # type: ignore return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1764,6 +1905,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: @@ -1772,12 +1914,11 @@ def deserialize_enum(data, enum_obj): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 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: @@ -1793,25 +1934,27 @@ 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. """ if isinstance(attr, ET.Element): attr = attr.text - return bytearray(b64decode(attr)) + return bytearray(b64decode(attr)) # type: ignore @staticmethod 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. """ if isinstance(attr, ET.Element): attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore encoded = attr.replace("-", "+").replace("_", "/") return b64decode(encoded) @@ -1820,34 +1963,37 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal + :return: Deserialized decimal :raises: DeserializationError if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod 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. """ if isinstance(attr, ET.Element): attr = attr.text - return _long_type(attr) + return _long_type(attr) # type: ignore @staticmethod 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. """ @@ -1857,36 +2003,37 @@ def deserialize_duration(attr): duration = isodate.parse_duration(attr) except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration + raise DeserializationError(msg) from err + 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. """ if isinstance(attr, ET.Element): attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) @staticmethod 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. """ if isinstance(attr, ET.Element): attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) return isodate.parse_time(attr) @@ -1895,13 +2042,14 @@ 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. """ if isinstance(attr, ET.Element): attr = attr.text try: - parsed_date = email.utils.parsedate_tz(attr) + 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)) ) @@ -1909,22 +2057,22 @@ def deserialize_rfc(attr): date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + 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. """ if isinstance(attr, ET.Element): attr = attr.text try: - attr = attr.upper() + attr = attr.upper() # type: ignore match = Deserializer.valid_date.match(attr) if not match: raise ValueError("Invalid datetime string: " + attr) @@ -1946,9 +2094,8 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_unix(attr): @@ -1956,15 +2103,16 @@ 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 """ if isinstance(attr, ET.Element): - attr = int(attr.text) + attr = int(attr.text) # type: ignore try: + attr = int(attr) date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_vendor.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_vendor.py index 3fc6bd9d75ae..a724c1f5be1a 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_vendor.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/_vendor.py @@ -11,24 +11,12 @@ from ._configuration import ConfidentialLedgerClientConfiguration if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core import PipelineClient from ._serialization import Deserializer, Serializer -def _format_url_section(template, **kwargs): # pylint: disable=inconsistent-return-statements - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) - - -class MixinABC(ABC): +class ConfidentialLedgerClientMixinABC(ABC): """DO NOT use this class. It is for internal typing use only.""" _client: "PipelineClient" diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/__init__.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/__init__.py index 8c4cc88b81a3..7e10bc0a690e 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/__init__.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/__init__.py @@ -5,17 +5,25 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._client import ConfidentialLedgerClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ConfidentialLedgerClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ["ConfidentialLedgerClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__ = [ + "ConfidentialLedgerClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_client.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_client.py index c040590052e1..413eb93ae0eb 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_client.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_client.py @@ -7,46 +7,61 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING +from typing import Any, Awaitable +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 ._configuration import ConfidentialLedgerClientConfiguration from ._operations import ConfidentialLedgerClientOperationsMixin -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - -class ConfidentialLedgerClient( - ConfidentialLedgerClientOperationsMixin -): # pylint: disable=client-accepts-api-version-keyword +class ConfidentialLedgerClient(ConfidentialLedgerClientOperationsMixin): """The ConfidentialLedgerClient writes and retrieves ledger entries against the Confidential Ledger service. - :param ledger_endpoint: The Confidential Ledger URL, for example + :param endpoint: The Confidential Ledger URL, for example https://contoso.confidentialledger.azure.com. Required. - :type ledger_endpoint: str - :keyword api_version: Api Version. Default value is "2022-05-13". Note that overriding this - default value may result in unsupported behavior. + :type endpoint: str + :keyword api_version: Api Version. Default value is "2024-08-22-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, ledger_endpoint: str, **kwargs: Any + self, endpoint: str, **kwargs: Any ) -> None: - _endpoint = "{ledgerEndpoint}" - self._config = ConfidentialLedgerClientConfiguration(ledger_endpoint=ledger_endpoint, **kwargs) - self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) + _endpoint = "{endpoint}" + self._config = ConfidentialLedgerClientConfiguration(endpoint=endpoint, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -66,20 +81,18 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHt request_copy = deepcopy(request) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "ConfidentialLedgerClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_configuration.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_configuration.py index 6f548afbf6b1..760c6d33def7 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_configuration.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_configuration.py @@ -8,36 +8,35 @@ from typing import Any -from azure.core.configuration import Configuration from azure.core.pipeline import policies from .._version import VERSION -class ConfidentialLedgerClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes +class ConfidentialLedgerClientConfiguration: # pylint: disable=too-many-instance-attributes """Configuration for ConfidentialLedgerClient. Note that all parameters used to create this instance are saved as instance attributes. - :param ledger_endpoint: The Confidential Ledger URL, for example + :param endpoint: The Confidential Ledger URL, for example https://contoso.confidentialledger.azure.com. Required. - :type ledger_endpoint: str - :keyword api_version: Api Version. Default value is "2022-05-13". Note that overriding this - default value may result in unsupported behavior. + :type endpoint: str + :keyword api_version: Api Version. Default value is "2024-08-22-preview". Note that overriding + this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, ledger_endpoint: str, **kwargs: Any) -> None: - super(ConfidentialLedgerClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2022-05-13") # type: str + def __init__(self, endpoint: str, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2024-08-22-preview") - if ledger_endpoint is None: - raise ValueError("Parameter 'ledger_endpoint' must not be None.") + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") - self.ledger_endpoint = ledger_endpoint + self.endpoint = endpoint self.api_version = api_version kwargs.setdefault("sdk_moniker", "confidentialledger/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -46,7 +45,7 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) 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") diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/__init__.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/__init__.py index a07d13d30393..9e343eef1ebf 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/__init__.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/__init__.py @@ -5,15 +5,21 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import ConfidentialLedgerClientOperationsMixin +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ConfidentialLedgerClientOperationsMixin # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ConfidentialLedgerClientOperationsMixin", ] -__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/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/_operations.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/_operations.py index 1f9f30e58a83..08296e1038ea 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/_operations.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/_operations.py @@ -6,9 +6,10 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from io import IOBase import sys -from typing import Any, AsyncIterable, Callable, Dict, IO, Optional, TypeVar, Union, cast, overload -from urllib.parse import parse_qs, urljoin, urlparse +from typing import Any, AsyncIterable, Callable, Dict, IO, List, Optional, TypeVar, Union, cast, overload +import urllib.parse from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ( @@ -16,41 +17,59 @@ HttpResponseError, ResourceExistsError, ResourceNotFoundError, + ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, AsyncHttpResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator import distributed_trace from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict from ..._operations._operations import ( - build_create_ledger_entry_request, - build_create_or_update_user_request, - build_delete_user_request, - build_get_constitution_request, - build_get_current_ledger_entry_request, - build_get_enclave_quotes_request, - build_get_ledger_entry_request, - build_get_receipt_request, - build_get_transaction_status_request, - build_get_user_request, - build_list_collections_request, - build_list_consortium_members_request, - build_list_ledger_entries_request, + build_confidential_ledger_create_ledger_entry_request, + build_confidential_ledger_create_or_update_ledger_user_request, + build_confidential_ledger_create_or_update_user_request, + build_confidential_ledger_create_user_defined_endpoint_request, + build_confidential_ledger_create_user_defined_role_request, + build_confidential_ledger_delete_ledger_user_request, + build_confidential_ledger_delete_user_defined_role_request, + build_confidential_ledger_delete_user_request, + build_confidential_ledger_get_constitution_request, + build_confidential_ledger_get_current_ledger_entry_request, + build_confidential_ledger_get_enclave_quotes_request, + build_confidential_ledger_get_ledger_entry_request, + build_confidential_ledger_get_ledger_user_request, + build_confidential_ledger_get_receipt_request, + build_confidential_ledger_get_runtime_options_request, + build_confidential_ledger_get_transaction_status_request, + build_confidential_ledger_get_user_defined_endpoint_request, + build_confidential_ledger_get_user_defined_endpoints_module_request, + build_confidential_ledger_get_user_defined_role_request, + build_confidential_ledger_get_user_request, + build_confidential_ledger_list_collections_request, + build_confidential_ledger_list_consortium_members_request, + build_confidential_ledger_list_ledger_entries_request, + build_confidential_ledger_list_ledger_users_request, + build_confidential_ledger_list_users_request, + build_confidential_ledger_update_runtime_options_request, + build_confidential_ledger_update_user_defined_role_request, ) -from .._vendor import MixinABC +from .._vendor import ConfidentialLedgerClientMixinABC if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ConfidentialLedgerClientOperationsMixin(MixinABC): +class ConfidentialLedgerClientOperationsMixin( # pylint: disable=too-many-public-methods + ConfidentialLedgerClientMixinABC +): + @distributed_trace_async async def get_constitution(self, **kwargs: Any) -> JSON: """Gets the constitution used for governance. @@ -66,32 +85,36 @@ async def get_constitution(self, **kwargs: Any) -> JSON: # response body for status code(s): 200 response == { - "digest": "str", # SHA256 digest of the constitution script. Required. - "script": "str" # Contents of the constitution. Required. + "digest": "str", + "script": "str" } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_constitution_request( + _request = build_confidential_ledger_get_constitution_request( api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -106,9 +129,9 @@ async def get_constitution(self, **kwargs: Any) -> JSON: deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore @distributed_trace def list_consortium_members(self, **kwargs: Any) -> AsyncIterable[JSON]: @@ -125,61 +148,73 @@ def list_consortium_members(self, **kwargs: Any) -> AsyncIterable[JSON]: # response body for status code(s): 200 response == { - "certificate": "str", # PEM-encoded certificate associated with the member. - Required. - "id": "str" # Identifier assigned to the member. Required. + "certificate": "str", + "id": "str" } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: - request = build_list_consortium_members_request( + _request = build_confidential_ledger_list_consortium_members_request( api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version - _parsed_next_link = urlparse(next_link) - _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = deserialized["members"] if cls: - list_of_elem = cls(list_of_elem) - return deserialized.get("nextLink", None), AsyncList(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -207,43 +242,43 @@ async def get_enclave_quotes(self, **kwargs: Any) -> JSON: # response body for status code(s): 200 response == { - "currentNodeId": "str", # Id of the Confidential Ledger node responding to - the request. Required. + "currentNodeId": "str", "enclaveQuotes": { "str": { - "mrenclave": "str", # Optional. MRENCLAVE value of the code - running in the enclave. - "nodeId": "str", # ID assigned to this node. Required. - "quoteVersion": "str", # Version of the quote presented. - Required. - "raw": "str" # Raw SGX quote, parsable by tools like Open - Enclave's oeverify. Required. + "nodeId": "str", + "quoteVersion": "str", + "raw": "str", + "mrenclave": "str" } } } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_enclave_quotes_request( + _request = build_confidential_ledger_get_enclave_quotes_request( api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -258,9 +293,9 @@ async def get_enclave_quotes(self, **kwargs: Any) -> JSON: deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore @distributed_trace def list_collections(self, **kwargs: Any) -> AsyncIterable[JSON]: @@ -277,59 +312,72 @@ def list_collections(self, **kwargs: Any) -> AsyncIterable[JSON]: # response body for status code(s): 200 response == { - "collectionId": "str" # Required. + "collectionId": "str" } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: - request = build_list_collections_request( + _request = build_confidential_ledger_list_collections_request( api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version - _parsed_next_link = urlparse(next_link) - _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = deserialized["collections"] if cls: - list_of_elem = cls(list_of_elem) - return deserialized.get("nextLink", None), AsyncList(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -371,25 +419,28 @@ def list_ledger_entries( # response body for status code(s): 200 response == { - "collectionId": "str", # Optional. - "contents": "str", # Contents of the ledger entry. Required. - "transactionId": "str" # Optional. A unique identifier for the state of the - ledger. If returned as part of a LedgerEntry, it indicates the state from which - the entry was read. + "contents": "str", + "collectionId": "str", + "transactionId": "str" } """ _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) def prepare_request(next_link=None): if not next_link: - request = build_list_ledger_entries_request( + _request = build_confidential_ledger_list_ledger_entries_request( collection_id=collection_id, from_transaction_id=from_transaction_id, to_transaction_id=to_transaction_id, @@ -398,39 +449,47 @@ def prepare_request(next_link=None): params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) else: # make call to next link with the client's api-version - _parsed_next_link = urlparse(next_link) - _next_request_params = case_insensitive_dict(parse_qs(_parsed_next_link.query)) + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) _next_request_params["api-version"] = self._config.api_version - request = HttpRequest("GET", urljoin(next_link, _parsed_next_link.path), params=_next_request_params) + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True ), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - return request + return _request async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() list_of_elem = deserialized["entries"] if cls: - list_of_elem = cls(list_of_elem) - return deserialized.get("nextLink", None), AsyncList(list_of_elem) + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) async def get_next(next_link=None): - request = prepare_request(next_link) + _request = prepare_request(next_link) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -466,29 +525,32 @@ async def create_ledger_entry( # JSON input template you can fill out and use as your body input. entry = { - "collectionId": "str", # Optional. - "contents": "str", # Contents of the ledger entry. Required. - "transactionId": "str" # Optional. A unique identifier for the state of the - ledger. If returned as part of a LedgerEntry, it indicates the state from which - the entry was read. + "contents": "str", + "collectionId": "str", + "transactionId": "str" } # response body for status code(s): 200 response == { - "collectionId": "str" # Required. + "collectionId": "str" } """ @overload async def create_ledger_entry( - self, entry: IO, *, collection_id: Optional[str] = None, content_type: str = "application/json", **kwargs: Any + self, + entry: IO[bytes], + *, + collection_id: Optional[str] = None, + content_type: str = "application/json", + **kwargs: Any ) -> JSON: """Writes a ledger entry. A collection id may optionally be specified. :param entry: Ledger entry. Required. - :type entry: IO + :type entry: IO[bytes] :keyword collection_id: The collection id. Default value is None. :paramtype collection_id: str :keyword content_type: Body Parameter content-type. Content type parameter for binary body. @@ -503,25 +565,22 @@ async def create_ledger_entry( # response body for status code(s): 200 response == { - "collectionId": "str" # Required. + "collectionId": "str" } """ @distributed_trace_async async def create_ledger_entry( - self, entry: Union[JSON, IO], *, collection_id: Optional[str] = None, **kwargs: Any + self, entry: Union[JSON, IO[bytes]], *, collection_id: Optional[str] = None, **kwargs: Any ) -> JSON: """Writes a ledger entry. A collection id may optionally be specified. - :param entry: Ledger entry. Is either a model type or a IO type. Required. - :type entry: JSON or IO + :param entry: Ledger entry. Is either a JSON type or a IO[bytes] type. Required. + :type entry: JSON or IO[bytes] :keyword collection_id: The collection id. Default value is None. :paramtype collection_id: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str :return: JSON object :rtype: JSON :raises ~azure.core.exceptions.HttpResponseError: @@ -529,29 +588,41 @@ async def create_ledger_entry( Example: .. code-block:: python + # JSON input template you can fill out and use as your body input. + entry = { + "contents": "str", + "collectionId": "str", + "transactionId": "str" + } + # response body for status code(s): 200 response == { - "collectionId": "str" # Required. + "collectionId": "str" } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) content_type = content_type or "application/json" _json = None _content = None - if isinstance(entry, (IO, bytes)): + if isinstance(entry, (IOBase, bytes)): _content = entry else: _json = entry - request = build_create_ledger_entry_request( + _request = build_confidential_ledger_create_ledger_entry_request( collection_id=collection_id, content_type=content_type, api_version=self._config.api_version, @@ -561,14 +632,13 @@ async def create_ledger_entry( params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -588,9 +658,9 @@ async def create_ledger_entry( deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), response_headers) + return cls(pipeline_response, cast(JSON, deserialized), response_headers) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore @distributed_trace_async async def get_ledger_entry( @@ -616,27 +686,28 @@ async def get_ledger_entry( # response body for status code(s): 200 response == { + "state": "str", "entry": { - "collectionId": "str", # Optional. The ledger entry found as a - result of the query. This is only available if the query is in Ready state. - "contents": "str", # Contents of the ledger entry. Required. - "transactionId": "str" # Optional. A unique identifier for the state - of the ledger. If returned as part of a LedgerEntry, it indicates the state - from which the entry was read. - }, - "state": "str" # State of a ledger query. Required. Known values are: - "Loading" and "Ready". + "contents": "str", + "collectionId": "str", + "transactionId": "str" + } } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_ledger_entry_request( + _request = build_confidential_ledger_get_ledger_entry_request( transaction_id=transaction_id, collection_id=collection_id, api_version=self._config.api_version, @@ -644,14 +715,13 @@ async def get_ledger_entry( params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -666,9 +736,9 @@ async def get_ledger_entry( deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore @distributed_trace_async async def get_receipt(self, transaction_id: str, **kwargs: Any) -> JSON: @@ -687,57 +757,73 @@ async def get_receipt(self, transaction_id: str, **kwargs: Any) -> JSON: # response body for status code(s): 200 response == { + "state": "str", + "transactionId": "str", + "applicationClaims": [ + { + "kind": "str", + "digest": { + "protocol": "str", + "value": "str" + }, + "ledgerEntry": { + "protocol": "str", + "collectionId": "str", + "contents": "str", + "secretKey": "str" + } + } + ], "receipt": { - "cert": "str", # Optional. - "leaf": "str", # Optional. - "leafComponents": { - "claimsDigest": "str", # Optional. - "commitEvidence": "str", # Optional. - "writeSetDigest": "str" # Optional. - }, - "nodeId": "str", # Required. + "nodeId": "str", "proof": [ { - "left": "str", # Optional. Required. - "right": "str" # Optional. Required. + "left": "str", + "right": "str" } ], - "root": "str", # Optional. + "signature": "str", + "cert": "str", + "leaf": "str", + "leafComponents": { + "claimsDigest": "str", + "commitEvidence": "str", + "writeSetDigest": "str" + }, + "root": "str", "serviceEndorsements": [ - "str" # Optional. - ], - "signature": "str" # Required. - }, - "state": "str", # State of a ledger query. Required. Known values are: - "Loading" and "Ready". - "transactionId": "str" # A unique identifier for the state of the ledger. If - returned as part of a LedgerEntry, it indicates the state from which the entry - was read. Required. + "str" + ] + } } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_receipt_request( + _request = build_confidential_ledger_get_receipt_request( transaction_id=transaction_id, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -752,9 +838,9 @@ async def get_receipt(self, transaction_id: str, **kwargs: Any) -> JSON: deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore @distributed_trace_async async def get_transaction_status(self, transaction_id: str, **kwargs: Any) -> JSON: @@ -773,36 +859,37 @@ async def get_transaction_status(self, transaction_id: str, **kwargs: Any) -> JS # response body for status code(s): 200 response == { - "state": "str", # Represents the state of the transaction. Required. Known - values are: "Committed" and "Pending". - "transactionId": "str" # A unique identifier for the state of the ledger. If - returned as part of a LedgerEntry, it indicates the state from which the entry - was read. Required. + "state": "str", + "transactionId": "str" } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_transaction_status_request( + _request = build_confidential_ledger_get_transaction_status_request( transaction_id=transaction_id, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -817,9 +904,9 @@ async def get_transaction_status(self, transaction_id: str, **kwargs: Any) -> JS deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore @distributed_trace_async async def get_current_ledger_entry(self, *, collection_id: Optional[str] = None, **kwargs: Any) -> JSON: @@ -838,36 +925,38 @@ async def get_current_ledger_entry(self, *, collection_id: Optional[str] = None, # response body for status code(s): 200 response == { - "collectionId": "str", # Optional. - "contents": "str", # Contents of the ledger entry. Required. - "transactionId": "str" # Optional. A unique identifier for the state of the - ledger. If returned as part of a LedgerEntry, it indicates the state from which - the entry was read. + "contents": "str", + "collectionId": "str", + "transactionId": "str" } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_current_ledger_entry_request( + _request = build_confidential_ledger_get_current_ledger_entry_request( collection_id=collection_id, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -882,12 +971,200 @@ async def get_current_ledger_entry(self, *, collection_id: Optional[str] = None, deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace + def list_users(self, **kwargs: Any) -> AsyncIterable[JSON]: + """Gets details on a list of users. + + All users' object IDs and single role per user will be returned. + + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "assignedRole": "str", + "userId": "str" + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_confidential_ledger_list_users_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "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 + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["ledgerUsers"] + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) + + @distributed_trace + def list_ledger_users(self, **kwargs: Any) -> AsyncIterable[JSON]: + """Gets details on a list of users. + + All users' object IDs and multiple roles will be returned. + + :return: An iterator like instance of JSON object + :rtype: ~azure.core.async_paging.AsyncItemPaged[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "assignedRoles": [ + "str" + ], + "userId": "str" + } + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_confidential_ledger_list_ledger_users_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url( + "self._config.endpoint", self._config.endpoint, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "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 + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request - return cast(JSON, deserialized) + async def extract_data(pipeline_response): + deserialized = pipeline_response.http_response.json() + list_of_elem = deserialized["ledgerUsers"] + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.get("nextLink") or None, AsyncList(list_of_elem) + + async def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + return pipeline_response + + return AsyncItemPaged(get_next, extract_data) @distributed_trace_async - async def delete_user(self, user_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + async def delete_user(self, user_id: str, **kwargs: Any) -> None: """Deletes a user from the Confidential Ledger. Deletes a user from the Confidential Ledger. @@ -898,29 +1175,33 @@ async def delete_user(self, user_id: str, **kwargs: Any) -> None: # pylint: dis :rtype: None :raises ~azure.core.exceptions.HttpResponseError: """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[None] + cls: ClsType[None] = kwargs.pop("cls", None) - request = build_delete_user_request( + _request = build_confidential_ledger_delete_user_request( user_id=user_id, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -930,7 +1211,7 @@ async def delete_user(self, user_id: str, **kwargs: Any) -> None: # pylint: dis raise HttpResponseError(response=response) if cls: - return cls(pipeline_response, None, {}) + return cls(pipeline_response, None, {}) # type: ignore @distributed_trace_async async def get_user(self, user_id: str, **kwargs: Any) -> JSON: @@ -949,35 +1230,37 @@ async def get_user(self, user_id: str, **kwargs: Any) -> JSON: # response body for status code(s): 200 response == { - "assignedRole": "str", # Represents an assignable role. Required. Known - values are: "Administrator", "Contributor", and "Reader". - "userId": "str" # Optional. Identifier for the user. This must either be an - AAD object id or a certificate fingerprint. + "assignedRole": "str", + "userId": "str" } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_user_request( + _request = build_confidential_ledger_get_user_request( user_id=user_id, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -992,9 +1275,9 @@ async def get_user(self, user_id: str, **kwargs: Any) -> JSON: deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore @overload async def create_or_update_user( @@ -1020,24 +1303,25 @@ async def create_or_update_user( # JSON input template you can fill out and use as your body input. user_details = { - "assignedRole": "str", # Represents an assignable role. Required. Known - values are: "Administrator", "Contributor", and "Reader". - "userId": "str" # Optional. Identifier for the user. This must either be an - AAD object id or a certificate fingerprint. + "assignedRole": "str", + "userId": "str" } # response body for status code(s): 200 response == { - "assignedRole": "str", # Represents an assignable role. Required. Known - values are: "Administrator", "Contributor", and "Reader". - "userId": "str" # Optional. Identifier for the user. This must either be an - AAD object id or a certificate fingerprint. + "assignedRole": "str", + "userId": "str" } """ @overload async def create_or_update_user( - self, user_id: str, user_details: IO, *, content_type: str = "application/merge-patch+json", **kwargs: Any + self, + user_id: str, + user_details: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any ) -> JSON: """Adds a user or updates a user's fields. @@ -1046,7 +1330,7 @@ async def create_or_update_user( :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. :type user_id: str :param user_details: Details about a Confidential Ledger user. Required. - :type user_details: IO + :type user_details: 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 @@ -1059,27 +1343,22 @@ async def create_or_update_user( # response body for status code(s): 200 response == { - "assignedRole": "str", # Represents an assignable role. Required. Known - values are: "Administrator", "Contributor", and "Reader". - "userId": "str" # Optional. Identifier for the user. This must either be an - AAD object id or a certificate fingerprint. + "assignedRole": "str", + "userId": "str" } """ @distributed_trace_async - async def create_or_update_user(self, user_id: str, user_details: Union[JSON, IO], **kwargs: Any) -> JSON: + async def create_or_update_user(self, user_id: str, user_details: Union[JSON, IO[bytes]], **kwargs: Any) -> JSON: """Adds a user or updates a user's fields. A JSON merge patch is applied for existing users. :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. :type user_id: str - :param user_details: Details about a Confidential Ledger user. Is either a model type or a IO - type. Required. - :type user_details: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: - 'application/merge-patch+json'. Default value is None. - :paramtype content_type: str + :param user_details: Details about a Confidential Ledger user. Is either a JSON type or a + IO[bytes] type. Required. + :type user_details: JSON or IO[bytes] :return: JSON object :rtype: JSON :raises ~azure.core.exceptions.HttpResponseError: @@ -1087,32 +1366,41 @@ async def create_or_update_user(self, user_id: str, user_details: Union[JSON, IO Example: .. code-block:: python + # JSON input template you can fill out and use as your body input. + user_details = { + "assignedRole": "str", + "userId": "str" + } + # response body for status code(s): 200 response == { - "assignedRole": "str", # Represents an assignable role. Required. Known - values are: "Administrator", "Contributor", and "Reader". - "userId": "str" # Optional. Identifier for the user. This must either be an - AAD object id or a certificate fingerprint. + "assignedRole": "str", + "userId": "str" } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) content_type = content_type or "application/merge-patch+json" _json = None _content = None - if isinstance(user_details, (IO, bytes)): + if isinstance(user_details, (IOBase, bytes)): _content = user_details else: _json = user_details - request = build_create_or_update_user_request( + _request = build_confidential_ledger_create_or_update_user_request( user_id=user_id, content_type=content_type, api_version=self._config.api_version, @@ -1122,14 +1410,131 @@ async def create_or_update_user(self, user_id: str, user_details: Union[JSON, IO params=_params, ) path_format_arguments = { - "ledgerEndpoint": self._serialize.url( - "self._config.ledger_endpoint", self._config.ledger_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace_async + async def delete_ledger_user(self, user_id: str, **kwargs: Any) -> None: + """Deletes a user with multiple roles from the Confidential Ledger. + + Deletes a user with multiple roles from the Confidential Ledger. + + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_delete_ledger_user_request( + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + 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 + + @distributed_trace_async + async def get_ledger_user(self, user_id: str, **kwargs: Any) -> JSON: + """Gets a user with multiple roles. + + Gets a user with multiple roles. + + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "assignedRoles": [ + "str" + ], + "userId": "str" + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_ledger_user_request( + user_id=user_id, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -1144,6 +1549,1195 @@ async def create_or_update_user(self, user_id: str, user_details: Union[JSON, IO deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore + + @overload + async def create_or_update_ledger_user( + self, + user_id: str, + user_multiple_roles: JSON, + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> JSON: + """Adds a user or updates a user's fields. + + A JSON merge patch is applied for existing users. + + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :param user_multiple_roles: Details about a Confidential Ledger user with multiple roles. + Required. + :type user_multiple_roles: 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 + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + user_multiple_roles = { + "assignedRoles": [ + "str" + ], + "userId": "str" + } + + # response body for status code(s): 200 + response == { + "assignedRoles": [ + "str" + ], + "userId": "str" + } + """ + + @overload + async def create_or_update_ledger_user( + self, + user_id: str, + user_multiple_roles: IO[bytes], + *, + content_type: str = "application/merge-patch+json", + **kwargs: Any + ) -> JSON: + """Adds a user or updates a user's fields. + + A JSON merge patch is applied for existing users. + + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :param user_multiple_roles: Details about a Confidential Ledger user with multiple roles. + Required. + :type user_multiple_roles: 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 + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "assignedRoles": [ + "str" + ], + "userId": "str" + } + """ + + @distributed_trace_async + async def create_or_update_ledger_user( + self, user_id: str, user_multiple_roles: Union[JSON, IO[bytes]], **kwargs: Any + ) -> JSON: + """Adds a user or updates a user's fields. + + A JSON merge patch is applied for existing users. + + :param user_id: The user id, either an AAD object ID or certificate fingerprint. Required. + :type user_id: str + :param user_multiple_roles: Details about a Confidential Ledger user with multiple roles. Is + either a JSON type or a IO[bytes] type. Required. + :type user_multiple_roles: JSON or IO[bytes] + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + user_multiple_roles = { + "assignedRoles": [ + "str" + ], + "userId": "str" + } + + # response body for status code(s): 200 + response == { + "assignedRoles": [ + "str" + ], + "userId": "str" + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + content_type = content_type or "application/merge-patch+json" + _json = None + _content = None + if isinstance(user_multiple_roles, (IOBase, bytes)): + _content = user_multiple_roles + else: + _json = user_multiple_roles + + _request = build_confidential_ledger_create_or_update_ledger_user_request( + user_id=user_id, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace_async + async def get_user_defined_endpoint(self, **kwargs: Any) -> JSON: + """Gets a user defined endpoint. + + Returns the user defined endpoint in the ACL instance. + + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "metadata": { + "endpoints": { + "str": { + "delete": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "get": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "patch": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "put": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + } + } + } + }, + "modules": {} + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_user_defined_endpoint_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @overload + async def create_user_defined_endpoint( + self, bundle: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Creates a user defined endpoint. + + Creates the user defined endpoint in the ACL instance. + + :param bundle: bundle parameter description. Required. + :type bundle: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + bundle = { + "metadata": { + "endpoints": { + "str": { + "delete": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "get": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "patch": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "put": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + } + } + } + }, + "modules": {} + } + """ + + @overload + async def create_user_defined_endpoint( + self, bundle: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Creates a user defined endpoint. + + Creates the user defined endpoint in the ACL instance. + + :param bundle: bundle parameter description. Required. + :type bundle: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_user_defined_endpoint(self, bundle: Union[JSON, IO[bytes]], **kwargs: Any) -> None: + """Creates a user defined endpoint. + + Creates the user defined endpoint in the ACL instance. + + :param bundle: bundle parameter description. Is either a JSON type or a IO[bytes] type. + Required. + :type bundle: JSON or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + bundle = { + "metadata": { + "endpoints": { + "str": { + "delete": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "get": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "patch": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + }, + "put": { + "authn_policies": [ + {} + ], + "forwarding_required": "str", + "interpreter_reuse": { + "key": "str" + }, + "js_function": "str", + "js_module": "str", + "mode": "str", + "openapi": {}, + "openapi_hidden": bool, + "redirection_strategy": "str" + } + } + } + }, + "modules": {} + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(bundle, (IOBase, bytes)): + _content = bundle + else: + _json = bundle + + _request = build_confidential_ledger_create_user_defined_endpoint_request( + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [201]: + 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 + + @distributed_trace_async + async def get_runtime_options(self, **kwargs: Any) -> JSON: + """Runtime options for user defined endpoints. + + It returns the runtime options. + + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_runtime_options_request( + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @overload + async def update_runtime_options( + self, js_runtime_options: JSON, *, content_type: str = "application/json", **kwargs: Any + ) -> JSON: + """Runtime options for user defined endpoints. + + Updates the runtime options. + + :param js_runtime_options: JS runtime options. Required. + :type js_runtime_options: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + js_runtime_options = { + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool + } + + # response body for status code(s): 200 + response == { + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool + } + """ + + @overload + async def update_runtime_options( + self, js_runtime_options: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> JSON: + """Runtime options for user defined endpoints. + + Updates the runtime options. + + :param js_runtime_options: JS runtime options. Required. + :type js_runtime_options: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool + } + """ + + @distributed_trace_async + async def update_runtime_options(self, js_runtime_options: Union[JSON, IO[bytes]], **kwargs: Any) -> JSON: + """Runtime options for user defined endpoints. + + Updates the runtime options. + + :param js_runtime_options: JS runtime options. Is either a JSON type or a IO[bytes] type. + Required. + :type js_runtime_options: JSON or IO[bytes] + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + js_runtime_options = { + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool + } + + # response body for status code(s): 200 + response == { + "log_exception_details": bool, + "max_cached_interpreters": 0, + "max_execution_time_ms": 0, + "max_heap_bytes": 0, + "max_stack_bytes": 0, + "return_exception_details": bool + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[JSON] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(js_runtime_options, (IOBase, bytes)): + _content = js_runtime_options + else: + _json = js_runtime_options + + _request = build_confidential_ledger_update_runtime_options_request( + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace_async + async def get_user_defined_endpoints_module(self, *, module: str, **kwargs: Any) -> JSON: + """Module for user defined endpoints. + + It gets the module for the user defined endpoint. + + :keyword module: module name of the user defined endpoint. Required. + :paramtype module: str + :return: JSON object + :rtype: JSON + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == { + "module": "str", + "name": "str" + } + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[JSON] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_user_defined_endpoints_module_request( + module=module, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore + + return cast(JSON, deserialized) # type: ignore + + @distributed_trace_async + async def get_user_defined_role(self, *, role_name: str, **kwargs: Any) -> List[JSON]: + """Gets role actions for user defined roles. + + user defined roles allow users to define and manage app specific AuthZ policy. + + :keyword role_name: user defined role name. Required. + :paramtype role_name: str + :return: list of JSON object + :rtype: list[JSON] + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # response body for status code(s): 200 + response == [ + { + "roleActions": [ + "str" + ], + "roleName": "str" + } + ] + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[List[JSON]] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_get_user_defined_role_request( + role_name=role_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if response.content: + deserialized = response.json() + else: + deserialized = None + + if cls: + return cls(pipeline_response, cast(List[JSON], deserialized), {}) # type: ignore + + return cast(List[JSON], deserialized) # type: ignore + + @overload + async def create_user_defined_role( + self, roles: List[JSON], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Creates new roles and their actions. + + User defined roles allow users to define and manage app specific AuthZ policy. + + :param roles: user defined role. Required. + :type roles: list[JSON] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + roles = [ + { + "roleActions": [ + "str" + ], + "roleName": "str" + } + ] + """ + + @overload + async def create_user_defined_role( + self, roles: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Creates new roles and their actions. + + User defined roles allow users to define and manage app specific AuthZ policy. + + :param roles: user defined role. Required. + :type roles: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def create_user_defined_role(self, roles: Union[List[JSON], IO[bytes]], **kwargs: Any) -> None: + """Creates new roles and their actions. + + User defined roles allow users to define and manage app specific AuthZ policy. + + :param roles: user defined role. Is either a [JSON] type or a IO[bytes] type. Required. + :type roles: list[JSON] or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(roles, (IOBase, bytes)): + _content = roles + else: + _json = roles + + _request = build_confidential_ledger_create_user_defined_role_request( + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + 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 + + @overload + async def update_user_defined_role( + self, roles: List[JSON], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Patch replaces the allowed action on existing roles,if the desire is to remove an existing + action, the role must be deleted and recreated. + + User defined roles allow users to define and manage app specific AuthZ policy. + + :param roles: user defined role. Required. + :type roles: list[JSON] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + + Example: + .. code-block:: python + + # JSON input template you can fill out and use as your body input. + roles = [ + { + "roleActions": [ + "str" + ], + "roleName": "str" + } + ] + """ + + @overload + async def update_user_defined_role( + self, roles: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> None: + """Patch replaces the allowed action on existing roles,if the desire is to remove an existing + action, the role must be deleted and recreated. + + User defined roles allow users to define and manage app specific AuthZ policy. + + :param roles: user defined role. Required. + :type roles: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace_async + async def update_user_defined_role(self, roles: Union[List[JSON], IO[bytes]], **kwargs: Any) -> None: + """Patch replaces the allowed action on existing roles,if the desire is to remove an existing + action, the role must be deleted and recreated. + + User defined roles allow users to define and manage app specific AuthZ policy. + + :param roles: user defined role. Is either a [JSON] type or a IO[bytes] type. Required. + :type roles: list[JSON] or IO[bytes] + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[None] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(roles, (IOBase, bytes)): + _content = roles + else: + _json = roles + + _request = build_confidential_ledger_update_user_defined_role_request( + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + 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 + + @distributed_trace_async + async def delete_user_defined_role(self, *, role_name: str, **kwargs: Any) -> None: + """Deletes user defined roles. + + A user defined role allows the users to create and manage their own role actions using the API. + + :keyword role_name: user defined role name. Required. + :paramtype role_name: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_confidential_ledger_delete_user_defined_role_request( + role_name=role_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + 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 diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/_patch.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/_patch.py index 377598c23f6b..c3bbd9c01f8b 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/_patch.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_operations/_patch.py @@ -2,6 +2,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ + + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize @@ -56,16 +58,13 @@ async def run(self) -> None: except ResourceNotFoundError as not_found_exception: # We'll allow some instances of resource not found to account for replication # delay if session stickiness is lost. + self._not_found_count += 1 - not_retryable = ( - not self._retry_not_found or - self._give_up_not_found_error(not_found_exception) - ) + not_retryable = not self._retry_not_found or self._give_up_not_found_error(not_found_exception) - if not_retryable or self._not_found_count >=3: + if not_retryable or self._not_found_count >= 3: raise - if not self.finished(): await asyncio.sleep(self._polling_interval_s) except Exception: @@ -106,7 +105,6 @@ async def operation() -> JSON: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling - return AsyncLROPoller(self._client, initial_response, lambda x: x, polling_method) async def begin_get_receipt(self, transaction_id: str, **kwargs: Any) -> AsyncLROPoller[JSON]: @@ -135,7 +133,6 @@ async def operation() -> JSON: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling - return AsyncLROPoller(self._client, initial_response, lambda x: x, polling_method) async def begin_create_ledger_entry( @@ -160,11 +157,13 @@ async def begin_create_ledger_entry( """ # Pop arguments that are unexpected in the pipeline. + polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod] lro_delay = kwargs.pop("polling_interval", 0.5) # Pop the custom deserializer, if any, so we know the format of the response and can # retrieve the transactionId. Serialize the response later. + cls = kwargs.pop("cls", None) # type: ClsType[JSON] kwargs["cls"] = lambda pipeline_response, json_response, headers: ( pipeline_response, @@ -181,6 +180,7 @@ async def begin_create_ledger_entry( # Delete the cls because it should only apply to the create_ledger_entry response, not the # wait_for_commit call. + del kwargs["cls"] transaction_id = post_result["transactionId"] # type: ignore @@ -194,7 +194,6 @@ async def begin_create_ledger_entry( ) else: kwargs["_create_ledger_entry_response"] = post_result - return await self.begin_wait_for_commit(transaction_id, **kwargs) async def begin_wait_for_commit( @@ -217,8 +216,11 @@ async def begin_wait_for_commit( # If this poller was called from begin_create_ledger_entry, we should return the # create_ledger_entry response, not the transaction status. + post_result = kwargs.pop("_create_ledger_entry_response", None) - deserialization_callback = lambda x: x if post_result is None else post_result # pylint: disable=unnecessary-lambda-assignment + deserialization_callback = lambda x: ( + x if post_result is None else post_result + ) # pylint: disable=unnecessary-lambda-assignment async def operation() -> JSON: return await super(ConfidentialLedgerClientOperationsMixin, self).get_transaction_status( @@ -230,11 +232,10 @@ async def operation() -> JSON: except ResourceNotFoundError: if polling is False or polling is None: raise - # This method allows for temporary resource not found errors, which may occur if session # stickiness is lost and there is replication lag. - initial_response = {} + initial_response = {} if polling is True: polling_method = cast( AsyncPollingMethod, @@ -244,7 +245,6 @@ async def operation() -> JSON: polling_method = cast(AsyncPollingMethod, AsyncNoPolling()) else: polling_method = polling - return AsyncLROPoller(self._client, initial_response, deserialization_callback, polling_method) async def create_ledger_entry( diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_patch.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_patch.py index fff718e4beb7..49d8369389fb 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_patch.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_patch.py @@ -2,6 +2,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ + + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize @@ -17,6 +19,8 @@ ) # Since we can't `await` in __init__, use the sync client for the Identity Service. + + from azure.confidentialledger.certificate import ConfidentialLedgerCertificateClient from azure.confidentialledger._patch import ConfidentialLedgerCertificateCredential @@ -64,6 +68,7 @@ def __init__( ) -> None: # Remove some kwargs first so that there aren't unexpected kwargs passed to # get_ledger_identity. + if isinstance(credential, ConfidentialLedgerCertificateCredential): auth_policy = None else: @@ -77,35 +82,38 @@ def __init__( if auth_policy is None: auth_policy = policies.AsyncBearerTokenCredentialPolicy(credential, *credential_scopes, **kwargs) - if os.path.isfile(ledger_certificate_path) is False: # We'll need to fetch the TLS certificate. + identity_service_client = ConfidentialLedgerCertificateClient(**kwargs) # Ledger URIs are of the form https://.confidential-ledger.azure.com. + ledger_id = endpoint.replace("https://", "").split(".")[0] # We use the sync client here because async __init__ is not allowed. + ledger_cert = identity_service_client.get_ledger_identity(ledger_id, **kwargs) with open(ledger_certificate_path, "w", encoding="utf-8") as outfile: outfile.write(ledger_cert["ledgerTlsCertificate"]) - # For ConfidentialLedgerCertificateCredential, pass the path to the certificate down to the # PipelineCLient. + if isinstance(credential, ConfidentialLedgerCertificateCredential): # The async version of the client seems to expect a sequence of filenames. # azure/core/pipeline/transport/_aiohttp.py:163 # > ssl_ctx.load_cert_chain(*cert) - kwargs["connection_cert"] = kwargs.get("connection_cert", (credential.certificate_path,)) + kwargs["connection_cert"] = kwargs.get("connection_cert", (credential.certificate_path,)) # The auto-generated client has authentication disabled so we can customize authentication. # If the credential is the typical TokenCredential, then construct the authentication policy # the normal way. + else: kwargs["authentication_policy"] = auth_policy - # Customize the underlying client to use a self-signed TLS certificate. + kwargs["connection_verify"] = kwargs.get("connection_verify", ledger_certificate_path) super().__init__(endpoint, **kwargs) diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_vendor.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_vendor.py index 48480a9bf1b4..2d82c1785c02 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_vendor.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/aio/_vendor.py @@ -11,13 +11,12 @@ from ._configuration import ConfidentialLedgerClientConfiguration if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core import AsyncPipelineClient from .._serialization import Deserializer, Serializer -class MixinABC(ABC): +class ConfidentialLedgerClientMixinABC(ABC): """DO NOT use this class. It is for internal typing use only.""" _client: "AsyncPipelineClient" diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/__init__.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/__init__.py index b9acbf9e838b..ed7118cfb0c1 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/__init__.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/__init__.py @@ -5,20 +5,28 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._client import ConfidentialLedgerCertificateClient -from .._version import VERSION +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ConfidentialLedgerCertificateClient # type: ignore +from ._version import VERSION __version__ = VERSION try: from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ["ConfidentialLedgerCertificateClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__ = [ + "ConfidentialLedgerCertificateClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_client.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_client.py index be5a85104e18..325578a24188 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_client.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_client.py @@ -7,48 +7,59 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, TYPE_CHECKING +from typing import Any +from typing_extensions import Self from azure.core import PipelineClient +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from ._configuration import ConfidentialLedgerCertificateClientConfiguration from ._operations import ConfidentialLedgerCertificateClientOperationsMixin from ._serialization import Deserializer, Serializer -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - -class ConfidentialLedgerCertificateClient( - ConfidentialLedgerCertificateClientOperationsMixin -): # pylint: disable=client-accepts-api-version-keyword +class ConfidentialLedgerCertificateClient(ConfidentialLedgerCertificateClientOperationsMixin): """The ConfidentialLedgerCertificateClient is used to retrieve the TLS certificate required for connecting to a Confidential Ledger. - :param certificate_endpoint: The certificate endpoint (or "Identity Service Endpoint" in the - Azure portal), for example https://identity.confidential-ledger.core.azure.com. Required. - :type certificate_endpoint: str - :keyword api_version: Api Version. Default value is "2022-05-13". Note that overriding this - default value may result in unsupported behavior. + :param endpoint: The certificate endpoint (or "Identity Service Endpoint" in the Azure portal), + for example https://identity.confidential-ledger.core.azure.com. Required. + :type endpoint: str + :keyword api_version: Api Version. Default value is "2024-08-22-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, certificate_endpoint: str, **kwargs: Any + self, endpoint: str, **kwargs: Any ) -> None: - _endpoint = "{certificateEndpoint}" - self._config = ConfidentialLedgerCertificateClientConfiguration( - certificate_endpoint=certificate_endpoint, **kwargs - ) - self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) + _endpoint = "{endpoint}" + self._config = ConfidentialLedgerCertificateClientConfiguration(endpoint=endpoint, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -68,23 +79,18 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: request_copy = deepcopy(request) path_format_arguments = { - "certificateEndpoint": self._serialize.url( - "self._config.certificate_endpoint", self._config.certificate_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore - def close(self): - # type: () -> None + def close(self) -> None: self._client.close() - def __enter__(self): - # type: () -> ConfidentialLedgerCertificateClient + def __enter__(self) -> Self: self._client.__enter__() return self - def __exit__(self, *exc_details): - # type: (Any) -> None + def __exit__(self, *exc_details: Any) -> None: self._client.__exit__(*exc_details) diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_configuration.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_configuration.py index ffbc310f3e35..ca30382baef6 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_configuration.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_configuration.py @@ -8,48 +8,44 @@ from typing import Any -from azure.core.configuration import Configuration from azure.core.pipeline import policies -from .._version import VERSION +from ._version import VERSION -class ConfidentialLedgerCertificateClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes,name-too-long +class ConfidentialLedgerCertificateClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for ConfidentialLedgerCertificateClient. Note that all parameters used to create this instance are saved as instance attributes. - :param certificate_endpoint: The certificate endpoint (or "Identity Service Endpoint" in the - Azure portal), for example https://identity.confidential-ledger.core.azure.com. Required. - :type certificate_endpoint: str - :keyword api_version: Api Version. Default value is "2022-05-13". Note that overriding this - default value may result in unsupported behavior. + :param endpoint: The certificate endpoint (or "Identity Service Endpoint" in the Azure portal), + for example https://identity.confidential-ledger.core.azure.com. Required. + :type endpoint: str + :keyword api_version: Api Version. Default value is "2024-08-22-preview". Note that overriding + this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, certificate_endpoint: str, **kwargs: Any) -> None: - super(ConfidentialLedgerCertificateClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2022-05-13") # type: str + def __init__(self, endpoint: str, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2024-08-22-preview") - if certificate_endpoint is None: - raise ValueError("Parameter 'certificate_endpoint' must not be None.") + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") - self.certificate_endpoint = certificate_endpoint + self.endpoint = endpoint self.api_version = api_version kwargs.setdefault("sdk_moniker", "confidentialledger-certificate/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> None + def _configure(self, **kwargs: Any) -> None: self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) 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") diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/__init__.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/__init__.py index d52f4bc0bbb3..1bf45ef8f3f1 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/__init__.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/__init__.py @@ -5,15 +5,21 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import ConfidentialLedgerCertificateClientOperationsMixin +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ConfidentialLedgerCertificateClientOperationsMixin # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ConfidentialLedgerCertificateClientOperationsMixin", ] -__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/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/_operations.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/_operations.py index 0d0c51576759..c3c2d0fcc081 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/_operations.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -14,6 +13,7 @@ HttpResponseError, ResourceExistsError, ResourceNotFoundError, + ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse @@ -22,12 +22,12 @@ from azure.core.utils import case_insensitive_dict from .._serialization import Serializer -from .._vendor import MixinABC, _format_url_section +from .._vendor import ConfidentialLedgerCertificateClientMixinABC if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] @@ -36,11 +36,13 @@ _SERIALIZER.client_side_validation = False -def build_get_ledger_identity_request(ledger_id: str, **kwargs: Any) -> HttpRequest: +def build_confidential_ledger_certificate_get_ledger_identity_request( # pylint: disable=name-too-long + ledger_id: str, **kwargs: Any +) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version = kwargs.pop("api_version", _params.pop("api-version", "2022-05-13")) # type: str + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2024-08-22-preview")) accept = _headers.pop("Accept", "application/json") # Construct URL @@ -49,7 +51,7 @@ def build_get_ledger_identity_request(ledger_id: str, **kwargs: Any) -> HttpRequ "ledgerId": _SERIALIZER.url("ledger_id", ledger_id, "str"), } - _url = _format_url_section(_url, **path_format_arguments) + _url: str = _url.format(**path_format_arguments) # type: ignore # Construct parameters _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") @@ -60,7 +62,10 @@ def build_get_ledger_identity_request(ledger_id: str, **kwargs: Any) -> HttpRequ return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) -class ConfidentialLedgerCertificateClientOperationsMixin(MixinABC): # pylint: disable=name-too-long +class ConfidentialLedgerCertificateClientOperationsMixin( # pylint: disable=name-too-long + ConfidentialLedgerCertificateClientMixinABC +): + @distributed_trace def get_ledger_identity(self, ledger_id: str, **kwargs: Any) -> JSON: """Gets identity information for a Confidential Ledger instance. @@ -78,34 +83,37 @@ def get_ledger_identity(self, ledger_id: str, **kwargs: Any) -> JSON: # response body for status code(s): 200 response == { - "ledgerId": "str", # Optional. Id for the ledger. - "ledgerTlsCertificate": "str" # PEM-encoded certificate used for TLS by the - Confidential Ledger. Required. + "ledgerTlsCertificate": "str", + "ledgerId": "str" } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_ledger_identity_request( + _request = build_confidential_ledger_certificate_get_ledger_identity_request( ledger_id=ledger_id, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "certificateEndpoint": self._serialize.url( - "self._config.certificate_endpoint", self._config.certificate_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -120,6 +128,6 @@ def get_ledger_identity(self, ledger_id: str, **kwargs: Any) -> JSON: deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/_patch.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/_patch.py index f7dd32510333..5755fd181b3f 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/_patch.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_operations/_patch.py @@ -2,6 +2,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ + + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_patch.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_patch.py index 3aafda1ead49..fb932b4c9497 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_patch.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_patch.py @@ -2,6 +2,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ + + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize @@ -42,5 +44,4 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential if not certificate_endpoint: certificate_endpoint = "https://identity.confidential-ledger.core.azure.com" - super().__init__(certificate_endpoint, **kwargs) diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_serialization.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_serialization.py index 648f84cc4e65..b24ab2885450 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_serialization.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_serialization.py @@ -1,3 +1,4 @@ +# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. @@ -24,7 +25,7 @@ # # -------------------------------------------------------------------------- -# pylint: skip-file +# pyright: reportUnnecessaryTypeIgnoreComment=false from base64 import b64decode, b64encode import calendar @@ -37,23 +38,37 @@ import re import sys import codecs +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + TypeVar, + MutableMapping, + Type, + List, +) try: from urllib import quote # type: ignore except ImportError: - from urllib.parse import quote # type: ignore + from urllib.parse import quote import xml.etree.ElementTree as ET -import isodate +import isodate # type: ignore -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping +ModelType = TypeVar("ModelType", bound="Model") +JSON = MutableMapping[str, Any] class RawDeserializer: @@ -65,8 +80,7 @@ class RawDeserializer: CONTEXT_NAME = "deserialized_data" @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: """Decode data according to content-type. Accept a stream of data as well, but will be load at once in memory for now. @@ -76,6 +90,8 @@ def deserialize_from_text(cls, data, content_type=None): :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 @@ -97,7 +113,7 @@ def deserialize_from_text(cls, data, content_type=None): 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: @@ -109,7 +125,7 @@ def deserialize_from_text(cls, data, content_type=None): pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # It might be because the server has an issue, and returned JSON with # content-type XML.... # So let's try a JSON load, and if it's still broken @@ -128,17 +144,23 @@ def _json_attemp(data): # The function hack is because Py2.7 messes up with exception # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") + 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 - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: """Deserialize from HTTP response. 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 @@ -156,13 +178,6 @@ def deserialize_from_http_generics(cls, body_bytes, headers): return None -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - _LOGGER = logging.getLogger(__name__) try: @@ -175,20 +190,35 @@ class UTC(datetime.tzinfo): """Time Zone info for handling UTC""" def utcoffset(self, dt): - """UTF offset for UTC is 0.""" + """UTF offset for UTC is 0. + + :param datetime.datetime dt: The datetime + :returns: The offset + :rtype: datetime.timedelta + """ return datetime.timedelta(0) def tzname(self, dt): - """Timestamp representation.""" + """Timestamp representation. + + :param datetime.datetime dt: The datetime + :returns: The timestamp representation + :rtype: str + """ return "Z" def dst(self, dt): - """No daylight saving for UTC.""" + """No daylight saving for UTC. + + :param datetime.datetime dt: The datetime + :returns: The daylight saving time + :rtype: datetime.timedelta + """ return datetime.timedelta(hours=1) try: - from datetime import timezone as _FixedOffset + from datetime import timezone as _FixedOffset # type: ignore except ImportError: # Python 2.7 class _FixedOffset(datetime.tzinfo): # type: ignore @@ -197,7 +227,7 @@ class _FixedOffset(datetime.tzinfo): # type: ignore :param datetime.timedelta offset: offset in timedelta format """ - def __init__(self, offset): + def __init__(self, offset) -> None: self.__offset = offset def utcoffset(self, dt): @@ -219,31 +249,33 @@ def __getinitargs__(self): try: from datetime import timezone - TZ_UTC = timezone.utc # type: ignore + TZ_UTC = timezone.utc except ImportError: TZ_UTC = UTC() # type: ignore _FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[Dict[str, Any]] = {} + 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): @@ -290,43 +329,57 @@ def __init__(self, **kwargs): else: setattr(self, k, kwargs[k]) - def __eq__(self, other): - """Compare objects by comparing all attributes.""" + def __eq__(self, other: Any) -> bool: + """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): - """Compare objects by comparing all attributes.""" + def __ne__(self, other: Any) -> bool: + """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): + def __str__(self) -> str: return str(self.__dict__) @classmethod - def enable_additional_properties_sending(cls): + def enable_additional_properties_sending(cls) -> None: cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} @classmethod - def is_xml_model(cls): + def is_xml_model(cls) -> bool: try: - cls._xml_map + cls._xml_map # type: ignore except AttributeError: return False return True @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 + xml_map = cls._xml_map # type: ignore except AttributeError: xml_map = {} return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) - def serialize(self, keep_readonly=False, **kwargs): - """Return the JSON that would be sent to azure from this model. + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -337,10 +390,17 @@ def serialize(self, keep_readonly=False, **kwargs): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize( # type: ignore # pylint: disable=protected-access + self, keep_readonly=keep_readonly, **kwargs + ) - def as_dict(self, keep_readonly=True, key_transformer=attribute_transformer, **kwargs): - """Return a dict that can be JSONify using json.dump. + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. Advanced usage might optionally use a callback as parameter: @@ -366,12 +426,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) + 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): @@ -381,25 +444,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, data, content_type=None): + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: """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 + :rtype: ModelType """ deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod - def from_dict(cls, data, key_extractors=None, content_type=None): + def from_dict( + cls: Type[ModelType], + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> ModelType: """Parse a dict using given key extractor return a model. By default consider key @@ -407,13 +476,15 @@ def from_dict(cls, data, key_extractors=None, content_type=None): 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 + :rtype: ModelType """ deserializer = Deserializer(cls._infer_class_models()) - deserializer.key_extractors = ( - [ + deserializer.key_extractors = ( # type: ignore + [ # type: ignore attribute_key_case_insensitive_extractor, rest_key_case_insensitive_extractor, last_rest_key_case_insensitive_extractor, @@ -421,7 +492,7 @@ def from_dict(cls, data, key_extractors=None, content_type=None): if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -429,21 +500,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: @@ -453,7 +528,7 @@ def _classify(cls, response, objects): return cls flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) try: - return objects[flatten_mapping_type[subtype_value]] + return objects[flatten_mapping_type[subtype_value]] # type: ignore except KeyError: _LOGGER.warning( "Subtype value %s has no mapping, use base class %s.", @@ -482,11 +557,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"} @@ -521,7 +598,7 @@ class Serializer(object): "multiple": lambda x, y: x % y != 0, } - def __init__(self, classes=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.serialize_type = { "iso-8601": Serializer.serialize_iso, "rfc-1123": Serializer.serialize_rfc, @@ -537,17 +614,20 @@ def __init__(self, classes=None): "[]": self.serialize_iter, "{}": self.serialize_dict, } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} 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. + :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) keep_readonly = kwargs.get("keep_readonly", False) @@ -573,12 +653,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"] == "": @@ -605,62 +687,63 @@ def _serialize(self, target_obj, data_type=None, **kwargs): if xml_desc.get("attr", False): if xml_ns: ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore continue if xml_desc.get("text", False): - serialized.text = new_attr + serialized.text = new_attr # type: ignore continue if isinstance(new_attr, list): - serialized.extend(new_attr) + 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 new_attr.tag = "}".join([splitted_tag[0], xml_name]) else: new_attr.tag = xml_name - serialized.append(new_attr) + serialized.append(new_attr) # type: ignore else: # That's a basic type # Integrate namespace if necessary local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) + local_node.text = str(new_attr) + serialized.append(local_node) # type: ignore else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} _new_attr = new_attr _serialized = serialized - for k in keys: + for k in keys: # type: ignore if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore _serialized = _serialized[k] - except ValueError: - continue + except ValueError as err: + if isinstance(err, SerializationError): + raise except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized + raise SerializationError(msg) from err + 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 + :returns: The serialized request body """ # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) try: is_xml_model_serialization = kwargs["is_xml"] except KeyError: @@ -675,7 +758,7 @@ def body(self, data, data_type, **kwargs): # We're not able to deal with additional properties for now. deserializer.additional_properties_detection = False if is_xml_model_serialization: - deserializer.key_extractors = [ + deserializer.key_extractors = [ # type: ignore attribute_key_case_insensitive_extractor, ] else: @@ -684,18 +767,20 @@ 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_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from err return self._serialize(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 + :returns: The serialized URL path :raises: TypeError if serialization fails. :raises: ValueError if data is None """ @@ -706,30 +791,30 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) + 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. - :rtype: str + :rtype: str, list :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 if data_type.startswith("["): internal_data_type = data_type[1:-1] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -739,19 +824,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 + :returns: The serialized header """ try: if data_type in ["[str]"]: @@ -760,30 +846,31 @@ 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. + :returns: The serialized data. + :rtype: str, int, float, bool, dict, list """ if data is None: raise ValueError("No value for given attribute") try: + if data is CoreNull: + return None 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 @@ -798,12 +885,11 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) + raise SerializationError(msg.format(data, data_type)) from err + 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 @@ -819,23 +905,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 @@ -843,14 +932,13 @@ def serialize_unicode(cls, data): pass try: - if isinstance(data, unicode): + if isinstance(data, unicode): # type: ignore # Don't change it, JSON and XML ElementTree are totally able # to serialize correctly u'' strings 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. @@ -860,13 +948,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'. + Defaults to False. :rtype: list, str + :return: serialized iterable """ if isinstance(data, str): raise SerializationError("Refuse str type as a valid iter type.") @@ -878,9 +966,14 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): for d in data: try: serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized.append(None) + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + if div: serialized = ["" if s is None else str(s) for s in serialized] serialized = div.join(serialized) @@ -916,16 +1009,17 @@ 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 = {} for key, value in attr.items(): try: serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: + except ValueError as err: + if isinstance(err, SerializationError): + raise serialized[self.serialize_unicode(key)] = None if "xml" in serialization_ctxt: @@ -940,7 +1034,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 @@ -948,6 +1042,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 @@ -958,7 +1053,7 @@ def serialize_object(self, attr, **kwargs): return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) if obj_type is _long_type: return self.serialize_long(attr) - if obj_type is unicode_str: + if obj_type is str: return self.serialize_unicode(attr) if obj_type is datetime.datetime: return self.serialize_iso(attr) @@ -972,7 +1067,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: @@ -1001,58 +1096,63 @@ def serialize_enum(attr, enum_obj=None): except AttributeError: result = attr try: - enum_obj(result) + enum_obj(result) # type: ignore return result - except ValueError: - for enum_value in enum_obj: + 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) @@ -1060,11 +1160,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) @@ -1074,30 +1175,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. + :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], @@ -1110,12 +1213,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. + :return: serialized iso """ if isinstance(attr, str): attr = isodate.parse_datetime(attr) @@ -1135,19 +1239,20 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + 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 + :return: serialied unix """ if isinstance(attr, int): return attr @@ -1155,16 +1260,17 @@ 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 while "." in key: - dict_keys = _FLATTEN.split(key) + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _FLATTEN.split(key)) if len(dict_keys) == 1: key = _decode_attribute_map_key(dict_keys[0]) break @@ -1173,14 +1279,15 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) 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 @@ -1194,7 +1301,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1202,17 +1308,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) @@ -1245,11 +1363,11 @@ def _extract_name_from_internal_type(internal_type): xml_name = internal_type_xml_map.get("name", internal_type.__name__) xml_ns = internal_type_xml_map.get("ns", None) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) 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 @@ -1269,7 +1387,7 @@ def xml_key_extractor(attr, attr_desc, data): # Integrate namespace if necessary xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) # If it's an attribute, that's simple if xml_desc.get("attr", False): @@ -1301,22 +1419,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( # pylint: disable=line-too-long + 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: @@ -1324,7 +1441,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. @@ -1333,9 +1450,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=None): + def __init__(self, classes: Optional[Mapping[str, type]] = None) -> None: self.deserialize_type = { "iso-8601": Deserializer.deserialize_iso, "rfc-1123": Deserializer.deserialize_rfc, @@ -1355,7 +1472,7 @@ def __init__(self, classes=None): "duration": (isodate.Duration, datetime.timedelta), "iso-8601": (datetime.datetime), } - self.dependencies = dict(classes) if classes else {} + self.dependencies: Dict[str, type] = dict(classes) if classes else {} self.key_extractors = [rest_key_extractor, xml_key_extractor] # Additional properties only works if the "rest_key_extractor" is used to # extract the keys. Making it to work whatever the key extractor is too much @@ -1373,11 +1490,12 @@ def __call__(self, target_obj, response_data, content_type=None): :param str content_type: Swagger "produces" if available. :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 @@ -1386,12 +1504,13 @@ def _deserialize(self, target_obj, data): :param object data: Object to deserialize. :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) @@ -1408,15 +1527,15 @@ def _deserialize(self, target_obj, data): response, class_name = self._classify_target(target_obj, data) - if isinstance(response, basestring): + 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 + 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"... @@ -1444,11 +1563,10 @@ def _deserialize(self, target_obj, data): value = self.deserialize_data(raw_value, attr_desc["type"]) d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + 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: @@ -1474,22 +1592,24 @@ def _classify_target(self, target, data): Once classification has been determined, initialize object. :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :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 - if isinstance(target, basestring): + if isinstance(target, str): try: target = self.dependencies[target] except KeyError: return target, target try: - target = target._classify(data, self.dependencies) + 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__ + return target, target.__class__.__name__ # type: ignore def failsafe_deserialize(self, target_obj, data, content_type=None): """Ignores any errors encountered in deserialization, @@ -1499,13 +1619,15 @@ def failsafe_deserialize(self, target_obj, data, content_type=None): a deserialization error. :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. + :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: - _LOGGER.warning( + except: # pylint: disable=bare-except + _LOGGER.debug( "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True ) return None @@ -1522,10 +1644,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", {}) @@ -1542,31 +1666,42 @@ def _unpack_content(raw_data, content_type=None): if hasattr(raw_data, "_content_consumed"): return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) + if isinstance(raw_data, (str, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore return raw_data 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) - raise DeserializationError(msg + str(err)) + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) from err else: try: for attr, value in attrs.items(): @@ -1575,15 +1710,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. :return: Deserialized object. + :rtype: object """ if data is None: return data @@ -1597,7 +1733,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) @@ -1616,15 +1756,15 @@ def deserialize_data(self, data, data_type): except (ValueError, TypeError, AttributeError) as err: msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) + raise DeserializationError(msg) from err + 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: @@ -1641,6 +1781,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): @@ -1651,11 +1792,12 @@ 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. """ @@ -1664,7 +1806,7 @@ def deserialize_object(self, attr, **kwargs): if isinstance(attr, ET.Element): # Do no recurse on XML, just return the tree as-is return attr - if isinstance(attr, basestring): + if isinstance(attr, str): return self.deserialize_basic(attr, "str") obj_type = type(attr) if obj_type in self.basic_types: @@ -1690,11 +1832,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 @@ -1702,6 +1843,7 @@ 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. """ @@ -1713,24 +1855,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, basestring): + 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): @@ -1738,6 +1879,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, @@ -1747,12 +1889,11 @@ def deserialize_unicode(data): # Consider this is real string try: - if isinstance(data, unicode): + if isinstance(data, unicode): # type: ignore return data except NameError: return str(data) - else: - return str(data) + return str(data) @staticmethod def deserialize_enum(data, enum_obj): @@ -1764,6 +1905,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: @@ -1772,12 +1914,11 @@ def deserialize_enum(data, enum_obj): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 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: @@ -1793,25 +1934,27 @@ 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. """ if isinstance(attr, ET.Element): attr = attr.text - return bytearray(b64decode(attr)) + return bytearray(b64decode(attr)) # type: ignore @staticmethod 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. """ if isinstance(attr, ET.Element): attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore encoded = attr.replace("-", "+").replace("_", "/") return b64decode(encoded) @@ -1820,34 +1963,37 @@ def deserialize_decimal(attr): """Deserialize string into Decimal object. :param str attr: response string to be deserialized. - :rtype: Decimal + :return: Deserialized decimal :raises: DeserializationError if string format invalid. + :rtype: decimal """ if isinstance(attr, ET.Element): attr = attr.text try: - return decimal.Decimal(attr) + return decimal.Decimal(str(attr)) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod 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. """ if isinstance(attr, ET.Element): attr = attr.text - return _long_type(attr) + return _long_type(attr) # type: ignore @staticmethod 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. """ @@ -1857,36 +2003,37 @@ def deserialize_duration(attr): duration = isodate.parse_duration(attr) except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration + raise DeserializationError(msg) from err + 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. """ if isinstance(attr, ET.Element): attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) @staticmethod 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. """ if isinstance(attr, ET.Element): attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore raise DeserializationError("Date must have only digits and -. Received: %s" % attr) return isodate.parse_time(attr) @@ -1895,13 +2042,14 @@ 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. """ if isinstance(attr, ET.Element): attr = attr.text try: - parsed_date = email.utils.parsedate_tz(attr) + 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)) ) @@ -1909,22 +2057,22 @@ def deserialize_rfc(attr): date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + 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. """ if isinstance(attr, ET.Element): attr = attr.text try: - attr = attr.upper() + attr = attr.upper() # type: ignore match = Deserializer.valid_date.match(attr) if not match: raise ValueError("Invalid datetime string: " + attr) @@ -1946,9 +2094,8 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj @staticmethod def deserialize_unix(attr): @@ -1956,15 +2103,16 @@ 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 """ if isinstance(attr, ET.Element): - attr = int(attr.text) + attr = int(attr.text) # type: ignore try: + attr = int(attr) date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj + raise DeserializationError(msg) from err + return date_obj diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_vendor.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_vendor.py index 24547660b34f..4ec17b50a333 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_vendor.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_vendor.py @@ -11,24 +11,12 @@ from ._configuration import ConfidentialLedgerCertificateClientConfiguration if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core import PipelineClient from ._serialization import Deserializer, Serializer -def _format_url_section(template, **kwargs): # pylint: disable=inconsistent-return-statements - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) - - -class MixinABC(ABC): +class ConfidentialLedgerCertificateClientMixinABC(ABC): # pylint: disable=name-too-long """DO NOT use this class. It is for internal typing use only.""" _client: "PipelineClient" diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_version.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_version.py new file mode 100644 index 000000000000..43d7b9b75006 --- /dev/null +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/_version.py @@ -0,0 +1,9 @@ +# 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) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.1.2" diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/__init__.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/__init__.py index b0ac5248f088..8c6c74550f4d 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/__init__.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/__init__.py @@ -5,17 +5,25 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._client import ConfidentialLedgerCertificateClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._client import ConfidentialLedgerCertificateClient # type: ignore try: from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import + from ._patch import * except ImportError: _patch_all = [] from ._patch import patch_sdk as _patch_sdk -__all__ = ["ConfidentialLedgerCertificateClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) +__all__ = [ + "ConfidentialLedgerCertificateClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) # pyright: ignore _patch_sdk() diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_client.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_client.py index 271c161d1d74..0dd8dacc4fcb 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_client.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_client.py @@ -7,48 +7,61 @@ # -------------------------------------------------------------------------- from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING +from typing import Any, Awaitable +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 ._configuration import ConfidentialLedgerCertificateClientConfiguration from ._operations import ConfidentialLedgerCertificateClientOperationsMixin -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - -class ConfidentialLedgerCertificateClient( - ConfidentialLedgerCertificateClientOperationsMixin -): # pylint: disable=client-accepts-api-version-keyword +class ConfidentialLedgerCertificateClient(ConfidentialLedgerCertificateClientOperationsMixin): """The ConfidentialLedgerCertificateClient is used to retrieve the TLS certificate required for connecting to a Confidential Ledger. - :param certificate_endpoint: The certificate endpoint (or "Identity Service Endpoint" in the - Azure portal), for example https://identity.confidential-ledger.core.azure.com. Required. - :type certificate_endpoint: str - :keyword api_version: Api Version. Default value is "2022-05-13". Note that overriding this - default value may result in unsupported behavior. + :param endpoint: The certificate endpoint (or "Identity Service Endpoint" in the Azure portal), + for example https://identity.confidential-ledger.core.azure.com. Required. + :type endpoint: str + :keyword api_version: Api Version. Default value is "2024-08-22-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, certificate_endpoint: str, **kwargs: Any + self, endpoint: str, **kwargs: Any ) -> None: - _endpoint = "{certificateEndpoint}" - self._config = ConfidentialLedgerCertificateClientConfiguration( - certificate_endpoint=certificate_endpoint, **kwargs - ) - self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) + _endpoint = "{endpoint}" + self._config = ConfidentialLedgerCertificateClientConfiguration(endpoint=endpoint, **kwargs) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) self._serialize = Serializer() self._deserialize = Deserializer() self._serialize.client_side_validation = False - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: + def send_request( + self, request: HttpRequest, *, stream: bool = False, **kwargs: Any + ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. >>> from azure.core.rest import HttpRequest @@ -68,20 +81,18 @@ def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHt request_copy = deepcopy(request) path_format_arguments = { - "certificateEndpoint": self._serialize.url( - "self._config.certificate_endpoint", self._config.certificate_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() - async def __aenter__(self) -> "ConfidentialLedgerCertificateClient": + async def __aenter__(self) -> Self: await self._client.__aenter__() return self - async def __aexit__(self, *exc_details) -> None: + async def __aexit__(self, *exc_details: Any) -> None: await self._client.__aexit__(*exc_details) diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_configuration.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_configuration.py index 53ad12beeae6..d329d5e5a72b 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_configuration.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_configuration.py @@ -8,36 +8,35 @@ from typing import Any -from azure.core.configuration import Configuration from azure.core.pipeline import policies -from ..._version import VERSION +from .._version import VERSION -class ConfidentialLedgerCertificateClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes,name-too-long +class ConfidentialLedgerCertificateClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for ConfidentialLedgerCertificateClient. Note that all parameters used to create this instance are saved as instance attributes. - :param certificate_endpoint: The certificate endpoint (or "Identity Service Endpoint" in the - Azure portal), for example https://identity.confidential-ledger.core.azure.com. Required. - :type certificate_endpoint: str - :keyword api_version: Api Version. Default value is "2022-05-13". Note that overriding this - default value may result in unsupported behavior. + :param endpoint: The certificate endpoint (or "Identity Service Endpoint" in the Azure portal), + for example https://identity.confidential-ledger.core.azure.com. Required. + :type endpoint: str + :keyword api_version: Api Version. Default value is "2024-08-22-preview". Note that overriding + this default value may result in unsupported behavior. :paramtype api_version: str """ - def __init__(self, certificate_endpoint: str, **kwargs: Any) -> None: - super(ConfidentialLedgerCertificateClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2022-05-13") # type: str + def __init__(self, endpoint: str, **kwargs: Any) -> None: + api_version: str = kwargs.pop("api_version", "2024-08-22-preview") - if certificate_endpoint is None: - raise ValueError("Parameter 'certificate_endpoint' must not be None.") + if endpoint is None: + raise ValueError("Parameter 'endpoint' must not be None.") - self.certificate_endpoint = certificate_endpoint + self.endpoint = endpoint self.api_version = api_version kwargs.setdefault("sdk_moniker", "confidentialledger-certificate/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _configure(self, **kwargs: Any) -> None: @@ -46,7 +45,7 @@ def _configure(self, **kwargs: Any) -> None: self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get("retry_policy") or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) 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") diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/__init__.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/__init__.py index d52f4bc0bbb3..1bf45ef8f3f1 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/__init__.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/__init__.py @@ -5,15 +5,21 @@ # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +# pylint: disable=wrong-import-position -from ._operations import ConfidentialLedgerCertificateClientOperationsMixin +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from ._patch import * # pylint: disable=unused-wildcard-import + +from ._operations import ConfidentialLedgerCertificateClientOperationsMixin # type: ignore from ._patch import __all__ as _patch_all -from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import +from ._patch import * from ._patch import patch_sdk as _patch_sdk __all__ = [ "ConfidentialLedgerCertificateClientOperationsMixin", ] -__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/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/_operations.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/_operations.py index 05f6b9bb08e1..5954145a9eb5 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/_operations.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/_operations.py @@ -1,4 +1,3 @@ -# pylint: disable=too-many-lines # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -14,25 +13,29 @@ HttpResponseError, ResourceExistsError, ResourceNotFoundError, + ResourceNotModifiedError, map_error, ) from azure.core.pipeline import PipelineResponse -from azure.core.rest import HttpRequest, AsyncHttpResponse +from azure.core.rest import AsyncHttpResponse, HttpRequest from azure.core.tracing.decorator_async import distributed_trace_async -from ..._operations._operations import build_get_ledger_identity_request -from .._vendor import MixinABC +from ..._operations._operations import build_confidential_ledger_certificate_get_ledger_identity_request +from .._vendor import ConfidentialLedgerCertificateClientMixinABC if sys.version_info >= (3, 9): from collections.abc import MutableMapping else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + from typing import MutableMapping # type: ignore JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object T = TypeVar("T") ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] -class ConfidentialLedgerCertificateClientOperationsMixin(MixinABC): # pylint: disable=name-too-long +class ConfidentialLedgerCertificateClientOperationsMixin( # pylint: disable=name-too-long + ConfidentialLedgerCertificateClientMixinABC +): + @distributed_trace_async async def get_ledger_identity(self, ledger_id: str, **kwargs: Any) -> JSON: """Gets identity information for a Confidential Ledger instance. @@ -50,34 +53,37 @@ async def get_ledger_identity(self, ledger_id: str, **kwargs: Any) -> JSON: # response body for status code(s): 200 response == { - "ledgerId": "str", # Optional. Id for the ledger. - "ledgerTlsCertificate": "str" # PEM-encoded certificate used for TLS by the - Confidential Ledger. Required. + "ledgerTlsCertificate": "str", + "ledgerId": "str" } """ - error_map = {401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError} + error_map: MutableMapping = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } error_map.update(kwargs.pop("error_map", {}) or {}) _headers = kwargs.pop("headers", {}) or {} _params = kwargs.pop("params", {}) or {} - cls = kwargs.pop("cls", None) # type: ClsType[JSON] + cls: ClsType[JSON] = kwargs.pop("cls", None) - request = build_get_ledger_identity_request( + _request = build_confidential_ledger_certificate_get_ledger_identity_request( ledger_id=ledger_id, api_version=self._config.api_version, headers=_headers, params=_params, ) path_format_arguments = { - "certificateEndpoint": self._serialize.url( - "self._config.certificate_endpoint", self._config.certificate_endpoint, "str", skip_quote=True - ), + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) # type: ignore + _request.url = self._client.format_url(_request.url, **path_format_arguments) - pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, stream=False, **kwargs + _stream = False + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, stream=_stream, **kwargs ) response = pipeline_response.http_response @@ -92,6 +98,6 @@ async def get_ledger_identity(self, ledger_id: str, **kwargs: Any) -> JSON: deserialized = None if cls: - return cls(pipeline_response, cast(JSON, deserialized), {}) + return cls(pipeline_response, cast(JSON, deserialized), {}) # type: ignore - return cast(JSON, deserialized) + return cast(JSON, deserialized) # type: ignore diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/_patch.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/_patch.py index f7dd32510333..5755fd181b3f 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/_patch.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_operations/_patch.py @@ -2,6 +2,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ + + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_patch.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_patch.py index c68f07004646..f91afd0831f5 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_patch.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_patch.py @@ -2,6 +2,8 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # ------------------------------------ + + """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize @@ -42,5 +44,4 @@ def __init__( # pylint: disable=missing-client-constructor-parameter-credential if not certificate_endpoint: certificate_endpoint = "https://identity.confidential-ledger.core.azure.com" - super().__init__(certificate_endpoint, **kwargs) diff --git a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_vendor.py b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_vendor.py index 32fc1057e7db..11d43f27728a 100644 --- a/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_vendor.py +++ b/sdk/confidentialledger/azure-confidentialledger/azure/confidentialledger/certificate/aio/_vendor.py @@ -11,13 +11,12 @@ from ._configuration import ConfidentialLedgerCertificateClientConfiguration if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports from azure.core import AsyncPipelineClient from .._serialization import Deserializer, Serializer -class MixinABC(ABC): +class ConfidentialLedgerCertificateClientMixinABC(ABC): # pylint: disable=name-too-long """DO NOT use this class. It is for internal typing use only.""" _client: "AsyncPipelineClient" diff --git a/sdk/confidentialledger/azure-confidentialledger/setup.py b/sdk/confidentialledger/azure-confidentialledger/setup.py index 8722dcbc6cee..c36678bbb93f 100644 --- a/sdk/confidentialledger/azure-confidentialledger/setup.py +++ b/sdk/confidentialledger/azure-confidentialledger/setup.py @@ -76,7 +76,7 @@ 'pytyped': ['py.typed'], }, install_requires=[ - "azure-core<2.0.0,>=1.24.0", + "azure-core<2.0.0,>=1.28.0", "isodate<1.0.0,>=0.6.1", "cryptography>=2.1.4", ], diff --git a/sdk/confidentialledger/azure-confidentialledger/swagger/README.md b/sdk/confidentialledger/azure-confidentialledger/swagger/README.md index cbc629ee1ba9..c54737e4e034 100644 --- a/sdk/confidentialledger/azure-confidentialledger/swagger/README.md +++ b/sdk/confidentialledger/azure-confidentialledger/swagger/README.md @@ -7,7 +7,7 @@ #### Tag: confidential-ledger These settings apply only when `--tag=confidential-ledger` is specified on the command line. ```yaml $(tag) == 'confidential-ledger' -input-file: https://github.com/Azure/azure-rest-api-specs/blob/main/specification/confidentialledger/data-plane/Microsoft.ConfidentialLedger/stable/2022-05-13/confidentialledger.json +input-file: https://github.com/Azure/azure-rest-api-specs/blob/main/specification/confidentialledger/data-plane/Microsoft.ConfidentialLedger/preview/2024-08-22-preview/confidentialledger.json output-folder: ../azure/confidentialledger namespace: azure.confidentialledger package-name: azure-confidentialledger @@ -23,7 +23,7 @@ python: true #### Tag: identity-service These settings apply only when `--tag=identity-service` is specified on the command line. ```yaml $(tag) == 'identity-service' -input-file: https://github.com/Azure/azure-rest-api-specs/blob/main/specification/confidentialledger/data-plane/Microsoft.ConfidentialLedger/stable/2022-05-13/identityservice.json +input-file: https://github.com/Azure/azure-rest-api-specs/blob/main/specification/confidentialledger/data-plane/Microsoft.ConfidentialLedger/preview/2024-08-22-preview/identityservice.json output-folder: ../azure/confidentialledger/certificate namespace: azure.confidentialledger.certificate package-name: azure-confidentialledger-certificate @@ -40,6 +40,6 @@ python: true Batch execution allows nested generation without the parent module overwriting the child. ```yaml batch: - - tag: confidential-ledger - tag: identity-service + - tag: confidential-ledger ``` \ No newline at end of file