From 81a7868ce579fb7eb0685c64ac71dda2594b8620 Mon Sep 17 00:00:00 2001 From: SDKAuto Date: Mon, 14 Apr 2025 02:47:52 +0000 Subject: [PATCH] CodeGen from PR 33563 in Azure/azure-rest-api-specs Merge dc27bd5306084ea4bfed262ff47ba4955b903817 into d18ba009da04dd6afc04402c39f87e032051fe9b --- .../azure-schemaregistry/_meta.json | 6 + .../apiview-properties.json | 6 + .../azure/schemaregistry/_model_base.py | 65 +- .../schemaregistry/_operations/_operations.py | 8 +- .../schemaregistry/_operations/_patch.py | 284 +-------- .../azure/schemaregistry/_patch.py | 571 +----------------- .../azure/schemaregistry/_serialization.py | 178 ++---- .../azure/schemaregistry/_version.py | 2 +- .../aio/_operations/_operations.py | 9 +- .../schemaregistry/aio/_operations/_patch.py | 225 +------ .../azure/schemaregistry/aio/_patch.py | 355 +---------- .../azure/schemaregistry/encoder/__init__.py | 26 - .../encoder/jsonencoder/__init__.py | 36 -- .../encoder/jsonencoder/_constants.py | 27 - .../encoder/jsonencoder/_exceptions.py | 44 -- .../_schema_registry_json_encoder.py | 382 ------------ .../encoder/jsonencoder/_utils.py | 261 -------- .../encoder/jsonencoder/_version.py | 27 - .../encoder/jsonencoder/aio/__init__.py | 30 - .../encoder/jsonencoder/aio/_async_lru.py | 228 ------- .../_schema_registry_json_encoder_async.py | 388 ------------ .../encoder/jsonencoder/py.typed | 1 - .../azure/schemaregistry/models/_patch.py | 38 +- .../generated_tests/conftest.py | 39 ++ .../generated_tests/testpreparer.py | 26 + .../testpreparer_async.py} | 20 +- .../eventhub_receive_integration_async.py | 1 + .../eventhub_receive_integration.py | 1 + .../async_tests/test_schema_registry_async.py | 1 + .../tests/test_schema_registry.py | 1 + .../azure-schemaregistry/tsp-location.yaml | 6 +- 31 files changed, 247 insertions(+), 3045 deletions(-) create mode 100644 sdk/schemaregistry/azure-schemaregistry/_meta.json create mode 100644 sdk/schemaregistry/azure-schemaregistry/apiview-properties.json delete mode 100644 sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/__init__.py delete mode 100644 sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/__init__.py delete mode 100644 sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_constants.py delete mode 100644 sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_exceptions.py delete mode 100644 sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_schema_registry_json_encoder.py delete mode 100644 sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_utils.py delete mode 100644 sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_version.py delete mode 100644 sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/__init__.py delete mode 100644 sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/_async_lru.py delete mode 100644 sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/_schema_registry_json_encoder_async.py delete mode 100644 sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/py.typed create mode 100644 sdk/schemaregistry/azure-schemaregistry/generated_tests/conftest.py create mode 100644 sdk/schemaregistry/azure-schemaregistry/generated_tests/testpreparer.py rename sdk/schemaregistry/azure-schemaregistry/{azure/schemaregistry/_types.py => generated_tests/testpreparer_async.py} (50%) diff --git a/sdk/schemaregistry/azure-schemaregistry/_meta.json b/sdk/schemaregistry/azure-schemaregistry/_meta.json new file mode 100644 index 000000000000..ca9079c69dec --- /dev/null +++ b/sdk/schemaregistry/azure-schemaregistry/_meta.json @@ -0,0 +1,6 @@ +{ + "commit": "0452565bc97d1f2d55954d99d170a38529ba7e4b", + "repository_url": "https://github.com/Azure/azure-rest-api-specs", + "typespec_src": "specification/schemaregistry/SchemaRegistry", + "@azure-tools/typespec-python": "0.42.2" +} \ No newline at end of file diff --git a/sdk/schemaregistry/azure-schemaregistry/apiview-properties.json b/sdk/schemaregistry/azure-schemaregistry/apiview-properties.json new file mode 100644 index 000000000000..f34b5bd43962 --- /dev/null +++ b/sdk/schemaregistry/azure-schemaregistry/apiview-properties.json @@ -0,0 +1,6 @@ +{ + "CrossLanguagePackageId": "SchemaRegistry", + "CrossLanguageDefinitionId": { + "azure.schemaregistry.models.SchemaContentTypeValues": "SchemaRegistry.SchemaContentTypeValues" + } +} \ No newline at end of file diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_model_base.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_model_base.py index 7f73b97b23ef..065b17f67c46 100644 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_model_base.py +++ b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_model_base.py @@ -2,8 +2,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. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pylint: disable=protected-access, broad-except @@ -373,15 +374,34 @@ def __ne__(self, other: typing.Any) -> bool: return not self.__eq__(other) def keys(self) -> typing.KeysView[str]: + """ + :returns: a set-like object providing a view on D's keys + :rtype: ~typing.KeysView + """ return self._data.keys() def values(self) -> typing.ValuesView[typing.Any]: + """ + :returns: an object providing a view on D's values + :rtype: ~typing.ValuesView + """ return self._data.values() def items(self) -> typing.ItemsView[str, typing.Any]: + """ + :returns: set-like object providing a view on D's items + :rtype: ~typing.ItemsView + """ return self._data.items() def get(self, key: str, default: typing.Any = None) -> typing.Any: + """ + Get the value for key if key is in the dictionary, else default. + :param str key: The key to look up. + :param any default: The value to return if key is not in the dictionary. Defaults to None + :returns: D[k] if k in D, else d. + :rtype: any + """ try: return self[key] except KeyError: @@ -397,17 +417,38 @@ def pop(self, key: str, default: _T) -> _T: ... def pop(self, key: str, default: typing.Any) -> typing.Any: ... def pop(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Removes specified key and return the corresponding value. + :param str key: The key to pop. + :param any default: The value to return if key is not in the dictionary + :returns: The value corresponding to the key. + :rtype: any + :raises KeyError: If key is not found and default is not given. + """ if default is _UNSET: return self._data.pop(key) return self._data.pop(key, default) def popitem(self) -> typing.Tuple[str, typing.Any]: + """ + Removes and returns some (key, value) pair + :returns: The (key, value) pair. + :rtype: tuple + :raises KeyError: if D is empty. + """ return self._data.popitem() def clear(self) -> None: + """ + Remove all items from D. + """ self._data.clear() def update(self, *args: typing.Any, **kwargs: typing.Any) -> None: + """ + Updates D from mapping/iterable E and F. + :param any args: Either a mapping object or an iterable of key-value pairs. + """ self._data.update(*args, **kwargs) @typing.overload @@ -417,6 +458,13 @@ def setdefault(self, key: str, default: None = None) -> None: ... def setdefault(self, key: str, default: typing.Any) -> typing.Any: ... def setdefault(self, key: str, default: typing.Any = _UNSET) -> typing.Any: + """ + Same as calling D.get(k, d), and setting D[k]=d if k not found + :param str key: The key to look up. + :param any default: The value to set if key is not in the dictionary + :returns: D[k] if k in D, else d. + :rtype: any + """ if default is _UNSET: return self._data.setdefault(key) return self._data.setdefault(key, default) @@ -910,6 +958,19 @@ def _failsafe_deserialize( return None +def _failsafe_deserialize_xml( + deserializer: typing.Any, + value: typing.Any, +) -> typing.Any: + try: + return _deserialize_xml(deserializer, value) + except DeserializationError: + _LOGGER.warning( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + class _RestField: def __init__( self, diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_operations/_operations.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_operations/_operations.py index b99470e7facc..4d1d62b78503 100644 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_operations/_operations.py +++ b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_operations/_operations.py @@ -5,7 +5,7 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import json # pylint: disable=unused-import +import json import sys from typing import Any, Callable, Dict, Iterable, Iterator, List, Optional, TypeVar import urllib.parse @@ -26,7 +26,7 @@ from azure.core.tracing.decorator import distributed_trace from azure.core.utils import case_insensitive_dict -from .._model_base import SdkJSONEncoder, _deserialize # pylint: disable=unused-import +from .._model_base import SdkJSONEncoder, _deserialize from .._serialization import Serializer from .._vendor import SchemaRegistryClientMixinABC @@ -271,7 +271,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[str], deserialized["Value"]) + list_of_elem = _deserialize(List[str], deserialized.get("Value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("NextLink") or None, iter(list_of_elem) @@ -367,7 +367,7 @@ def prepare_request(next_link=None): def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[int], deserialized["Value"]) + list_of_elem = _deserialize(List[int], deserialized.get("Value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("NextLink") or None, iter(list_of_elem) diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_operations/_patch.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_operations/_patch.py index 4c620652d9b2..8bcb627aa475 100644 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_operations/_patch.py +++ b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_operations/_patch.py @@ -1,285 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List, IO, Any, TYPE_CHECKING, Optional +from typing import List -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict -from azure.core.tracing.decorator import distributed_trace - -from ._operations import ( - ClsType, - SchemaRegistryClientOperationsMixin as GeneratedClientOperationsMixin, -) -from .._serialization import Serializer - -if TYPE_CHECKING: - from azure.core.pipeline import PipelineResponse - -_SERIALIZER = Serializer() - - -def build_schema_registry_get_schema_properties_by_content_request( # pylint: disable=name-too-long - group_name: str, schema_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/$schemaGroups/{groupName}/schemas/{schemaName}:get-id" - path_format_arguments = { - "groupName": _SERIALIZER.url("group_name", group_name, "str"), - "schemaName": _SERIALIZER.url("schemaName", schema_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_schema_registry_register_schema_request( # pylint: disable=name-too-long - group_name: str, schema_name: str, **kwargs: Any -) -> HttpRequest: - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type: str = kwargs.pop("content_type") - api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2022-10")) - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/$schemaGroups/{groupName}/schemas/{schemaName}" - path_format_arguments = { - "groupName": _SERIALIZER.url("group_name", group_name, "str"), - "schemaName": _SERIALIZER.url("name", schema_name, "str"), - } - - _url: str = _url.format(**path_format_arguments) # type: ignore - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _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) - - -class SchemaRegistryClientOperationsMixin(GeneratedClientOperationsMixin): - """ - Implement custom operations. - """ - - @distributed_trace - def _get_schema_properties_by_content( # type: ignore[override] # pylint: disable=inconsistent-return-statements - self, - group_name: str, - schema_name: str, - schema_content: IO, - *, - content_type: Optional[str] = None, - stream: bool = False, - **kwargs: Any - ) -> None: - """Get properties for existing schema. - - Gets the properties referencing an existing schema within the specified schema group, as matched by - schema content comparison. - - :param group_name: Name of schema group. Required. - :type group_name: str - :param schema_name: Name of schema. Required. - :type schema_name: str - :param schema_content: String representation (UTF-8) of the registered schema. Required. - :type schema_content: IO - :keyword content_type: The content type for given schema. If None, value will be set to "text/plain; - charset=utf-8". - :paramtype content_type: str or None - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 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: str = content_type or _headers.pop("Content-Type", "text/plain; charset=utf-8") - cls: ClsType[None] = kwargs.pop("cls", None) - - _content = schema_content - - request = build_schema_registry_get_schema_properties_by_content_request( - group_name=group_name, - schema_name=schema_name, - content_type=_content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "fullyQualifiedNamespace": self._serialize.url( - "self._config.fully_qualified_namespace", - self._config.fully_qualified_namespace, - "str", - skip_quote=True, - ), - } - request.url = self._client.format_url(request.url, **path_format_arguments) - - _stream = stream - 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 _stream: - response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Schema-Id"] = self._deserialize("str", response.headers.get("Schema-Id")) - response_headers["Schema-Id-Location"] = self._deserialize("str", response.headers.get("Schema-Id-Location")) - response_headers["Schema-Group-Name"] = self._deserialize("str", response.headers.get("Schema-Group-Name")) - response_headers["Schema-Name"] = self._deserialize("str", response.headers.get("Schema-Name")) - response_headers["Schema-Version"] = self._deserialize("int", response.headers.get("Schema-Version")) - - if cls: - return cls(pipeline_response, None, response_headers) - - @distributed_trace - def _register_schema( # type: ignore[override] # pylint: disable=inconsistent-return-statements - self, - group_name: str, - schema_name: str, - schema_content: IO, - *, - content_type: Optional[str] = None, - stream: bool = False, - **kwargs: Any - ) -> None: - """Register new schema. - - Register new schema. If schema of specified name does not exist in specified group, schema is - created at version 1. If schema of specified name exists already in specified group, schema is - created at latest version + 1. - - :param group_name: Name of schema group. Required. - :type group_name: str - :param schema_name: Name of schema. Required. - :type schema_name: str - :param schema_content: String representation (UTF-8) of the schema. Required. - :type schema_content: IO - :keyword content_type: The content type for given schema. If None, value will be "text/plain; - charset=utf-8". - :paramtype content_type: str or None - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 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: str = content_type or _headers.pop("Content-Type", "text/plain; charset=utf-8") - cls: ClsType[None] = kwargs.pop("cls", None) - - _content = schema_content - - request = build_schema_registry_register_schema_request( - group_name=group_name, - schema_name=schema_name, - content_type=_content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "fullyQualifiedNamespace": self._serialize.url( - "self._config.fully_qualified_namespace", - self._config.fully_qualified_namespace, - "str", - skip_quote=True, - ), - } - request.url = self._client.format_url(request.url, **path_format_arguments) - - _stream = stream - 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 _stream: - response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Schema-Id"] = self._deserialize("str", response.headers.get("Schema-Id")) - response_headers["Schema-Id-Location"] = self._deserialize("str", response.headers.get("Schema-Id-Location")) - response_headers["Schema-Group-Name"] = self._deserialize("str", response.headers.get("Schema-Group-Name")) - response_headers["Schema-Name"] = self._deserialize("str", response.headers.get("Schema-Name")) - response_headers["Schema-Version"] = self._deserialize("int", response.headers.get("Schema-Version")) - - if cls: - return cls(pipeline_response, None, response_headers) - - -__all__: List[str] = [ - "SchemaRegistryClientOperationsMixin", -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_patch.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_patch.py index e181e0672a76..8bcb627aa475 100644 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_patch.py +++ b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_patch.py @@ -1,560 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from __future__ import annotations -from functools import partial -from typing import ( - cast, - Tuple, - Mapping, - Dict, - TYPE_CHECKING, - Iterator, - AsyncIterator, - Union, - List, - Any, - overload, - IO, -) -from enum import Enum -from typing_extensions import Protocol, TypedDict, Self -from azure.core import CaseInsensitiveEnumMeta -from azure.core.tracing.decorator import distributed_trace +from typing import List -from ._client import SchemaRegistryClient as GeneratedServiceClient -from .models._patch import SchemaFormat, NormalizedSchemaContentTypes - -if TYPE_CHECKING: - from azure.core.credentials import TokenCredential - from azure.core.pipeline import PipelineResponse - from azure.core.rest import HttpResponse, AsyncHttpResponse - - class SchemaPropertiesDict(TypedDict): # needed for use with spread operator - """ - Typing for SchemaProperties dict. - """ - - id: str - format: "SchemaFormat" - group_name: str - name: str - version: int - - -###### Response Handlers ###### - - -def _parse_schema_properties_dict(response_headers: Mapping[str, Union[str, int]]) -> Dict[str, Union[str, int]]: - return { - "id": response_headers["Schema-Id"], - "group_name": response_headers["Schema-Group-Name"], - "name": response_headers["Schema-Name"], - "version": int(response_headers["Schema-Version"]), - } - - -def _normalize_content_type(content_type: str) -> str: - return content_type.replace(" ", "").lower() - - -def _get_format(content_type: str) -> Union[SchemaFormat, str]: - # Exception cases may be due to forward compatibility. - # i.e. Getting a schema with a content type from a future API version. - # In this case, we default to returning the content type string. - - # remove whitespace and case from string - normalized_content_type = _normalize_content_type(content_type) - if normalized_content_type == NormalizedSchemaContentTypes.AVRO.value: - return SchemaFormat.AVRO - if normalized_content_type == NormalizedSchemaContentTypes.JSON.value: - return SchemaFormat.JSON - if normalized_content_type == NormalizedSchemaContentTypes.CUSTOM.value: - return SchemaFormat.CUSTOM - return content_type - - -def prepare_schema_properties_result( # pylint:disable=unused-argument,redefined-builtin - format: str, - pipeline_response: "PipelineResponse", - deserialized: Union[Iterator[bytes], AsyncIterator[bytes]], - response_headers: Mapping[str, Union[str, int]], -) -> Dict[str, Union[str, int]]: - properties_dict = _parse_schema_properties_dict(response_headers) - properties_dict["format"] = SchemaFormat(format) - pipeline_response.http_response.raise_for_status() - return properties_dict - - -def prepare_schema_result( # pylint:disable=unused-argument - pipeline_response: "PipelineResponse", - deserialized: Union[Iterator[bytes], AsyncIterator[bytes]], - response_headers: Mapping[str, Union[str, int]], -) -> Tuple[Union["HttpResponse", "AsyncHttpResponse"], Dict[str, Union[int, str]]]: - properties_dict = _parse_schema_properties_dict(response_headers) - # re-generate after multi-content type response fix: https://github.com/Azure/autorest.python/issues/2122 - properties_dict["format"] = _get_format(cast(str, response_headers.get("Content-Type"))) - pipeline_response.http_response.raise_for_status() - return pipeline_response.http_response, properties_dict - - -###### Request Helper Functions ###### - - -def get_http_request_kwargs(kwargs): - http_request_keywords = ["params", "headers", "json", "data", "files"] - http_request_kwargs = {key: kwargs.pop(key, None) for key in http_request_keywords if key in kwargs} - return http_request_kwargs - - -def get_content_type(format: str): # pylint:disable=redefined-builtin - if format.lower() == SchemaFormat.CUSTOM.value.lower(): - return "text/plain; charset=utf-8" - return f"application/json; serialization={format}" - - -def get_case_insensitive_format(format: Union[str, SchemaFormat]) -> str: # pylint:disable=redefined-builtin - try: - format = cast(SchemaFormat, format) - format = format.value - except AttributeError: - pass - return format.capitalize() - - -###### Wrapper Class ###### - - -class SchemaRegistryClient: - """ - SchemaRegistryClient is a client for registering and retrieving schemas from the - Azure Schema Registry service. - - :param str fully_qualified_namespace: The Schema Registry service fully qualified host name. - For example: my-namespace.servicebus.windows.net. - :param credential: To authenticate managing the entities of the SchemaRegistry namespace. - :type credential: ~azure.core.credentials.TokenCredential - :keyword str api_version: The Schema Registry service API version to use for requests. - Default value is "2022-10". - - .. admonition:: Example: - - .. literalinclude:: ../samples/sync_samples/sample_code_schemaregistry.py - :start-after: [START create_sr_client_sync] - :end-before: [END create_sr_client_sync] - :language: python - :dedent: 4 - :caption: Create a new instance of the SchemaRegistryClient. - - """ - - def __init__(self, fully_qualified_namespace: str, credential: TokenCredential, **kwargs: Any) -> None: - # using composition (not inheriting from generated client) to allow - # calling different operations conditionally within one method - self._generated_client = GeneratedServiceClient( - fully_qualified_namespace=fully_qualified_namespace, - credential=credential, - **kwargs, - ) - - def __enter__(self) -> Self: - self._generated_client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._generated_client.__exit__(*exc_details) - - def close(self) -> None: - """This method is to close the sockets opened by the client. - It need not be used when using with a context manager. - """ - self._generated_client.close() - - @distributed_trace - def register_schema( - self, - group_name: str, - name: str, - definition: str, - format: Union[str, SchemaFormat], # pylint:disable=redefined-builtin - **kwargs: Any, - ) -> SchemaProperties: - """ - Register new schema. If schema of specified name does not exist in specified group, - schema is created at version 1. If schema of specified name exists already in specified group, - schema is created at latest version + 1. - - :param str group_name: Schema group under which schema should be registered. - :param str name: Name of schema being registered. - :param str definition: String representation of the schema being registered. - :param format: Format for the schema being registered. - :type format: Union[str, SchemaFormat] - :return: The SchemaProperties associated with the registered schema. - :rtype: ~azure.schemaregistry.SchemaProperties - :raises: :class:`~azure.core.exceptions.HttpResponseError` - - .. admonition:: Example: - - .. literalinclude:: ../samples/sync_samples/sample_code_schemaregistry.py - :start-after: [START register_schema_sync] - :end-before: [END register_schema_sync] - :language: python - :dedent: 4 - :caption: Register a new schema. - - """ - format = get_case_insensitive_format(format) - http_request_kwargs = get_http_request_kwargs(kwargs) - # ignoring return type because the generated client operations are not annotated w/ cls return type - schema_properties: Dict[str, Union[int, str]] = ( - self._generated_client._register_schema( # type:ignore # pylint:disable=protected-access - group_name=group_name, - schema_name=name, - schema_content=cast(IO[Any], definition), - content_type=kwargs.pop("content_type", get_content_type(format)), - cls=partial(prepare_schema_properties_result, format), - **http_request_kwargs, - ) - ) - properties = cast("SchemaPropertiesDict", schema_properties) - return SchemaProperties(**properties) - - @overload - def get_schema(self, schema_id: str, **kwargs: Any) -> Schema: - """Gets a registered schema. - - To get a registered schema by its unique ID, pass the `schema_id` parameter and any optional - keyword arguments. Azure Schema Registry guarantees that ID is unique within a namespace. - - WARNING: If retrieving a schema format that is unsupported by this client version, upgrade to a client - version that supports the schema format. Otherwise, the content MIME type string will be returned as - the `format` value in the `properties` of the returned Schema. - - :param str schema_id: References specific schema in registry namespace. Required if `group_name`, - `name`, and `version` are not provided. - :return: The schema stored in the registry associated with the provided arguments. - :rtype: ~azure.schemaregistry.Schema - :raises: :class:`~azure.core.exceptions.HttpResponseError` - - .. admonition:: Example: - - .. literalinclude:: ../samples/sync_samples/sample_code_schemaregistry.py - :start-after: [START get_schema_sync] - :end-before: [END get_schema_sync] - :language: python - :dedent: 4 - :caption: Get schema by id. - - """ - ... - - @overload - def get_schema(self, *, group_name: str, name: str, version: int, **kwargs: Any) -> Schema: - """Gets a registered schema. - - To get a specific version of a schema within the specified schema group, pass in the required - keyword arguments `group_name`, `name`, and `version` and any optional keyword arguments. - - WARNING: If retrieving a schema format that is unsupported by this client version, upgrade to a client - version that supports the schema format. Otherwise, the content MIME type string will be returned as - the `format` value in the `properties` of the returned Schema. - - :keyword str group_name: Name of schema group that contains the registered schema. - :keyword str name: Name of schema which should be retrieved. - :keyword int version: Version of schema which should be retrieved. - :return: The schema stored in the registry associated with the provided arguments. - :rtype: ~azure.schemaregistry.Schema - :raises: :class:`~azure.core.exceptions.HttpResponseError` - - .. admonition:: Example: - - .. literalinclude:: ../samples/sync_samples/sample_code_schemaregistry.py - :start-after: [START get_schema_by_version_sync] - :end-before: [END get_schema_by_version_sync] - :language: python - :dedent: 4 - :caption: Get schema by version. - """ - ... - - @distributed_trace - def get_schema( # pylint: disable=docstring-missing-param,docstring-should-be-keyword,docstring-keyword-should-match-keyword-only - self, *args: str, **kwargs: Any - ) -> Schema: - """Gets a registered schema. There are two ways to call this method: - - 1) To get a registered schema by its unique ID, pass the `schema_id` parameter and any optional - keyword arguments. Azure Schema Registry guarantees that ID is unique within a namespace. - - 2) To get a specific version of a schema within the specified schema group, pass in the required - keyword arguments `group_name`, `name`, and `version` and any optional keyword arguments. - - WARNING: If retrieving a schema format that is unsupported by this client version, upgrade to a client - version that supports the schema format. Otherwise, the content MIME type string will be returned as - the `format` value in the `properties` of the returned Schema. - - :param str schema_id: References specific schema in registry namespace. Required if `group_name`, - `name`, and `version` are not provided. - :keyword str group_name: Name of schema group that contains the registered schema. - :keyword str name: Name of schema which should be retrieved. - :keyword int version: Version of schema which should be retrieved. - :return: The schema stored in the registry associated with the provided arguments. - :rtype: ~azure.schemaregistry.Schema - :raises: :class:`~azure.core.exceptions.HttpResponseError` - - .. admonition:: Example: - - .. literalinclude:: ../samples/sync_samples/sample_code_schemaregistry.py - :start-after: [START get_schema_sync] - :end-before: [END get_schema_sync] - :language: python - :dedent: 4 - :caption: Get schema by id. - - .. literalinclude:: ../samples/sync_samples/sample_code_schemaregistry.py - :start-after: [START get_schema_by_version_sync] - :end-before: [END get_schema_by_version_sync] - :language: python - :dedent: 4 - :caption: Get schema by version. - """ - http_request_kwargs = get_http_request_kwargs(kwargs) - http_response: "HttpResponse" - schema_properties: Dict[str, Union[int, str]] - try: - # Check positional args for schema_id. - # Else, check if schema_id was passed in with keyword. - try: - schema_id = args[0] - except IndexError: - schema_id = kwargs.pop("schema_id") - schema_id = cast(str, schema_id) - # ignoring return type because the generated client operations are not annotated w/ cls return type - ( - http_response, - schema_properties, - ) = self._generated_client._get_schema_by_id( # type:ignore # pylint:disable=protected-access - id=schema_id, - cls=prepare_schema_result, - headers={ # TODO: remove when multiple content types in response are supported - "Accept": """application/json; serialization=Avro, application/json; """ - """serialization=json, text/plain; charset=utf-8""" - }, - stream=True, - **http_request_kwargs, - ) - except KeyError: - # If group_name, name, and version aren't passed in as kwargs, raise error. - try: - group_name = kwargs.pop("group_name") - name = kwargs.pop("name") - version = kwargs.pop("version") - except KeyError: - raise TypeError( # pylint:disable=raise-missing-from - """Missing required argument(s). Specify either `schema_id` """ - """or `group_name`, `name`, `version.""" - ) - # ignoring return type because the generated client operations are not annotated w/ cls return type - http_response, schema_properties = self._generated_client._get_schema_by_version( # type: ignore # pylint:disable=protected-access - group_name=group_name, - schema_name=name, - schema_version=version, - cls=prepare_schema_result, - headers={ # TODO: remove when multiple content types in response are supported - "Accept": """application/json; serialization=Avro, application/json; """ - """serialization=json, text/plain; charset=utf-8""" - }, - stream=True, - **http_request_kwargs, - ) # type:ignore - http_response.read() - properties = cast("SchemaPropertiesDict", schema_properties) - return Schema( - definition=http_response.text(), - properties=SchemaProperties(**properties), - ) - - @distributed_trace - def get_schema_properties( - self, - group_name: str, - name: str, - definition: str, - format: Union[str, SchemaFormat], # pylint:disable=redefined-builtin - **kwargs: Any, - ) -> SchemaProperties: - """ - Gets the schema properties corresponding to an existing schema within the specified schema group, - as matched by schema definition comparison. - - :param str group_name: Schema group under which schema should be registered. - :param str name: Name of schema for which properties should be retrieved. - :param str definition: String representation of the schema for which properties should be retrieved. - :param format: Format for the schema for which properties should be retrieved. - :type format: Union[str, SchemaFormat] - :return: The SchemaProperties associated with the provided schema metadata. - :rtype: ~azure.schemaregistry.SchemaProperties - :raises: :class:`~azure.core.exceptions.HttpResponseError` - - .. admonition:: Example: - - .. literalinclude:: ../samples/sync_samples/sample_code_schemaregistry.py - :start-after: [START get_schema_id_sync] - :end-before: [END get_schema_id_sync] - :language: python - :dedent: 4 - :caption: Get schema id. - - """ - format = get_case_insensitive_format(format) - http_request_kwargs = get_http_request_kwargs(kwargs) - # ignoring return type because the generated client operations are not annotated w/ cls return type - schema_properties: Dict[str, Union[int, str]] = ( - self._generated_client._get_schema_properties_by_content( # type: ignore # pylint:disable=protected-access - group_name=group_name, - schema_name=name, - schema_content=cast(IO[Any], definition), - content_type=kwargs.pop("content_type", get_content_type(format)), - cls=partial(prepare_schema_properties_result, format), - **http_request_kwargs, - ) - ) # type:ignore - properties = cast("SchemaPropertiesDict", schema_properties) - return SchemaProperties(**properties) - - -class SchemaProperties: - """ - Meta properties of a schema. - - :ivar id: References specific schema in registry namespace. - :vartype id: str - :ivar format: Format for the schema being stored. - :vartype format: ~azure.schemaregistry.SchemaFormat - :ivar group_name: Schema group under which schema is stored. - :vartype group_name: str - :ivar name: Name of schema. - :vartype name: str - :ivar version: Version of schema. - :vartype version: int - """ - - def __init__(self, **kwargs: Any) -> None: - self.id: str = kwargs.pop("id") - self.format: SchemaFormat = kwargs.pop("format") - self.group_name: str = kwargs.pop("group_name") - self.name: str = kwargs.pop("name") - self.version: int = kwargs.pop("version") - - def __repr__(self) -> str: - return ( - f"SchemaProperties(id={self.id}, format={self.format}, " - f"group_name={self.group_name}, name={self.name}, version={self.version})"[:1024] - ) - - -class Schema: - """ - The schema content of a schema, along with id and meta properties. - - :ivar definition: The content of the schema. - :vartype definition: str - :ivar properties: The properties of the schema. - :vartype properties: SchemaProperties - """ - - def __init__(self, **kwargs: Any) -> None: - self.definition: str = kwargs.pop("definition") - self.properties: SchemaProperties = kwargs.pop("properties") - - def __repr__(self) -> str: - return f"Schema(definition={self.definition}, properties={self.properties})"[:1024] - - -# ApiVersion was added to a previously GA'd version. However, newer libraries should not -# accept ApiVersion enums and only take strings. Leaving this here for backwards compatibility. -class ApiVersion(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """ - Represents the Schema Registry API version to use for requests. - """ - - V2021_10 = "2021-10" - V2022_10 = "2022-10" - """This is the default version.""" - - -###### Encoder Protocols ###### - - -class SchemaContentValidate(Protocol): - # TODO: make __call__ a public API so that docs show, until then, keep below docstring - - """ - Callable protocol which validates content against provided schema. If invalid, raises Exception. - Else, returns None. - - :param mapping[str, any] schema: The schema to validate against. - :param mapping[str, any] content: The content to validate. - - :rtype: None - :returns: None if valid. - :raises: Exception if content is invalid against provided schema. - """ - - def __call__(self, schema: Mapping[str, Any], content: Mapping[str, Any]) -> None: - """ - Validates content against provided schema. If invalid, raises Exception. - Else, returns None. - - :param mapping[str, any] schema: The schema to validate against. - :param mapping[str, any] content: The content to validate. - - :rtype: None - :returns: None if valid. - :raises: Exception if content is invalid against provided schema. - """ - - -class MessageContent(TypedDict): - """A dict with required keys: - - `content`: bytes - - `content_type`: str - """ - - content: bytes - content_type: str - - -class OutboundMessageContent(Protocol): - """Protocol for classes that set content and content type values internally.""" - - @classmethod - def from_message_content(cls, content: bytes, content_type: str, **kwargs: Any) -> Self: - """Creates an object that is a subtype of OutboundMessageContent, given content type and - a content value to be set on the object. - - :param bytes content: The content value to be set as the body of the message. - :param str content_type: The content type to be set on the message. - :rtype: ~azure.schemaregistry.OutboundMessageContent - :returns: The OutboundMessageContent object with encoded content and content type. - """ - - -class InboundMessageContent(Protocol): - """Message Types that get content and content type values internally.""" - - def __message_content__(self) -> MessageContent: - """A MessageContent object, with `content` and `content_type` set to - the values of their respective properties on the InboundMessageContent object. - - :rtype: ~azure.schemaregistry.MessageContent - :returns: TypedDict of the content and content type from the InboundMessageContent object. - """ +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): @@ -564,15 +19,3 @@ def patch_sdk(): you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize """ - - -__all__: List[str] = [ - "SchemaRegistryClient", - "SchemaProperties", - "Schema", - "SchemaFormat", - "SchemaContentValidate", - "MessageContent", - "OutboundMessageContent", - "InboundMessageContent", -] # Add all objects you want publicly available to users at this package level diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_serialization.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_serialization.py index b24ab2885450..eb86ea23c965 100644 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_serialization.py +++ b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_serialization.py @@ -1,28 +1,10 @@ -# pylint: disable=too-many-lines +# pylint: disable=line-too-long,useless-suppression,too-many-lines +# coding=utf-8 # -------------------------------------------------------------------------- -# # Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- # pyright: reportUnnecessaryTypeIgnoreComment=false @@ -48,9 +30,7 @@ IO, Mapping, Callable, - TypeVar, MutableMapping, - Type, List, ) @@ -61,13 +41,13 @@ import xml.etree.ElementTree as ET import isodate # type: ignore +from typing_extensions import Self from azure.core.exceptions import DeserializationError, SerializationError from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") -ModelType = TypeVar("ModelType", bound="Model") JSON = MutableMapping[str, Any] @@ -185,73 +165,7 @@ def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], except NameError: _long_type = int - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0. - - :param datetime.datetime dt: The datetime - :returns: The offset - :rtype: datetime.timedelta - """ - return datetime.timedelta(0) - - def tzname(self, dt): - """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. - - :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 # type: ignore -except ImportError: # Python 2.7 - - class _FixedOffset(datetime.tzinfo): # type: ignore - """Fixed offset in minutes east from UTC. - Copy/pasted from Python doc - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset) -> None: - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc -except ImportError: - TZ_UTC = UTC() # type: ignore +TZ_UTC = datetime.timezone.utc _FLATTEN = re.compile(r"(? ModelType: + def deserialize(cls, data: Any, content_type: Optional[str] = None) -> Self: """Parse a str using the RestAPI syntax and return a model. :param str data: A str using RestAPI structure. JSON by default. :param str content_type: JSON by default, set application/xml if XML. :returns: An instance of this model - :raises: DeserializationError if something went wrong - :rtype: ModelType + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def from_dict( - cls: Type[ModelType], + cls, data: Any, key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, content_type: Optional[str] = None, - ) -> ModelType: + ) -> Self: """Parse a dict using given key extractor return a model. By default consider key @@ -479,8 +393,8 @@ def from_dict( :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 + :raises DeserializationError: if something went wrong + :rtype: Self """ deserializer = Deserializer(cls._infer_class_models()) deserializer.key_extractors = ( # type: ignore @@ -626,7 +540,7 @@ def _serialize( # pylint: disable=too-many-nested-blocks, too-many-branches, to :param object target_obj: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, dict - :raises: SerializationError if serialization fails. + :raises SerializationError: if serialization fails. :returns: The serialized data. """ key_transformer = kwargs.get("key_transformer", self.key_transformer) @@ -736,8 +650,8 @@ def body(self, data, data_type, **kwargs): :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None + :raises SerializationError: if serialization fails. + :raises ValueError: if data is None :returns: The serialized request body """ @@ -781,8 +695,8 @@ def url(self, name, data, data_type, **kwargs): :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 + :raises TypeError: if serialization fails. + :raises ValueError: if data is None """ try: output = self.serialize_data(data, data_type, **kwargs) @@ -805,8 +719,8 @@ def query(self, name, data, data_type, **kwargs): :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str, list - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None :returns: The serialized query parameter """ try: @@ -835,8 +749,8 @@ def header(self, name, data, data_type, **kwargs): :param object data: The data to be serialized. :param str data_type: The type to be serialized from. :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None + :raises TypeError: if serialization fails. + :raises ValueError: if data is None :returns: The serialized header """ try: @@ -855,9 +769,9 @@ def serialize_data(self, data, data_type, **kwargs): :param object data: The data to be serialized. :param str data_type: The type to be serialized from. - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. + :raises AttributeError: if required data is None. + :raises ValueError: if data is None + :raises SerializationError: if serialization fails. :returns: The serialized data. :rtype: str, int, float, bool, dict, list """ @@ -1192,7 +1106,7 @@ def serialize_rfc(attr, **kwargs): # pylint: disable=unused-argument :param Datetime attr: Object to be serialized. :rtype: str - :raises: TypeError if format invalid. + :raises TypeError: if format invalid. :return: serialized rfc """ try: @@ -1218,7 +1132,7 @@ def serialize_iso(attr, **kwargs): # pylint: disable=unused-argument :param Datetime attr: Object to be serialized. :rtype: str - :raises: SerializationError if format invalid. + :raises SerializationError: if format invalid. :return: serialized iso """ if isinstance(attr, str): @@ -1251,7 +1165,7 @@ def serialize_unix(attr, **kwargs): # pylint: disable=unused-argument :param Datetime attr: Object to be serialized. :rtype: int - :raises: SerializationError if format invalid + :raises SerializationError: if format invalid :return: serialied unix """ if isinstance(attr, int): @@ -1429,7 +1343,7 @@ def xml_key_extractor(attr, attr_desc, data): # pylint: disable=unused-argument # 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 + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( xml_name ) ) @@ -1488,7 +1402,7 @@ def __call__(self, target_obj, response_data, content_type=None): :param str target_obj: Target data type to deserialize to. :param requests.Response response_data: REST response object. :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. :rtype: object """ @@ -1502,7 +1416,7 @@ def _deserialize(self, target_obj, data): # pylint: disable=inconsistent-return :param str target_obj: Target data type to deserialize to. :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. :rtype: object """ @@ -1717,7 +1631,7 @@ def deserialize_data(self, data, data_type): # pylint: disable=too-many-return- :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. + :raises DeserializationError: if deserialization fails. :return: Deserialized object. :rtype: object """ @@ -1799,7 +1713,7 @@ def deserialize_object(self, attr, **kwargs): # pylint: disable=too-many-return :param dict attr: Dictionary to be deserialized. :return: Deserialized object. :rtype: dict - :raises: TypeError if non-builtin datatype encountered. + :raises TypeError: if non-builtin datatype encountered. """ if attr is None: return None @@ -1845,7 +1759,7 @@ def deserialize_basic(self, attr, data_type): # pylint: disable=too-many-return :param str data_type: deserialization data type. :return: Deserialized basic type. :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. + :raises TypeError: if string format is not valid. """ # If we're here, data is supposed to be a basic type. # If it's still an XML node, take the text @@ -1936,7 +1850,7 @@ def deserialize_bytearray(attr): :param str attr: response string to be deserialized. :return: Deserialized bytearray :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1949,7 +1863,7 @@ def deserialize_base64(attr): :param str attr: response string to be deserialized. :return: Deserialized base64 string :rtype: bytearray - :raises: TypeError if string format invalid. + :raises TypeError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1964,7 +1878,7 @@ def deserialize_decimal(attr): :param str attr: response string to be deserialized. :return: Deserialized decimal - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. :rtype: decimal """ if isinstance(attr, ET.Element): @@ -1982,7 +1896,7 @@ def deserialize_long(attr): :param str attr: response string to be deserialized. :return: Deserialized int :rtype: long or int - :raises: ValueError if string format invalid. + :raises ValueError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -1995,7 +1909,7 @@ def deserialize_duration(attr): :param str attr: response string to be deserialized. :return: Deserialized duration :rtype: TimeDelta - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -2013,7 +1927,7 @@ def deserialize_date(attr): :param str attr: response string to be deserialized. :return: Deserialized date :rtype: Date - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -2029,7 +1943,7 @@ def deserialize_time(attr): :param str attr: response string to be deserialized. :return: Deserialized time :rtype: datetime.time - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -2044,14 +1958,14 @@ def deserialize_rfc(attr): :param str attr: response string to be deserialized. :return: Deserialized RFC datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text try: parsed_date = email.utils.parsedate_tz(attr) # type: ignore date_obj = datetime.datetime( - *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + *parsed_date[:6], tzinfo=datetime.timezone(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) ) if not date_obj.tzinfo: date_obj = date_obj.astimezone(tz=TZ_UTC) @@ -2067,7 +1981,7 @@ def deserialize_iso(attr): :param str attr: response string to be deserialized. :return: Deserialized ISO datetime :rtype: Datetime - :raises: DeserializationError if string format invalid. + :raises DeserializationError: if string format invalid. """ if isinstance(attr, ET.Element): attr = attr.text @@ -2105,7 +2019,7 @@ def deserialize_unix(attr): :param int attr: Object to be serialized. :return: Deserialized datetime :rtype: Datetime - :raises: DeserializationError if format invalid + :raises DeserializationError: if format invalid """ if isinstance(attr, ET.Element): attr = int(attr.text) # type: ignore diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_version.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_version.py index 01a36609b978..95a5f0e6b3c2 100644 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_version.py +++ b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_version.py @@ -6,4 +6,4 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -VERSION = "1.3.1" +VERSION = "1.3.0b4" diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_operations/_operations.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_operations/_operations.py index c5118daaa3be..02c1fb70330c 100644 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_operations/_operations.py +++ b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_operations/_operations.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. @@ -5,7 +6,7 @@ # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -import json # pylint: disable=unused-import +import json import sys from typing import Any, AsyncIterable, AsyncIterator, Callable, Dict, List, Optional, TypeVar import urllib.parse @@ -27,7 +28,7 @@ from azure.core.tracing.decorator_async import distributed_trace_async from azure.core.utils import case_insensitive_dict -from ..._model_base import SdkJSONEncoder, _deserialize # pylint: disable=unused-import +from ..._model_base import SdkJSONEncoder, _deserialize from ..._operations._operations import ( build_schema_registry_get_schema_by_id_request, build_schema_registry_get_schema_by_version_request, @@ -116,7 +117,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[str], deserialized["Value"]) + list_of_elem = _deserialize(List[str], deserialized.get("Value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("NextLink") or None, AsyncList(list_of_elem) @@ -212,7 +213,7 @@ def prepare_request(next_link=None): async def extract_data(pipeline_response): deserialized = pipeline_response.http_response.json() - list_of_elem = _deserialize(List[int], deserialized["Value"]) + list_of_elem = _deserialize(List[int], deserialized.get("Value", [])) if cls: list_of_elem = cls(list_of_elem) # type: ignore return deserialized.get("NextLink") or None, AsyncList(list_of_elem) diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_operations/_patch.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_operations/_patch.py index 6e7284e992ea..8bcb627aa475 100644 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_operations/_patch.py +++ b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_operations/_patch.py @@ -1,226 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from typing import List, IO, Any, TYPE_CHECKING, Optional -from azure.core.tracing.decorator_async import distributed_trace_async +from typing import List -from azure.core.exceptions import ( - ClientAuthenticationError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError, - ResourceNotModifiedError, - map_error, -) -from azure.core.utils import case_insensitive_dict -from ..._operations._patch import ( - build_schema_registry_get_schema_properties_by_content_request, - build_schema_registry_register_schema_request, -) -from ._operations import ( - ClsType, - SchemaRegistryClientOperationsMixin as GeneratedClientOperationsMixin, -) - -if TYPE_CHECKING: - from azure.core.pipeline import PipelineResponse - - -class SchemaRegistryClientOperationsMixin(GeneratedClientOperationsMixin): - """ - Generated client to add custom methods. - """ - - @distributed_trace_async - async def _get_schema_properties_by_content( # type: ignore[override] - self, - group_name: str, - schema_name: str, - schema_content: IO, - *, - content_type: Optional[str] = None, - stream: bool = False, - **kwargs: Any - ) -> None: - """Get properties for existing schema. - - Gets the properties referencing an existing schema within the specified schema group, as matched by - schema content comparison. - - :param group_name: Name of schema group. Required. - :type group_name: str - :param schema_name: Name of schema. Required. - :type schema_name: str - :param schema_content: String representation (UTF-8) of the registered schema. Required. - :type schema_content: IO - :keyword content_type: The content type for given schema. If None, value will be "text/plain; - charset=utf-8". - :paramtype content_type: str or None - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 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: str = content_type or _headers.pop("Content-Type", "text/plain; charset=utf-8") - cls: ClsType[None] = kwargs.pop("cls", None) - - _content = schema_content - - request = build_schema_registry_get_schema_properties_by_content_request( - group_name=group_name, - schema_name=schema_name, - content_type=_content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "fullyQualifiedNamespace": self._serialize.url( - "self._config.fully_qualified_namespace", - self._config.fully_qualified_namespace, - "str", - skip_quote=True, - ), - } - request.url = self._client.format_url(request.url, **path_format_arguments) - - _stream = stream - 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]: - if _stream: - await response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Schema-Id"] = self._deserialize("str", response.headers.get("Schema-Id")) - response_headers["Schema-Id-Location"] = self._deserialize("str", response.headers.get("Schema-Id-Location")) - response_headers["Schema-Group-Name"] = self._deserialize("str", response.headers.get("Schema-Group-Name")) - response_headers["Schema-Name"] = self._deserialize("str", response.headers.get("Schema-Name")) - response_headers["Schema-Version"] = self._deserialize("int", response.headers.get("Schema-Version")) - - if cls: - return cls(pipeline_response, None, response_headers) - - @distributed_trace_async - async def _register_schema( # type: ignore[override] - self, - group_name: str, - schema_name: str, - schema_content: IO, - *, - content_type: Optional[str] = None, - stream: bool = False, - **kwargs: Any - ) -> None: - """Register new schema. - - Register new schema. If schema of specified name does not exist in specified group, schema is - created at version 1. If schema of specified name exists already in specified group, schema is - created at latest version + 1. - - :param group_name: Name of schema group. Required. - :type group_name: str - :param schema_name: Name of schema. Required. - :type schema_name: str - :param schema_content: String representation (UTF-8) of the schema. Required. - :type schema_content: IO - :keyword content_type: The content type for given schema. If None, value will be "text/plain; - charset=utf-8". - :paramtype content_type: str or None - :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You - will have to context manage the returned stream. - :return: None - :rtype: None - :raises ~azure.core.exceptions.HttpResponseError: - """ - error_map = { - 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: str = content_type or _headers.pop("Content-Type", "text/plain; charset=utf-8") - cls: ClsType[None] = kwargs.pop("cls", None) - - _content = schema_content - - request = build_schema_registry_register_schema_request( - group_name=group_name, - schema_name=schema_name, - content_type=_content_type, - api_version=self._config.api_version, - content=_content, - headers=_headers, - params=_params, - ) - path_format_arguments = { - "fullyQualifiedNamespace": self._serialize.url( - "self._config.fully_qualified_namespace", - self._config.fully_qualified_namespace, - "str", - skip_quote=True, - ), - } - request.url = self._client.format_url(request.url, **path_format_arguments) - - _stream = stream - 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]: - if _stream: - await response.read() # Load the body in memory and close the socket - map_error(status_code=response.status_code, response=response, error_map=error_map) - raise HttpResponseError(response=response) - - response_headers = {} - response_headers["Location"] = self._deserialize("str", response.headers.get("Location")) - response_headers["Schema-Id"] = self._deserialize("str", response.headers.get("Schema-Id")) - response_headers["Schema-Id-Location"] = self._deserialize("str", response.headers.get("Schema-Id-Location")) - response_headers["Schema-Group-Name"] = self._deserialize("str", response.headers.get("Schema-Group-Name")) - response_headers["Schema-Name"] = self._deserialize("str", response.headers.get("Schema-Name")) - response_headers["Schema-Version"] = self._deserialize("int", response.headers.get("Schema-Version")) - - if cls: - return cls(pipeline_response, None, response_headers) - - -__all__: List[str] = [ - "SchemaRegistryClientOperationsMixin" -] # Add all objects you want publicly available to users at this package level +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_patch.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_patch.py index 0eceb8d1b619..8bcb627aa475 100644 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_patch.py +++ b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/aio/_patch.py @@ -1,351 +1,15 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ -from __future__ import annotations -from typing import ( - List, - Any, - TYPE_CHECKING, - Union, - overload, - cast, - IO, - Dict, -) -from functools import partial -from typing_extensions import Self +from typing import List -from azure.core.tracing.decorator_async import distributed_trace_async - -from .._patch import ( - get_http_request_kwargs, - get_case_insensitive_format, - get_content_type, - Schema, - SchemaProperties, - prepare_schema_result, - prepare_schema_properties_result, -) -from ..models._patch import SchemaFormat -from ._client import SchemaRegistryClient as GeneratedServiceClient - -if TYPE_CHECKING: - from azure.core.credentials_async import AsyncTokenCredential - from azure.core.rest import AsyncHttpResponse - from .._patch import SchemaPropertiesDict - - -###### Wrapper Class ###### - - -class SchemaRegistryClient: - """ - SchemaRegistryClient is a client for registering and retrieving schemas from the Azure Schema Registry service. - - :param str fully_qualified_namespace: The Schema Registry service fully qualified host name. - For example: my-namespace.servicebus.windows.net. - :param credential: To authenticate managing the entities of the SchemaRegistry namespace. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword str api_version: The Schema Registry service API version to use for requests. - Default value is "2022-10". - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_code_schemaregistry_async.py - :start-after: [START create_sr_client_async] - :end-before: [END create_sr_client_async] - :language: python - :dedent: 4 - :caption: Create a new instance of the SchemaRegistryClient. - - """ - - def __init__( - self, - fully_qualified_namespace: str, - credential: "AsyncTokenCredential", - **kwargs: Any, - ) -> None: - # using composition (not inheriting from generated client) to allow - # calling different operations conditionally within one method - self._generated_client = GeneratedServiceClient( - fully_qualified_namespace=fully_qualified_namespace, - credential=credential, - **kwargs, - ) - - async def __aenter__(self) -> Self: - await self._generated_client.__aenter__() - return self - - async def __aexit__(self, *args: Any) -> None: - await self._generated_client.__aexit__(*args) - - async def close(self) -> None: - """This method is to close the sockets opened by the client. - It need not be used when using with a context manager. - """ - await self._generated_client.close() - - @distributed_trace_async - async def register_schema( - self, - group_name: str, - name: str, - definition: str, - format: Union[str, SchemaFormat], # pylint:disable=redefined-builtin - **kwargs: Any, - ) -> SchemaProperties: - """ - Register new schema. If schema of specified name does not exist in specified group, - schema is created at version 1. If schema of specified name exists already in specified group, - schema is created at latest version + 1. - - :param str group_name: Schema group under which schema should be registered. - :param str name: Name of schema being registered. - :param str definition: String representation of the schema being registered. - :param format: Format for the schema being registered. - :type format: Union[str, ~azure.schemaregistry.SchemaFormat] - :return: The SchemaProperties associated with the registered schema. - :rtype: ~azure.schemaregistry.SchemaProperties - :raises: :class:`~azure.core.exceptions.HttpResponseError` - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_code_schemaregistry_async.py - :start-after: [START register_schema_async] - :end-before: [END register_schema_async] - :language: python - :dedent: 4 - :caption: Register a new schema. - - """ - format = get_case_insensitive_format(format) - http_request_kwargs = get_http_request_kwargs(kwargs) - # ignoring return type because the generated client operations are not annotated w/ cls return type - schema_properties: Dict[str, Union[int, str]] = ( - await self._generated_client._register_schema( # type: ignore # pylint:disable=protected-access - group_name=group_name, - schema_name=name, - schema_content=cast(IO[Any], definition), - content_type=kwargs.pop("content_type", get_content_type(format)), - cls=partial(prepare_schema_properties_result, format), - **http_request_kwargs, - ) - ) - - properties = cast("SchemaPropertiesDict", schema_properties) - return SchemaProperties(**properties) - - @overload - async def get_schema(self, schema_id: str, **kwargs: Any) -> Schema: - """Gets a registered schema. - - To get a registered schema by its unique ID, pass the `schema_id` parameter and any optional - keyword arguments. Azure Schema Registry guarantees that ID is unique within a namespace. - - WARNING: If retrieving a schema format that is unsupported by this client version, upgrade to a client - version that supports the schema format. Otherwise, the content MIME type string will be returned as - the `format` value in the `properties` of the returned Schema. - - :param str schema_id: References specific schema in registry namespace. Required if `group_name`, - `name`, and `version` are not provided. - :return: The schema stored in the registry associated with the provided arguments. - :rtype: ~azure.schemaregistry.Schema - :raises: :class:`~azure.core.exceptions.HttpResponseError` - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_code_schemaregistry_async.py - :start-after: [START get_schema_async] - :end-before: [END get_schema_async] - :language: python - :dedent: 4 - :caption: Get schema by id. - - """ - ... - - @overload - async def get_schema(self, *, group_name: str, name: str, version: int, **kwargs: Any) -> Schema: - """Gets a registered schema. - - To get a specific version of a schema within the specified schema group, pass in the required - keyword arguments `group_name`, `name`, and `version` and any optional keyword arguments. - - WARNING: If retrieving a schema format that is unsupported by this client version, upgrade to a client - version that supports the schema format. Otherwise, the content MIME type string will be returned as - the `format` value in the `properties` of the returned Schema. - - :keyword str group_name: Name of schema group that contains the registered schema. - :keyword str name: Name of schema which should be retrieved. - :keyword int version: Version of schema which should be retrieved. - :return: The schema stored in the registry associated with the provided arguments. - :rtype: ~azure.schemaregistry.Schema - :raises: :class:`~azure.core.exceptions.HttpResponseError` - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_code_schemaregistry_async.py - :start-after: [START get_schema_by_version_async] - :end-before: [END get_schema_by_version_async] - :language: python - :dedent: 4 - :caption: Get schema by version. - """ - ... - - @distributed_trace_async - async def get_schema( # pylint: disable=docstring-missing-param,docstring-should-be-keyword,docstring-keyword-should-match-keyword-only - self, *args: str, **kwargs: Any - ) -> Schema: - """Gets a registered schema. There are two ways to call this method: - - 1) To get a registered schema by its unique ID, pass the `schema_id` parameter and any optional - keyword arguments. Azure Schema Registry guarantees that ID is unique within a namespace. - - 2) To get a specific version of a schema within the specified schema group, pass in the required - keyword arguments `group_name`, `name`, and `version` and any optional keyword arguments. - - WARNING: If retrieving a schema format that is unsupported by this client version, upgrade to a client - version that supports the schema format. Otherwise, the content MIME type string will be returned as - the `format` value in the `properties` of the returned Schema. - - :param str schema_id: References specific schema in registry namespace. Required if `group_name`, - `name`, and `version` are not provided. - :keyword str group_name: Name of schema group that contains the registered schema. - :keyword str name: Name of schema which should be retrieved. - :keyword int version: Version of schema which should be retrieved. - :return: The schema stored in the registry associated with the provided arguments. - :rtype: ~azure.schemaregistry.Schema - :raises: :class:`~azure.core.exceptions.HttpResponseError` - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_code_schemaregistry_async.py - :start-after: [START get_schema_async] - :end-before: [END get_schema_async] - :language: python - :dedent: 4 - :caption: Get schema by id. - - .. literalinclude:: ../samples/async_samples/sample_code_schemaregistry_async.py - :start-after: [START get_schema_by_version_async] - :end-before: [END get_schema_by_version_async] - :language: python - :dedent: 4 - :caption: Get schema by version. - """ - http_request_kwargs = get_http_request_kwargs(kwargs) - http_response: "AsyncHttpResponse" - schema_properties: Dict[str, Union[int, str]] - try: - # Check positional args for schema_id. - # Else, check if schema_id was passed in with keyword. - try: - schema_id = args[0] - except IndexError: - schema_id = kwargs.pop("schema_id") - schema_id = cast(str, schema_id) - # ignoring return type because the generated client operations are not annotated w/ cls return type - ( - http_response, - schema_properties, - ) = await self._generated_client._get_schema_by_id( # type: ignore # pylint:disable=protected-access - id=schema_id, - cls=prepare_schema_result, - headers={ # TODO: remove when multiple content types are supported - "Accept": """application/json; serialization=Avro, application/json; """ - """serialization=json, text/plain; charset=utf-8""" - }, - stream=True, - **http_request_kwargs, - ) - - except KeyError: - # If group_name, name, and version aren't passed in as kwargs, raise error. - try: - group_name = kwargs.pop("group_name") - name = kwargs.pop("name") - version = kwargs.pop("version") - except KeyError: - raise TypeError( # pylint:disable=raise-missing-from - """Missing required argument(s). Specify either `schema_id` """ - """or `group_name`, `name`, `version.""" - ) - # ignoring return type because the generated client operations are not annotated w/ cls return type - http_response, schema_properties = await self._generated_client._get_schema_by_version( # type: ignore # pylint:disable=protected-access - group_name=group_name, - schema_name=name, - schema_version=version, - cls=prepare_schema_result, - headers={ # TODO: remove when multiple content types are supported - "Accept": """application/json; serialization=Avro, application/json; """ - """serialization=json, text/plain; charset=utf-8""" - }, - stream=True, - **http_request_kwargs, - ) - - await http_response.read() - properties = cast("SchemaPropertiesDict", schema_properties) - return Schema( - definition=http_response.text(), - properties=SchemaProperties(**properties), - ) - - @distributed_trace_async - async def get_schema_properties( - self, - group_name: str, - name: str, - definition: str, - format: Union[str, SchemaFormat], # pylint:disable=redefined-builtin - **kwargs: Any, - ) -> SchemaProperties: - """ - Gets the schema properties corresponding to an existing schema within the specified schema group, - as matched by schema defintion comparison. - - :param str group_name: Schema group under which schema should be registered. - :param str name: Name of schema for which properties should be retrieved. - :param str definition: String representation of the schema for which properties should be retrieved. - :param format: Format for the schema for which properties should be retrieved. - :type format: Union[str, SchemaFormat] - :return: The SchemaProperties associated with the provided schema metadata. - :rtype: ~azure.schemaregistry.SchemaProperties - :raises: :class:`~azure.core.exceptions.HttpResponseError` - - .. admonition:: Example: - - .. literalinclude:: ../samples/async_samples/sample_code_schemaregistry_async.py - :start-after: [START get_schema_id_async] - :end-before: [END get_schema_id_async] - :language: python - :dedent: 4 - :caption: Get schema by id. - - """ - format = get_case_insensitive_format(format) - http_request_kwargs = get_http_request_kwargs(kwargs) - # ignoring return type because the generated client operations are not annotated w/ cls return type - schema_properties: Dict[str, Union[int, str]] = ( - await self._generated_client._get_schema_properties_by_content( # type: ignore # pylint:disable=protected-access - group_name=group_name, - schema_name=name, - schema_content=cast(IO[Any], definition), - content_type=kwargs.pop("content_type", get_content_type(format)), - cls=partial(prepare_schema_properties_result, format), - **http_request_kwargs, - ) - ) - properties = cast("SchemaPropertiesDict", schema_properties) - return SchemaProperties(**properties) +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level def patch_sdk(): @@ -355,8 +19,3 @@ def patch_sdk(): you can't accomplish using the techniques described in https://aka.ms/azsdk/python/dpcodegen/python/customize """ - - -__all__: List[str] = [ - "SchemaRegistryClient", -] # Add all objects you want publicly available to users at this package level diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/__init__.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/__init__.py deleted file mode 100644 index 80f86cb969ec..000000000000 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/__init__.py +++ /dev/null @@ -1,26 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/__init__.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/__init__.py deleted file mode 100644 index 6a3cd6679330..000000000000 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/__init__.py +++ /dev/null @@ -1,36 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from ._version import VERSION - -__version__ = VERSION - -from ._schema_registry_json_encoder import ( - JsonSchemaEncoder, -) -from ._exceptions import InvalidContentError - - -__all__ = ["JsonSchemaEncoder", "InvalidContentError"] diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_constants.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_constants.py deleted file mode 100644 index 6ae93df1712d..000000000000 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_constants.py +++ /dev/null @@ -1,27 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -JSON_MIME_TYPE = "application/json;serialization=Json" diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_exceptions.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_exceptions.py deleted file mode 100644 index d301978eed94..000000000000 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_exceptions.py +++ /dev/null @@ -1,44 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from typing import Any, Dict, Optional - - -class InvalidContentError(ValueError): - """Error during encoding or decoding content with a schema. - - :param str message: The message object stringified as 'message' attribute - :keyword dict[str, str] or None details: The error details. Depending on the error, this may include - information like: `schema_id`, `schema_definition`, `message_content`. - - :ivar str message: A stringified version of the message parameter - :ivar dict[str, str] details: The error details. Depending on the error, this may include - information like: `schema_id`, `schema_definition`, `message_content`. - """ - - def __init__(self, message: str, *args: Any, details: Optional[Dict[str, str]] = None) -> None: - self.message: str = str(message) - self.details: Dict[str, str] = details or {} - super(InvalidContentError, self).__init__(self.message, *args) diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_schema_registry_json_encoder.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_schema_registry_json_encoder.py deleted file mode 100644 index 870a80059dfe..000000000000 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_schema_registry_json_encoder.py +++ /dev/null @@ -1,382 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from __future__ import annotations -import logging -import json -from functools import lru_cache -from typing import ( - TYPE_CHECKING, - Any, - cast, - Dict, - Mapping, - Optional, - Type, - overload, - Union, -) -from ..._patch import SchemaFormat -from ._utils import ( - create_message_content, - parse_message, - decode_content, - get_loaded_schema, - get_jsonschema_validator, - InboundMessageContent, - OutboundMessageContent, -) - -if TYPE_CHECKING: - import azure.schemaregistry - from ..._patch import MessageContent, SchemaContentValidate - -_LOGGER = logging.getLogger(__name__) - - -class JsonSchemaEncoder(object): - """ - JsonSchemaEncoder provides the ability to encode and decode content according to the given JSON schema. - It will check the registry for the pre-registered schema and cache the schema locally. - - :keyword client: Required. The schema registry client which is used to retrieve schema from the service. - :paramtype client: ~azure.schemaregistry.SchemaRegistryClient - :keyword validate: Required. Used for validation in encode and decode. - If a JSON Schema meta-schema `$schema` string is provided, for example - `"https://json-schema.org/draft/2020-12/schema"`, the corresponding validator from `jsonschema` will be used. - In this case, `jsonschema` must be installed with `jsonencoder` extras: - `pip install azure-schemaregistry[jsonencoder]`. For a list of supported `jsonschema` validators, - please refer to the `jsonschema` documentation: - https://python-jsonschema.readthedocs.io/en/stable/api/jsonschema/validators/index.html - If a callable is provided, the schema and content will be passed in for validation. - :paramtype validate: str or ~azure.schemaregistry.SchemaContentValidate - :keyword Optional[str] group_name: Schema group under which schema should be registered. - Required if `schema`, not `schema_id`, is provided to `encode`. - """ - - def __init__( - self, - *, - client: "azure.schemaregistry.SchemaRegistryClient", - validate: Union[str, "SchemaContentValidate"], - group_name: Optional[str] = None, - ) -> None: - self._schema_registry_client = client - if isinstance(validate, str): - self._validate = get_jsonschema_validator(validate) - else: - self._validate = validate - self._schema_group = group_name - - def __enter__(self) -> "JsonSchemaEncoder": - self._schema_registry_client.__enter__() - return self - - def __exit__(self, *exc_details: Any) -> None: - self._schema_registry_client.__exit__(*exc_details) - - def close(self) -> None: - """This method is to close the sockets opened by the client. - It need not be used when using with a context manager. - """ - self._schema_registry_client.close() - - @lru_cache(maxsize=128) - def _get_schema_id(self, schema_name: str, schema_str: str, **kwargs: Any) -> str: - """ - Get schema id from local cache with the given schema. - If there is no item in the local cache, get schema id from the service and cache it. - - :param schema_name: Name of the schema - :type schema_name: str - :param str schema_str: Schema string - :return: Schema Id - :rtype: str - """ - schema_id = self._schema_registry_client.get_schema_properties( - cast(str, self._schema_group), - schema_name, - schema_str, - SchemaFormat.JSON.value, - **kwargs, - ).id - return schema_id - - @lru_cache(maxsize=128) - def _get_schema(self, schema_id: str, **kwargs: Any) -> str: - """ - Get schema content from local cache with the given schema id. - If there is no item in the local cache, get schema from the service and cache it. - - :param str schema_id: Schema id - :return: Schema content - :rtype: str - """ - schema_str = self._schema_registry_client.get_schema(schema_id, **kwargs).definition - return schema_str - - @overload - def encode( - self, - content: Mapping[str, Any], - *, - schema: str, - message_type: Type[OutboundMessageContent], - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> OutboundMessageContent: - """Encodes content after validating against the pre-registered JSON schema. Encoded content and content - type will be passed to the provided OutboundMessageContent class to create the message object. - - If `message_type` is set, then additional keyword arguments for building the OutboundMessageContent object - will be passed to the OutboundMessageContent.from_message_content() method. - - :param content: The content to be encoded. - :type content: mapping[str, any] - :keyword schema: Required. The pre-registered schema used to validate the content. `schema_id` - must not be passed. - :paramtype schema: str - :keyword message_type: The message class to construct the message. Must be a subtype of the - azure.schemaregistry.OutboundMessageContent protocol. - :paramtype message_type: type[OutboundMessageContent] - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: The OutboundMessageContent object with encoded content and content type. - :rtype: OutboundMessageContent - :raises: ~azure.schemaregistry.encoder.InvalidContentError if there is an issue with encoding content - or validating it against the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - - @overload - def encode( - self, - content: Mapping[str, Any], - *, - schema_id: str, - message_type: Type[OutboundMessageContent], - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> OutboundMessageContent: - """Encodes content after validating against the pre-registered JSON schema corresponding to - the provided schema ID. Encoded content and content type will be passed to the provided - OutboundMessageContent class to create message object. - - If `message_type` is set, then additional keyword arguments for building the OutboundMessageContent object - will be passed to the OutboundMessageContent.from_message_content() method. - - :param content: The content to be encoded. - :type content: mapping[str, any] - :keyword schema_id: Required. The schema ID corresponding to the pre-registered schema to be used - for validation. `schema` must not be passed. - :paramtype schema_id: str - :keyword message_type: The message class to construct the message. Must be a subtype of the - azure.schemaregistry.OutboundMessageContent protocol. - :paramtype message_type: type[OutboundMessageContent] - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: The OutboundMessageContent object with encoded content and content type. - :rtype: OutboundMessageContent - :raises: ~azure.schemaregistry.encoder.InvalidContentError if there is an issue with encoding content - or validating it against the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - - @overload - def encode( - self, - content: Mapping[str, Any], - *, - schema: str, - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> "MessageContent": - """Encodes content after validating against the pre-registered schema. The following dict will be returned: - {"content": JSON encoded value, "content_type": JSON mime type string + schema ID}. - - :param content: The content to be encoded. - :type content: mapping[str, any] - :keyword schema: Required. The pre-registered schema used to validate the content. `schema_id` - must not be passed. - :paramtype schema: str - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: TypedDict of encoded content and content type. - :rtype: MessageContent - :raises: ~azure.schemaregistry.encoder.InvalidContentError if there is an issue with encoding content - or validating it against the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - - @overload - def encode( - self, - content: Mapping[str, Any], - *, - schema_id: str, - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> "MessageContent": - """Encodes content after validating against the pre-registered schema corresponding to - the provided schema ID. The following dict will be returned: - {"content": JSON encoded value, "content_type": JSON mime type string + schema ID}. - - :param content: The content to be encoded. - :type content: mapping[str, any] - :keyword schema_id: Required. The schema ID corresponding to the pre-registered schema to be used - for validation. `schema` must not be passed. - :paramtype schema_id: str - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: TypedDict of encoded content and content type. - :rtype: MessageContent - :raises: ~azure.schemaregistry.encoder.InvalidContentError if there is an issue with encoding content - or validating it against the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - - def encode( - self, - content: Mapping[str, Any], - *, - schema: Optional[str] = None, - schema_id: Optional[str] = None, - message_type: Optional[Type[OutboundMessageContent]] = None, - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> Union[OutboundMessageContent, "MessageContent"]: - """Encodes content after validating against the provided pre-registered schema or the one corresponding to - the provided schema ID. If provided with a OutboundMessageContent subtype, encoded content and - content type will be passed to create message object. If not provided, the following dict will be returned: - {"content": JSON encoded value, "content_type": JSON mime type string + schema ID}. - - If `message_type` is set, then additional keyword arguments for building OutboundMessageContent will be - passed to the OutboundMessageContent.from_message_content() method. - - :param content: The content to be encoded. - :type content: mapping[str, any] - :keyword schema: The pre-registered schema used to validate the content. Exactly one of - `schema` or `schema_id` must be passed. - :paramtype schema: str or None - :keyword schema_id: The schema ID corresponding to the pre-registered schema to be used - for validation. Exactly one of `schema` or `schema_id` must be passed. - :paramtype schema_id: str or None - :keyword message_type: The message class to construct the message. If passed, must be a subtype of the - azure.schemaregistry.OutboundMessageContent protocol. - :paramtype message_type: type[OutboundMessageContent] or None - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: TypedDict of encoded content and content type if `message_type` is not set, otherwise the - constructed message object. - :rtype: OutboundMessageContent or MessageContent - :raises: ~azure.schemaregistry.encoder.InvalidContentError if there is an issue with encoding content - or validating it against the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - request_options = request_options or {} - - # If schema_id, get schema for validation. If schema, get schema_id for content type. - if schema_id and not schema: - cache_misses = self._get_schema.cache_info().misses # pylint: disable=no-value-for-parameter - schema_str = self._get_schema(schema_id, **request_options) - new_cache_misses = self._get_schema.cache_info().misses # pylint: disable=no-value-for-parameter - if new_cache_misses > cache_misses: - cache_info = self._get_schema.cache_info() # pylint: disable=no-value-for-parameter - _LOGGER.info( - "New entry has been added to schema cache. Cache info: %s", - str(cache_info), - ) - schema_dict = json.loads(schema_str) - elif schema and not schema_id: - if not self._schema_group: - raise TypeError("'group_name' is required in constructor, if 'schema' is passed to encode.") - - schema_fullname, schema_str, schema_dict = get_loaded_schema(schema, content) - cache_misses = self._get_schema_id.cache_info().misses # pylint: disable=no-value-for-parameter - schema_id = self._get_schema_id(schema_fullname, schema_str, **request_options) - new_cache_misses = self._get_schema_id.cache_info().misses # pylint: disable=no-value-for-parameter - if new_cache_misses > cache_misses: - cache_info = self._get_schema_id.cache_info() # pylint: disable=no-value-for-parameter - _LOGGER.info( - "New entry has been added to schema ID cache. Cache info: %s", - str(cache_info), - ) - else: - raise TypeError("Exactly one of 'schema' or 'schema_id' is required.") - - return create_message_content( - content=content, - schema=schema_dict, - schema_id=schema_id, - validate=self._validate, - message_type=message_type, - **kwargs, - ) - - def decode( - self, - message: Union["MessageContent", InboundMessageContent], - *, - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> Dict[str, Any]: - """Decode bytes content using schema ID in the content type field. - - :param message: The message object which holds the content to be decoded and content type - containing the schema ID. - :type message: InboundMessageContent or MessageContent - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: The decoded content. - :rtype: dict[str, any] - :raises: ~azure.schemaregistry.encoder.jsonencoder.InvalidContentError if there is - an issue with decoding content or validating it with the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - schema_id, content = parse_message(message) - cache_misses = self._get_schema.cache_info().misses # pylint: disable=no-value-for-parameter - request_options = request_options or {} - schema_definition = self._get_schema(schema_id, **request_options) - new_cache_misses = self._get_schema.cache_info().misses # pylint: disable=no-value-for-parameter - if new_cache_misses > cache_misses: - cache_info = self._get_schema.cache_info() # pylint: disable=no-value-for-parameter - _LOGGER.info( - "New entry has been added to schema cache. Cache info: %s", - str(cache_info), - ) - - return decode_content( - content=content, - schema_id=schema_id, - schema_definition=schema_definition, - validate=self._validate, - **kwargs, - ) diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_utils.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_utils.py deleted file mode 100644 index 16583a88b3e0..000000000000 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_utils.py +++ /dev/null @@ -1,261 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -from typing import ( - Any, - Callable, - Optional, - Type, - Union, - cast, - Mapping, - TYPE_CHECKING, - Tuple, - TypeVar, - overload, -) -import json - -try: - import jsonschema -except ImportError: - jsonschema = None - -from functools import partial - - -from ..._patch import ( - MessageContent, - InboundMessageContent as InboundMessageContentProtocol, - OutboundMessageContent as OutboundMessageContentProtocol, -) -from ._exceptions import ( - InvalidContentError, -) -from ._constants import JSON_MIME_TYPE - -if TYPE_CHECKING: - try: - from jsonschema.protocols import Validator - except ImportError: - pass - from ..._patch import SchemaContentValidate - -# TypeVar ties the return type to the exact OutboundMessageContent/InboundMessageContent class, -# rather than the "OutboundMessageContent/InboundMessageContent" Protocol. -# Otherwise, mypy will complain that the return type is not compatible with the type annotation when -# the OutboundMessageContent/InboundMessageContent object is returned and passed around. -InboundMessageContent = TypeVar("InboundMessageContent", bound=InboundMessageContentProtocol) -OutboundMessageContent = TypeVar("OutboundMessageContent", bound=OutboundMessageContentProtocol) - - -def get_jsonschema_validator(draft_identifier: str) -> "Validator": - - # get validator - try: - validator = jsonschema.validators.validator_for({"$schema": draft_identifier}, default=False) - except AttributeError: - raise ValueError( - "To use a provided JSON Schema Validator, please install the " - "package with extras: `pip install azure-schemaregistry[jsonencoder]`." - ) from None - - if not validator: - raise ValueError( - f"{draft_identifier} is not a supported `jsonschema` meta-schema `$schema` value. " - "Please pass in a `$schema` value from the list of supported `jsonschema` validators: " - "https://python-jsonschema.readthedocs.io/en/stable/api/jsonschema/validators/index.html" - ) - - return partial(jsonschema_validate, validator=validator) - - -def jsonschema_validate(validator: "Validator", schema: Mapping[str, Any], content: Mapping[str, Any]) -> None: - """ - Validates content against provided schema using `jsonschema.Draft4Validator`. - If invalid, raises Exception. Else, returns None. - If jsonschema is not installed, raises ValueError. - :param jsonschema.protocols.Validator validator: The validator to use. - :param mapping[str, any] schema: The schema to validate against. - :param mapping[str, any] content: The content to validate. - :return: None - :rtype: None - """ - validator(schema).validate(content) - - -def get_loaded_schema( - schema: Union[str, Callable], - content: Mapping[str, Any], -) -> Tuple[str, str, Mapping[str, Any]]: - """Returns the tuple: (schema name, schema string, schema dict). - :param str or callable schema: The schema to load. - :param mapping[str, any] content: The content to validate. - :return: The schema name, schema string, and schema dict. - :rtype: tuple[str, str, mapping[str, any]] - """ - # get schema string - schema_dict: Mapping[str, Any] - schema_str: str - schema_fullname: str - try: - # str - schema = cast(str, schema) - schema_dict = json.loads(schema) - schema_str = schema - except TypeError: - # callable - schema = cast(Callable, schema) - try: - schema_dict = schema(content) - except Exception as exc: - raise InvalidContentError( - f"Cannot generate schema with callable given the following content: {content}" - ) from exc - schema_str = json.dumps(schema_dict) - - # get schema name for get_schema_properties operation - try: - schema_fullname = schema_dict["title"] - except KeyError: - raise ValueError("Schema must have 'title' property.") from None - - return schema_fullname, schema_str, schema_dict - - -@overload -def create_message_content( - content: Mapping[str, Any], - schema: Mapping[str, Any], - schema_id: str, - validate: "Validator", - message_type: Type[OutboundMessageContent], - **kwargs: Any, -) -> OutboundMessageContent: ... - - -@overload -def create_message_content( - content: Mapping[str, Any], - schema: Mapping[str, Any], - schema_id: str, - validate: "Validator", - message_type: None = None, -) -> MessageContent: ... - - -def create_message_content( - content: Mapping[str, Any], - schema: Mapping[str, Any], - schema_id: str, - validate: Union["Validator", "SchemaContentValidate"], - message_type: Optional[Type[OutboundMessageContent]] = None, - **kwargs: Any, -) -> Union[OutboundMessageContent, MessageContent]: - content_type = f"{JSON_MIME_TYPE}+{schema_id}" - try: - # validate content - validate(schema=schema, content=content) - except Exception as exc: - raise InvalidContentError( - f"Invalid content value '{content}' for the following schema with schema ID {schema_id}:" - f"{json.dumps(schema)}", - details={"schema_id": f"{schema_id}"}, - ) from exc - - try: - content_bytes = json.dumps(content, separators=(",", ":")).encode() - except Exception as exc: - raise InvalidContentError( - f"Cannot encode value '{content}' for the following schema with schema ID {schema_id}:" - f"{json.dumps(schema)}", - details={"schema_id": f"{schema_id}"}, - ) from exc - - if message_type: - try: - return cast( - OutboundMessageContent, - message_type.from_message_content(content_bytes, content_type, **kwargs), - ) - except AttributeError as exc: - raise TypeError( - f"""Cannot set content and content type on model object. The content model - {str(message_type)} must be a subtype of the OutboundMessageContent protocol. - If using an Azure SDK model class, please check the README.md for the full list - of supported Azure SDK models and their corresponding versions.""", - {"content": content_bytes, "content_type": content_type}, - ) from exc - - return MessageContent({"content": content_bytes, "content_type": content_type}) - - -def parse_message(message: Union[InboundMessageContent, MessageContent]): - try: - message = cast("InboundMessageContent", message) - message_content_dict = message.__message_content__() - content = message_content_dict["content"] - content_type = message_content_dict["content_type"] - except AttributeError: - message = cast(MessageContent, message) - try: - content = message["content"] - content_type = message["content_type"] - except (KeyError, TypeError) as exc: - raise TypeError( - f"""The content model {str(message)} must be a subtype of the InboundMessageContent protocol or type - MessageContent. If using an Azure SDK model class, please check the README.md - for the full list of supported Azure SDK models and their corresponding versions.""" - ) from exc - - try: - content_type_parts = content_type.split("+") - if len(content_type_parts) != 2 or content_type_parts[0] != JSON_MIME_TYPE: - raise InvalidContentError( - f"Content type {content_type} was not in the expected format of JSON MIME type + schema ID." - ) - schema_id = content_type_parts[1] - except AttributeError: - raise InvalidContentError( - f"Content type {content_type} was not in the expected format of JSON MIME type + schema ID." - ) from None - - return schema_id, content - - -def decode_content( - content: bytes, - schema_id: str, - schema_definition: str, - validate: Union["Validator", "SchemaContentValidate"], -): - try: - content = json.loads(content) - except Exception as exc: - error_message = f"""Cannot decode value '{content!r}' for schema - with schema ID {schema_id}: {schema_definition}""" - raise InvalidContentError( - error_message, - details={ - "schema_id": f"{schema_id}", - "schema_definition": f"{schema_definition}", - }, - ) from exc - try: - validate( - schema=json.loads(schema_definition), - content=cast(Mapping[str, Any], content), - ) - except Exception as exc: - error_message = f"""Invalid content value '{content!r}' for schema - with schema ID {schema_id}: {schema_definition}""" - raise InvalidContentError( - error_message, - details={ - "schema_id": f"{schema_id}", - "schema_definition": f"{schema_definition}", - }, - ) from exc - return content diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_version.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_version.py deleted file mode 100644 index d316addb36cb..000000000000 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/_version.py +++ /dev/null @@ -1,27 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -VERSION = "1.0.0b1" diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/__init__.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/__init__.py deleted file mode 100644 index 571f6a1c8318..000000000000 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/__init__.py +++ /dev/null @@ -1,30 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from ._schema_registry_json_encoder_async import ( - JsonSchemaEncoder, -) - -__all__ = ["JsonSchemaEncoder"] diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/_async_lru.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/_async_lru.py deleted file mode 100644 index ce4d1936eaa2..000000000000 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/_async_lru.py +++ /dev/null @@ -1,228 +0,0 @@ -# -------------------------------------------------------------------------- -# The MIT License -# -# Copyright (c) 2018 aio-libs team https://github.com/aio-libs/ -# Copyright (c) 2017 Ocean S. A. https://ocean.io/ -# Copyright (c) 2016-2017 WikiBusiness Corporation http://wikibusiness.org/ -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -# THE SOFTWARE. -# -------------------------------------------------------------------------- -# Copying over `async_lru.py`[https://github.com/aio-libs/async-lru/blob/master/async_lru.py] -# from `aio-libs`[https://github.com/aio-libs/async-lru] for the following reasons: -# 1. There has not been an official release of `async_lru` in 2 years. -# 2. The last update to the library was a year ago, so it seems the library is -# not being actively maintained. - -import asyncio -from collections import OrderedDict -from functools import _CacheInfo, _make_key, partial, wraps - - -__version__ = "1.0.2" - -__all__ = ("alru_cache",) - - -def unpartial(fn): - while hasattr(fn, "func"): - fn = fn.func - - return fn - - -def _done_callback(fut, task): - if task.cancelled(): - fut.cancel() - return - - exc = task.exception() - if exc is not None: - fut.set_exception(exc) - return - - fut.set_result(task.result()) - - -def _cache_invalidate(wrapped, typed, *args, **kwargs): - # pylint: disable=protected-access - key = _make_key(args, kwargs, typed) - - exists = key in wrapped._cache - - if exists: - wrapped._cache.pop(key) - - return exists - - -def _cache_clear(wrapped): - # pylint: disable=protected-access - wrapped.hits = wrapped.misses = 0 - wrapped._cache = OrderedDict() - wrapped.tasks = set() - - -def _open(wrapped): - if not wrapped.closed: - raise RuntimeError("alru_cache is not closed") - - # pylint: disable=protected-access - was_closed = wrapped.hits == wrapped.misses == len(wrapped.tasks) == len(wrapped._cache) == 0 - - if not was_closed: - raise RuntimeError("alru_cache was not closed correctly") - - wrapped.closed = False - - -def _close(wrapped, *, cancel=False, return_exceptions=True): - if wrapped.closed: - raise RuntimeError("alru_cache is closed") - - wrapped.closed = True - - if cancel: - for task in wrapped.tasks: - if not task.done(): # not sure is it possible - task.cancel() - - return _wait_closed(wrapped, return_exceptions=return_exceptions) - - -async def _wait_closed(wrapped, *, return_exceptions): - wait_closed = asyncio.gather(*wrapped.tasks, return_exceptions=return_exceptions) - - wait_closed.add_done_callback(partial(_close_waited, wrapped)) - - ret = await wait_closed - - # hack to get _close_waited callback to be executed - await asyncio.sleep(0) - - return ret - - -def _close_waited(wrapped, _): - wrapped.cache_clear() - - -def _cache_info(wrapped, maxsize): - # pylint: disable=protected-access - return _CacheInfo( - wrapped.hits, - wrapped.misses, - maxsize, - len(wrapped._cache), - ) - - -def __cache_touch(wrapped, key): - # pylint: disable=protected-access - try: - wrapped._cache.move_to_end(key) - except KeyError: # not sure is it possible - pass - - -def _cache_hit(wrapped, key): - wrapped.hits += 1 - __cache_touch(wrapped, key) - - -def _cache_miss(wrapped, key): - wrapped.misses += 1 - __cache_touch(wrapped, key) - - -def alru_cache( - fn=None, - maxsize=128, - typed=False, - *, - cache_exceptions=True, -): - def wrapper(fn): - # pylint: disable=protected-access - _origin = unpartial(fn) - - if not asyncio.iscoroutinefunction(_origin): - raise RuntimeError("Coroutine function is required, got {}".format(fn)) - - # functools.partialmethod support - if hasattr(fn, "_make_unbound_method"): - fn = fn._make_unbound_method() - - @wraps(fn) - async def wrapped(*fn_args, **fn_kwargs): - if wrapped.closed: - raise RuntimeError("alru_cache is closed for {}".format(wrapped)) - - loop = asyncio.get_event_loop() - - key = _make_key(fn_args, fn_kwargs, typed) - - fut = wrapped._cache.get(key) - - if fut is not None: - if not fut.done(): - _cache_hit(wrapped, key) - return await asyncio.shield(fut) - - exc = fut._exception - - if exc is None or cache_exceptions: - _cache_hit(wrapped, key) - return fut.result() - - # exception here and cache_exceptions == False - wrapped._cache.pop(key) - - fut = loop.create_future() - task = loop.create_task(fn(*fn_args, **fn_kwargs)) - task.add_done_callback(partial(_done_callback, fut)) - - wrapped.tasks.add(task) - task.add_done_callback(wrapped.tasks.remove) - - wrapped._cache[key] = fut - - if maxsize is not None and len(wrapped._cache) > maxsize: - wrapped._cache.popitem(last=False) - - _cache_miss(wrapped, key) - return await asyncio.shield(fut) - - _cache_clear(wrapped) - wrapped._origin = _origin - wrapped.closed = False - wrapped.cache_info = partial(_cache_info, wrapped, maxsize) - wrapped.cache_clear = partial(_cache_clear, wrapped) - wrapped.invalidate = partial(_cache_invalidate, wrapped, typed) - wrapped.close = partial(_close, wrapped) - wrapped.open = partial(_open, wrapped) - - return wrapped - - if fn is None: - return wrapper - - if callable(fn) or hasattr(fn, "_make_unbound_method"): - return wrapper(fn) - - raise NotImplementedError("{} decorating is not supported".format(fn)) diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/_schema_registry_json_encoder_async.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/_schema_registry_json_encoder_async.py deleted file mode 100644 index 020ba687cd62..000000000000 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/aio/_schema_registry_json_encoder_async.py +++ /dev/null @@ -1,388 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from __future__ import annotations -import json -import logging -from typing import ( - TYPE_CHECKING, - Any, - Dict, - Mapping, - Optional, - overload, - Type, - Union, - cast, -) -from ...._patch import SchemaFormat - -from .._utils import ( - create_message_content, - parse_message, - decode_content, - get_loaded_schema, - get_jsonschema_validator, - InboundMessageContent, - OutboundMessageContent, -) -from ._async_lru import alru_cache - -if TYPE_CHECKING: - import azure.schemaregistry.aio - from ...._patch import MessageContent, SchemaContentValidate - -_LOGGER = logging.getLogger(__name__) - - -class JsonSchemaEncoder(object): - """ - JsonSchemaEncoder provides the ability to encode and decode content according to the given JSON schema. - It will check the registry for the pre-registered schema and cache the schema locally. - - :keyword client: Required. The schema registry client which is used to retrieve schema from the service. - and retrieve schema from the service. - :paramtype client: ~azure.schemaregistry.aio.SchemaRegistryClient - :keyword validate: Required. Used for validation in encode and decode. - If a JSON Schema meta-schema `$schema` string is provided, for example - `"https://json-schema.org/draft/2020-12/schema"`, the corresponding validator from `jsonschema` will be used. - In this case, `jsonschema` must be installed with `jsonencoder` extras: - `pip install azure-schemaregistry[jsonencoder]`. For a list of supported `jsonschema` validators, - please refer to the `jsonschema` documentation: - https://python-jsonschema.readthedocs.io/en/stable/api/jsonschema/validators/index.html - If a callable is provided, the schema and content will be passed in for validation. - :paramtype validate: str or ~azure.schemaregistry.SchemaContentValidate - :keyword Optional[str] group_name: Schema group under which schema should be registered. - Required if `schema`, not `schema_id`, is provided to `encode`. - """ - - def __init__( - self, - *, - client: "azure.schemaregistry.aio.SchemaRegistryClient", - validate: Union[str, "SchemaContentValidate"], - group_name: Optional[str] = None, - ) -> None: - self._schema_registry_client = client - if isinstance(validate, str): - self._validate = get_jsonschema_validator(validate) - else: - self._validate = validate - self._schema_group = group_name - - async def __aenter__(self) -> "JsonSchemaEncoder": - await self._schema_registry_client.__aenter__() - return self - - async def __aexit__(self, *exc_details: Any) -> None: - await self._schema_registry_client.__aexit__(*exc_details) - - async def close(self) -> None: - """This method is to close the sockets opened by the client. - It need not be used when using with a context manager. - """ - await self._schema_registry_client.close() - - @alru_cache(maxsize=128, cache_exceptions=False) - async def _get_schema_id(self, schema_name: str, schema_str: str, **kwargs: Any) -> str: - """ - Get schema id from local cache with the given schema. - If there is no item in the local cache, get schema id from the service and cache it. - - :param schema_name: Name of the schema - :type schema_name: str - :param str schema_str: Schema string - :return: Schema Id - :rtype: str - """ - schema_properties = await self._schema_registry_client.get_schema_properties( - cast(str, self._schema_group), - schema_name, - schema_str, - SchemaFormat.JSON.value, - **kwargs, - ) - return schema_properties.id - - @alru_cache(maxsize=128, cache_exceptions=False) - async def _get_schema(self, schema_id: str, **kwargs: Any) -> str: - """ - Get schema definition from local cache with the given schema id. - If there is no item in the local cache, get schema from the service and cache it. - - :param str schema_id: Schema id - :return: Schema definition - :rtype: str - """ - schema = await self._schema_registry_client.get_schema(schema_id, **kwargs) - return schema.definition - - @overload - async def encode( - self, - content: Mapping[str, Any], - *, - schema: str, - message_type: Type[OutboundMessageContent], - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> OutboundMessageContent: - """Encodes content after validating against the pre-registered JSON schema. Encoded content and content - type will be passed to the provided OutboundMessageContent class to create message object. - - If `message_type` is set, then additional keyword arguments for building OutboundMessageContent will - be passed to the OutboundMessageContent.from_message_content() method. - - :param content: The content to be encoded. - :type content: mapping[str, any] - :keyword schema: Required. The pre-registered schema used to validate the content. `schema_id` - must not be passed. - :paramtype schema: str - :keyword message_type: The message class to construct the message. Must be a subtype of the - azure.schemaregistry.OutboundMessageContent protocol. - :paramtype message_type: type[OutboundMessageContent] - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: The OutboundMessageContent object with encoded content and content type. - :rtype: OutboundMessageContent - :raises: ~azure.schemaregistry.encoder.InvalidContentError if there is an issue with encoding content - or validating it against the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - - @overload - async def encode( - self, - content: Mapping[str, Any], - *, - schema_id: str, - message_type: Type[OutboundMessageContent], - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> OutboundMessageContent: - """Encodes content after validating against the pre-registered JSON schema corresponding to - the provided schema ID. Encoded content and content type will be passed to the provided - OutboundMessageContent class to create message object. - - If `message_type` is set, then additional keyword arguments for building OutboundMessageContent - will be passed to the OutboundMessageContent.from_message_content() method. - - :param content: The content to be encoded. - :type content: mapping[str, any] - :keyword schema_id: Required. The schema ID corresponding to the pre-registered schema to be used - for validation. `schema` must not be passed. - :paramtype schema_id: str - :keyword message_type: The message class to construct the message. Must be a subtype of the - azure.schemaregistry.OutboundMessageContent protocol. - :paramtype message_type: type[OutboundMessageContent] - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: The OutboundMessageContent object with encoded content and content type. - :rtype: OutboundMessageContent - :raises: ~azure.schemaregistry.encoder.InvalidContentError if there is an issue with encoding content - or validating it against the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - - @overload - async def encode( - self, - content: Mapping[str, Any], - *, - schema: str, - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> "MessageContent": - """Encodes content after validating against the pre-registered schema. The following dict will be returned: - {"content": JSON encoded value, "content_type": JSON mime type string + schema ID}. - - :param content: The content to be encoded. - :type content: mapping[str, any] - :keyword schema: Required. The pre-registered schema used to validate the content. `schema_id` - must not be passed. - :paramtype schema: str - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: TypedDict of encoded content and content type. - :rtype: MessageContent - :raises: ~azure.schemaregistry.encoder.InvalidContentError if there is an issue with encoding content - or validating it against the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - - @overload - async def encode( - self, - content: Mapping[str, Any], - *, - schema_id: str, - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> "MessageContent": - """Encodes content after validating against the pre-registered schema corresponding to - the provided schema ID. The following dict will be returned: - {"content": JSON encoded value, "content_type": JSON mime type string + schema ID}. - - :param content: The content to be encoded. - :type content: mapping[str, any] - :keyword schema_id: Required. The schema ID corresponding to the pre-registered schema to be used - for validation. `schema` must not be passed. - :paramtype schema_id: str - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: TypedDict of encoded content and content type. - :rtype: MessageContent - :raises: ~azure.schemaregistry.encoder.InvalidContentError if there is an issue with encoding content - or validating it against the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - - async def encode( - self, - content: Mapping[str, Any], - *, - schema: Optional[str] = None, - schema_id: Optional[str] = None, - message_type: Optional[Type[OutboundMessageContent]] = None, - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> Union[OutboundMessageContent, "MessageContent"]: - """Encodes content after validating against the provided pre-registered schema or the one corresponding to - the provided schema ID. If provided with a OutboundMessageContent subtype, encoded content and content type - will be passed to create message object. If not provided, the following dict will be returned: - {"content": JSON encoded value, "content_type": JSON mime type string + schema ID}. - - If `message_type` is set, then additional keyword arguments for building OutboundMessageContent will be passed - to the OutboundMessageContent.from_message_content() method. - - :param content: The content to be encoded. - :type content: mapping[str, any] - :keyword schema: The pre-registered schema used to validate the content. Exactly one of - `schema` or `schema_id` must be passed. - :paramtype schema: str or None - :keyword schema_id: The schema ID corresponding to the pre-registered schema to be used - for validation. Exactly one of `schema` or `schema_id` must be passed. - :paramtype schema_id: str or None - :keyword message_type: The message class to construct the message. Must be a subtype of the - azure.schemaregistry.encoder.OutboundMessageContent protocol. - :keyword message_type: The message class to construct the message. If passed, must be a subtype of the - azure.schemaregistry.OutboundMessageContent protocol. - :paramtype message_type: type[OutboundMessageContent] or None - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: TypedDict of encoded content and content type if `message_type` is not set, otherwise the - constructed message object. - :rtype: OutboundMessageContent or MessageContent - :raises: ~azure.schemaregistry.encoder.InvalidContentError if there is an issue with encoding content - or validating it against the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - request_options = request_options or {} - - # If schema_id, get schema for validation. If schema, get schema_id for content type. - if schema_id and not schema: - cache_misses = self._get_schema.cache_info().misses - schema_str = await self._get_schema(schema_id, **request_options) - new_cache_misses = self._get_schema.cache_info().misses - if new_cache_misses > cache_misses: - cache_info = self._get_schema.cache_info() - _LOGGER.info( - "New entry has been added to schema cache. Cache info: %s", - str(cache_info), - ) - schema_dict = json.loads(schema_str) - elif schema and not schema_id: - if not self._schema_group: - raise TypeError("'group_name' is required in constructor, if 'schema' is passed to encode.") - - schema_fullname, schema_str, schema_dict = get_loaded_schema(schema, content) - cache_misses = self._get_schema_id.cache_info().misses - schema_id = await self._get_schema_id(schema_fullname, schema_str, **request_options) - new_cache_misses = ( - self._get_schema_id.cache_info().misses - ) - if new_cache_misses > cache_misses: - cache_info = self._get_schema_id.cache_info() - _LOGGER.info( - "New entry has been added to schema ID cache. Cache info: %s", - str(cache_info), - ) - else: - raise TypeError("Exactly one of 'schema' or 'schema_id' is required.") - - return create_message_content( - content=content, - schema=schema_dict, - schema_id=cast(str, schema_id), - validate=self._validate, - message_type=message_type, - **kwargs, - ) - - async def decode( - self, - message: Union["MessageContent", InboundMessageContent], - *, - request_options: Optional[Dict[str, Any]] = None, - **kwargs: Any, - ) -> Dict[str, Any]: - """Decode bytes content using schema ID in the content type field. - - :param message: The message object which holds the content to be decoded and content type - containing the schema ID. - :type message: InboundMessageContent or MessageContent - :keyword request_options: The keyword arguments for http requests to be passed to the client. - :paramtype request_options: dict[str, any] or None - :returns: The decoded content. - :rtype: dict[str, any] - :raises: ~azure.schemaregistry.encoder.jsonencoder.InvalidContentError if there is - an issue with decoding content or validating it with the schema. - :raises: ~azure.core.exceptions.HttpResponseError if there is an issue with the request to get the schema - from the registry. - """ - schema_id, content = parse_message(message) - cache_misses = self._get_schema.cache_info().misses - request_options = request_options or {} - schema_definition = await self._get_schema(schema_id, **request_options) - new_cache_misses = self._get_schema.cache_info().misses - if new_cache_misses > cache_misses: - cache_info = self._get_schema.cache_info() - _LOGGER.info( - "New entry has been added to schema cache. Cache info: %s", - str(cache_info), - ) - - return decode_content( - content=content, - schema_id=schema_id, - schema_definition=schema_definition, - validate=self._validate, - **kwargs, - ) diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/py.typed b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/py.typed deleted file mode 100644 index e5aff4f83af8..000000000000 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/encoder/jsonencoder/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/models/_patch.py b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/models/_patch.py index b3745335d600..8bcb627aa475 100644 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/models/_patch.py +++ b/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/models/_patch.py @@ -1,42 +1,14 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# -------------------------------------------------------------------------- """Customize generated code here. Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize """ from typing import List -from enum import Enum - -from azure.core import CaseInsensitiveEnumMeta -from ._enums import SchemaContentTypeValues - - -class SchemaFormat(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Represents the format of the schema to be stored by the Schema Registry service.""" - - AVRO = "Avro" - """Represents the Apache Avro schema format.""" - JSON = "Json" - """Represents the JSON schema format.""" - CUSTOM = "Custom" - """Represents a custom schema format.""" - - -# Normalizing the schema content type strings for whitespace and case insensitive comparison. -class NormalizedSchemaContentTypes(str, Enum, metaclass=CaseInsensitiveEnumMeta): - """Describes closed list of normalized schema content type values.""" - - AVRO = SchemaContentTypeValues.AVRO.value.replace(" ", "").lower() - """Avro encoding.""" - JSON = SchemaContentTypeValues.JSON.value.replace(" ", "").lower() - """JSON encoding""" - CUSTOM = SchemaContentTypeValues.CUSTOM.value.replace(" ", "").lower() - """Plain text custom encoding.""" - - __all__: List[str] = [] # Add all objects you want publicly available to users at this package level diff --git a/sdk/schemaregistry/azure-schemaregistry/generated_tests/conftest.py b/sdk/schemaregistry/azure-schemaregistry/generated_tests/conftest.py new file mode 100644 index 000000000000..0edb76ca93e9 --- /dev/null +++ b/sdk/schemaregistry/azure-schemaregistry/generated_tests/conftest.py @@ -0,0 +1,39 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +import os +import pytest +from dotenv import load_dotenv +from devtools_testutils import ( + test_proxy, + add_general_regex_sanitizer, + add_body_key_sanitizer, + add_header_regex_sanitizer, +) + +load_dotenv() + + +# For security, please avoid record sensitive identity information in recordings +@pytest.fixture(scope="session", autouse=True) +def add_sanitizers(test_proxy): + schemaregistry_subscription_id = os.environ.get( + "SCHEMAREGISTRY_SUBSCRIPTION_ID", "00000000-0000-0000-0000-000000000000" + ) + schemaregistry_tenant_id = os.environ.get("SCHEMAREGISTRY_TENANT_ID", "00000000-0000-0000-0000-000000000000") + schemaregistry_client_id = os.environ.get("SCHEMAREGISTRY_CLIENT_ID", "00000000-0000-0000-0000-000000000000") + schemaregistry_client_secret = os.environ.get( + "SCHEMAREGISTRY_CLIENT_SECRET", "00000000-0000-0000-0000-000000000000" + ) + add_general_regex_sanitizer(regex=schemaregistry_subscription_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=schemaregistry_tenant_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=schemaregistry_client_id, value="00000000-0000-0000-0000-000000000000") + add_general_regex_sanitizer(regex=schemaregistry_client_secret, value="00000000-0000-0000-0000-000000000000") + + add_header_regex_sanitizer(key="Set-Cookie", value="[set-cookie;]") + add_header_regex_sanitizer(key="Cookie", value="cookie;") + add_body_key_sanitizer(json_path="$..access_token", value="access_token") diff --git a/sdk/schemaregistry/azure-schemaregistry/generated_tests/testpreparer.py b/sdk/schemaregistry/azure-schemaregistry/generated_tests/testpreparer.py new file mode 100644 index 000000000000..08c05c39d9b8 --- /dev/null +++ b/sdk/schemaregistry/azure-schemaregistry/generated_tests/testpreparer.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) Python Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from azure.schemaregistry import SchemaRegistryClient +from devtools_testutils import AzureRecordedTestCase, PowerShellPreparer +import functools + + +class SchemaRegistryClientTestBase(AzureRecordedTestCase): + + def create_client(self, endpoint): + credential = self.get_credential(SchemaRegistryClient) + return self.create_client_from_credential( + SchemaRegistryClient, + credential=credential, + endpoint=endpoint, + ) + + +SchemaRegistryPreparer = functools.partial( + PowerShellPreparer, "schemaregistry", schemaregistry_endpoint="https://fake_schemaregistry_endpoint.com" +) diff --git a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_types.py b/sdk/schemaregistry/azure-schemaregistry/generated_tests/testpreparer_async.py similarity index 50% rename from sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_types.py rename to sdk/schemaregistry/azure-schemaregistry/generated_tests/testpreparer_async.py index f2b3319751b6..3b3c633aac49 100644 --- a/sdk/schemaregistry/azure-schemaregistry/azure/schemaregistry/_types.py +++ b/sdk/schemaregistry/azure-schemaregistry/generated_tests/testpreparer_async.py @@ -1,18 +1,20 @@ # coding=utf-8 -# pylint: disable=too-many-lines # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) Python Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- +from azure.schemaregistry.aio import SchemaRegistryClient +from devtools_testutils import AzureRecordedTestCase -from typing import Literal, Union -SchemaContentTypeValues = Union[ - Literal["application/octet-stream"], - Literal["text/plain; charset=utf-8"], - Literal["application/json; serialization=Avro"], - Literal["application/json; serialization=Json"], - Literal["text/vnd.ms.protobuf"], -] +class SchemaRegistryClientTestBaseAsync(AzureRecordedTestCase): + + def create_async_client(self, endpoint): + credential = self.get_credential(SchemaRegistryClient, is_async=True) + return self.create_client_from_credential( + SchemaRegistryClient, + credential=credential, + endpoint=endpoint, + ) diff --git a/sdk/schemaregistry/azure-schemaregistry/samples/async_samples/jsonencoder/eventhub_receive_integration_async.py b/sdk/schemaregistry/azure-schemaregistry/samples/async_samples/jsonencoder/eventhub_receive_integration_async.py index c986e1c1c6c2..a28b6abca68b 100644 --- a/sdk/schemaregistry/azure-schemaregistry/samples/async_samples/jsonencoder/eventhub_receive_integration_async.py +++ b/sdk/schemaregistry/azure-schemaregistry/samples/async_samples/jsonencoder/eventhub_receive_integration_async.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression #!/usr/bin/env python # -------------------------------------------------------------------------------------------- diff --git a/sdk/schemaregistry/azure-schemaregistry/samples/sync_samples/jsonencoder/eventhub_receive_integration.py b/sdk/schemaregistry/azure-schemaregistry/samples/sync_samples/jsonencoder/eventhub_receive_integration.py index f006af3f9a4f..a7c01bfe4421 100644 --- a/sdk/schemaregistry/azure-schemaregistry/samples/sync_samples/jsonencoder/eventhub_receive_integration.py +++ b/sdk/schemaregistry/azure-schemaregistry/samples/sync_samples/jsonencoder/eventhub_receive_integration.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression #!/usr/bin/env python # -------------------------------------------------------------------------------------------- diff --git a/sdk/schemaregistry/azure-schemaregistry/tests/async_tests/test_schema_registry_async.py b/sdk/schemaregistry/azure-schemaregistry/tests/async_tests/test_schema_registry_async.py index 697d2a3890ad..68bc214489fd 100644 --- a/sdk/schemaregistry/azure-schemaregistry/tests/async_tests/test_schema_registry_async.py +++ b/sdk/schemaregistry/azure-schemaregistry/tests/async_tests/test_schema_registry_async.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. diff --git a/sdk/schemaregistry/azure-schemaregistry/tests/test_schema_registry.py b/sdk/schemaregistry/azure-schemaregistry/tests/test_schema_registry.py index 9ed0b1475557..80dbeec21bda 100644 --- a/sdk/schemaregistry/azure-schemaregistry/tests/test_schema_registry.py +++ b/sdk/schemaregistry/azure-schemaregistry/tests/test_schema_registry.py @@ -1,3 +1,4 @@ +# pylint: disable=line-too-long,useless-suppression # -------------------------------------------------------------------------- # # Copyright (c) Microsoft Corporation. All rights reserved. diff --git a/sdk/schemaregistry/azure-schemaregistry/tsp-location.yaml b/sdk/schemaregistry/azure-schemaregistry/tsp-location.yaml index b9214dcf68ee..704dfe1347b7 100644 --- a/sdk/schemaregistry/azure-schemaregistry/tsp-location.yaml +++ b/sdk/schemaregistry/azure-schemaregistry/tsp-location.yaml @@ -1,4 +1,4 @@ -cleanup: false -commit: 7e22a66617633d162735fe65388c2852127b4aac directory: specification/schemaregistry/SchemaRegistry -repo: Azure/azure-rest-api-specs \ No newline at end of file +commit: 0452565bc97d1f2d55954d99d170a38529ba7e4b +repo: Azure/azure-rest-api-specs +additionalDirectories: