diff --git a/.vscode/cspell.json b/.vscode/cspell.json index 63d181459029..f1271563e39c 100644 --- a/.vscode/cspell.json +++ b/.vscode/cspell.json @@ -297,6 +297,7 @@ "mibps", "mgmt", "mhsm", + "mros", "Nify", "mipsle", "mktime", diff --git a/sdk/eventgrid/azure-eventgrid/CHANGELOG.md b/sdk/eventgrid/azure-eventgrid/CHANGELOG.md index 67215858cab5..77789330402e 100644 --- a/sdk/eventgrid/azure-eventgrid/CHANGELOG.md +++ b/sdk/eventgrid/azure-eventgrid/CHANGELOG.md @@ -22,6 +22,13 @@ This version and all future versions will require Python 3.8+. ### Features Added - Added new enums values to `SystemEventNames` related to Azure Storage and Azure VMware Solution. +## 4.17.0b1 (2023-11-09) + +### Features Added + +- Added new features to the EventGridClient that supports `publish_cloud_events`, `receive_cloud_events`, `acknowledge_cloud_events` , `release_cloud_events`, and `reject_cloud_events` operations. These features include a `renew_cloud_event_locks` operation, as well as a `release_with_delay` parameter on the `release_cloud_events` operation. +- `lock_tokens` parameter in `reject_cloud_events`, `release_cloud_events`, and `acknowledge_cloud_events` renamed to `reject_options`, `release_options`, and `acknowledge_options`. +- Added new models to support these new operations on EventGridClient. ## 4.16.0 (2023-11-08) diff --git a/sdk/eventgrid/azure-eventgrid/assets.json b/sdk/eventgrid/azure-eventgrid/assets.json index 46490ff40be4..d7404dd2fdd0 100644 --- a/sdk/eventgrid/azure-eventgrid/assets.json +++ b/sdk/eventgrid/azure-eventgrid/assets.json @@ -2,5 +2,5 @@ "AssetsRepo": "Azure/azure-sdk-assets", "AssetsRepoPrefixPath": "python", "TagPrefix": "python/eventgrid/azure-eventgrid", - "Tag": "python/eventgrid/azure-eventgrid_fce4958e09" + "Tag": "python/eventgrid/azure-eventgrid_f155c8ac2d" } diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py index 329e214d89c1..a7b6c85bbe3e 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_client.py @@ -11,6 +11,7 @@ from azure.core import PipelineClient from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies from azure.core.rest import HttpRequest, HttpResponse from ._configuration import EventGridClientConfiguration @@ -32,7 +33,7 @@ class EventGridClient(EventGridClientOperationsMixin): # pylint: disable=client :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential :keyword api_version: The API version to use for this operation. Default value is - "2023-06-01-preview". Note that overriding this default value may result in unsupported + "2023-10-01-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ @@ -45,7 +46,11 @@ def __init__( ) -> None: _endpoint = '{endpoint}' self._config = EventGridClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) - self._client: PipelineClient = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) + _policies = kwargs.pop('policies', None) + if _policies is None: + _policies = [policies.RequestIdPolicy(**kwargs),self._config.headers_policy,self._config.user_agent_policy,self._config.proxy_policy,policies.ContentDecodePolicy(**kwargs),self._config.redirect_policy,self._config.retry_policy,self._config.authentication_policy,self._config.custom_hook_policy,self._config.logging_policy,policies.DistributedTracingPolicy(**kwargs),policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None,self._config.http_logging_policy] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + self._serialize = Serializer() self._deserialize = Deserializer() @@ -54,7 +59,7 @@ def __init__( def send_request( self, - request: HttpRequest, + request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> HttpResponse: """Runs the network request through the client's chained policies. @@ -80,7 +85,7 @@ def send_request( } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore def close(self) -> None: self._client.close() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_configuration.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_configuration.py index 8a5c765af4f5..a615bd59224d 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_configuration.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_configuration.py @@ -8,7 +8,6 @@ from typing import Any, TYPE_CHECKING, Union -from azure.core.configuration import Configuration from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies @@ -19,9 +18,7 @@ from azure.core.credentials import TokenCredential -class EventGridClientConfiguration( # pylint: disable=too-many-instance-attributes,name-too-long - Configuration -): +class EventGridClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for EventGridClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +32,7 @@ class EventGridClientConfiguration( # pylint: disable=too-many-instance-attri :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials.TokenCredential :keyword api_version: The API version to use for this operation. Default value is - "2023-06-01-preview". Note that overriding this default value may result in unsupported + "2023-10-01-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ @@ -46,8 +43,7 @@ def __init__( credential: Union[AzureKeyCredential, "TokenCredential"], **kwargs: Any ) -> None: - super(EventGridClientConfiguration, self).__init__(**kwargs) - api_version: str = kwargs.pop('api_version', "2023-06-01-preview") + api_version: str = kwargs.pop('api_version', "2023-10-01-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -59,6 +55,7 @@ def __init__( self.api_version = api_version self.credential_scopes = kwargs.pop('credential_scopes', ['https://eventgrid.azure.net/.default']) kwargs.setdefault('sdk_moniker', 'eventgrid/{}'.format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _infer_policy(self, **kwargs): @@ -77,9 +74,9 @@ def _configure( self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get('redirect_policy') or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.RetryPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py index 2e328fc6adeb..8474b72c2346 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_model_base.py @@ -31,7 +31,7 @@ _LOGGER = logging.getLogger(__name__) -__all__ = ["AzureJSONEncoder", "Model", "rest_field", "rest_discriminator"] +__all__ = ["SdkJSONEncoder", "Model", "rest_field", "rest_discriminator"] TZ_UTC = timezone.utc @@ -125,7 +125,7 @@ def _is_readonly(p): return False -class AzureJSONEncoder(JSONEncoder): +class SdkJSONEncoder(JSONEncoder): """A JSON encoder that's capable of serializing datetime objects and bytes.""" def __init__(self, *args, exclude_readonly: bool = False, format: typing.Optional[str] = None, **kwargs): @@ -140,7 +140,7 @@ def default(self, o): # pylint: disable=too-many-return-statements return {k: v for k, v in o.items() if k not in readonly_props} return dict(o.items()) try: - return super(AzureJSONEncoder, self).default(o) + return super(SdkJSONEncoder, self).default(o) except TypeError: if isinstance(o, _Null): return None @@ -157,7 +157,7 @@ def default(self, o): # pylint: disable=too-many-return-statements except AttributeError: # This will be raised when it hits value.total_seconds in the method above pass - return super(AzureJSONEncoder, self).default(o) + return super(SdkJSONEncoder, self).default(o) _VALID_DATE = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" + r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") @@ -553,7 +553,7 @@ def as_dict(self, *, exclude_readonly: bool = False) -> typing.Dict[str, typing. if exclude_readonly: readonly_props = [p._rest_name for p in self._attr_to_rest_field.values() if _is_readonly(p)] for k, v in self.items(): - if exclude_readonly and k in readonly_props: # pyright: reportUnboundVariable=false + if exclude_readonly and k in readonly_props: # pyright: ignore[reportUnboundVariable] continue result[k] = Model._as_dict_value(v, exclude_readonly=exclude_readonly) return result @@ -754,9 +754,12 @@ def _deserialize( value: typing.Any, module: typing.Optional[str] = None, rf: typing.Optional["_RestField"] = None, + format: typing.Optional[str] = None, ) -> typing.Any: if isinstance(value, PipelineResponse): value = value.http_response.json() + if rf is None and format: + rf = _RestField(format=format) deserializer = _get_deserialize_callable_from_annotation(deserializer, module, rf) return _deserialize_with_callable(deserializer, value) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py index 5d63b0e4eaa0..c166e5de9c64 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/__init__.py @@ -6,7 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._patch import EventGridClientOperationsMixin +from ._operations import EventGridClientOperationsMixin from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py index b665dd492629..50a506ffb3e5 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_operations.py @@ -18,7 +18,7 @@ from azure.core.utils import case_insensitive_dict from .. import models as _models -from .._model_base import AzureJSONEncoder, _deserialize +from .._model_base import SdkJSONEncoder, _deserialize from .._serialization import Serializer from .._vendor import EventGridClientMixinABC @@ -42,7 +42,7 @@ def build_event_grid_publish_cloud_event_request( # pylint: disable=name-too-lo _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', "2023-06-01-preview")) + api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-10-01-preview")) accept = _headers.pop('Accept', "application/json") # Construct URL @@ -77,7 +77,7 @@ def build_event_grid_publish_cloud_events_request( # pylint: disable=name-too-l _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', "2023-06-01-preview")) + api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-10-01-preview")) accept = _headers.pop('Accept', "application/json") # Construct URL @@ -115,7 +115,7 @@ def build_event_grid_receive_cloud_events_request( # pylint: disable=name-too-l _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-06-01-preview")) + api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-10-01-preview")) accept = _headers.pop('Accept', "application/json") # Construct URL @@ -154,8 +154,8 @@ def build_event_grid_acknowledge_cloud_events_request( # pylint: disable=name-t _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('content-type', None)) - api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-06-01-preview")) + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) + api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-10-01-preview")) accept = _headers.pop('Accept', "application/json") # Construct URL @@ -171,9 +171,9 @@ def build_event_grid_acknowledge_cloud_events_request( # pylint: disable=name-t _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers - if content_type is not None: - _headers['content-type'] = _SERIALIZER.header("content_type", content_type, 'str') _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + if content_type is not None: + _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') return HttpRequest( method="POST", @@ -187,13 +187,15 @@ def build_event_grid_acknowledge_cloud_events_request( # pylint: disable=name-t def build_event_grid_release_cloud_events_request( # pylint: disable=name-too-long topic_name: str, event_subscription_name: str, + *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, **kwargs: Any ) -> HttpRequest: _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('content-type', None)) - api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-06-01-preview")) + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) + api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-10-01-preview")) accept = _headers.pop('Accept', "application/json") # Construct URL @@ -207,11 +209,13 @@ def build_event_grid_release_cloud_events_request( # pylint: disable=name-too-l # Construct parameters _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') + if release_delay_in_seconds is not None: + _params['releaseDelayInSeconds'] = _SERIALIZER.query("release_delay_in_seconds", release_delay_in_seconds, 'int') # Construct headers - if content_type is not None: - _headers['content-type'] = _SERIALIZER.header("content_type", content_type, 'str') _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') + if content_type is not None: + _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') return HttpRequest( method="POST", @@ -230,8 +234,8 @@ def build_event_grid_reject_cloud_events_request( # pylint: disable=name-too-lo _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('content-type', None)) - api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-06-01-preview")) + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) + api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-10-01-preview")) accept = _headers.pop('Accept', "application/json") # Construct URL @@ -247,9 +251,47 @@ def build_event_grid_reject_cloud_events_request( # pylint: disable=name-too-lo _params['api-version'] = _SERIALIZER.query("api_version", api_version, 'str') # Construct headers + _headers['Accept'] = _SERIALIZER.header("accept", accept, 'str') if content_type is not None: - _headers['content-type'] = _SERIALIZER.header("content_type", content_type, 'str') + _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') + + return HttpRequest( + method="POST", + url=_url, + params=_params, + headers=_headers, + **kwargs + ) + + +def build_event_grid_renew_cloud_event_locks_request( # pylint: disable=name-too-long + topic_name: str, + event_subscription_name: str, + **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) + api_version: str = kwargs.pop('api_version', _params.pop('api-version', "2023-10-01-preview")) + accept = _headers.pop('Accept', "application/json") + + # Construct URL + _url = "/topics/{topicName}/eventsubscriptions/{eventSubscriptionName}:renewLock" + path_format_arguments = { + "topicName": _SERIALIZER.url("topic_name", topic_name, 'str'), + "eventSubscriptionName": _SERIALIZER.url("event_subscription_name", event_subscription_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['Accept'] = _SERIALIZER.header("accept", accept, 'str') + if content_type is not None: + _headers['Content-Type'] = _SERIALIZER.header("content_type", content_type, 'str') return HttpRequest( method="POST", @@ -302,9 +344,9 @@ def _publish_cloud_event( # pylint: disable=protected-access 'cls', None ) - _content = json.dumps(event, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(event, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_event_grid_publish_cloud_event_request( + _request = build_event_grid_publish_cloud_event_request( topic_name=topic_name, content_type=content_type, api_version=self._config.api_version, @@ -315,11 +357,11 @@ def _publish_cloud_event( # pylint: disable=protected-access path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -343,7 +385,7 @@ def _publish_cloud_event( # pylint: disable=protected-access if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore @@ -386,9 +428,9 @@ def _publish_cloud_events( # pylint: disable=protected-access 'cls', None ) - _content = json.dumps(events, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(events, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_event_grid_publish_cloud_events_request( + _request = build_event_grid_publish_cloud_events_request( topic_name=topic_name, content_type=content_type, api_version=self._config.api_version, @@ -399,11 +441,11 @@ def _publish_cloud_events( # pylint: disable=protected-access path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -427,7 +469,7 @@ def _publish_cloud_events( # pylint: disable=protected-access if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore @@ -475,7 +517,7 @@ def _receive_cloud_events( # pylint: disable=protected-access ) - request = build_event_grid_receive_cloud_events_request( + _request = build_event_grid_receive_cloud_events_request( topic_name=topic_name, event_subscription_name=event_subscription_name, max_events=max_events, @@ -487,11 +529,11 @@ def _receive_cloud_events( # pylint: disable=protected-access path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -515,7 +557,7 @@ def _receive_cloud_events( # pylint: disable=protected-access if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore @@ -524,13 +566,13 @@ def acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: _models.AcknowledgeOptions, + acknowledge_options: _models.AcknowledgeOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if at least - one event is successfully acknowledged. The response body will include the set of successfully + """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully acknowledged lockTokens, along with other failed lockTokens with their corresponding error information. Successfully acknowledged events will no longer be available to any consumer. @@ -538,8 +580,8 @@ def acknowledge_cloud_events( :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: AcknowledgeOptions. Required. - :type lock_tokens: ~azure.eventgrid.models.AcknowledgeOptions + :param acknowledge_options: AcknowledgeOptions. Required. + :type acknowledge_options: ~azure.eventgrid.models.AcknowledgeOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -555,13 +597,13 @@ def acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: JSON, + acknowledge_options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if at least - one event is successfully acknowledged. The response body will include the set of successfully + """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully acknowledged lockTokens, along with other failed lockTokens with their corresponding error information. Successfully acknowledged events will no longer be available to any consumer. @@ -569,8 +611,8 @@ def acknowledge_cloud_events( :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: AcknowledgeOptions. Required. - :type lock_tokens: JSON + :param acknowledge_options: AcknowledgeOptions. Required. + :type acknowledge_options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -586,13 +628,13 @@ def acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: IO, + acknowledge_options: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if at least - one event is successfully acknowledged. The response body will include the set of successfully + """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully acknowledged lockTokens, along with other failed lockTokens with their corresponding error information. Successfully acknowledged events will no longer be available to any consumer. @@ -600,8 +642,8 @@ def acknowledge_cloud_events( :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: AcknowledgeOptions. Required. - :type lock_tokens: IO + :param acknowledge_options: AcknowledgeOptions. Required. + :type acknowledge_options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -618,11 +660,11 @@ def acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: Union[_models.AcknowledgeOptions, JSON, IO], + acknowledge_options: Union[_models.AcknowledgeOptions, JSON, IO], **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if at least - one event is successfully acknowledged. The response body will include the set of successfully + """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully acknowledged lockTokens, along with other failed lockTokens with their corresponding error information. Successfully acknowledged events will no longer be available to any consumer. @@ -630,10 +672,11 @@ def acknowledge_cloud_events( :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: AcknowledgeOptions. Is one of the following types: AcknowledgeOptions, - JSON, IO Required. - :type lock_tokens: ~azure.eventgrid.models.AcknowledgeOptions or JSON or IO - :keyword content_type: content type. Default value is None. + :param acknowledge_options: AcknowledgeOptions. Is one of the following types: + AcknowledgeOptions, JSON, IO Required. + :type acknowledge_options: ~azure.eventgrid.models.AcknowledgeOptions or JSON or IO + :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default + value is None. :paramtype content_type: str :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You will have to context manage the returned stream. @@ -649,19 +692,19 @@ def acknowledge_cloud_events( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('content-type', None)) + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) cls: ClsType[_models.AcknowledgeResult] = kwargs.pop( 'cls', None ) content_type = content_type or "application/json" _content = None - if isinstance(lock_tokens, (IOBase, bytes)): - _content = lock_tokens + if isinstance(acknowledge_options, (IOBase, bytes)): + _content = acknowledge_options else: - _content = json.dumps(lock_tokens, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(acknowledge_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_event_grid_acknowledge_cloud_events_request( + _request = build_event_grid_acknowledge_cloud_events_request( topic_name=topic_name, event_subscription_name=event_subscription_name, content_type=content_type, @@ -673,11 +716,11 @@ def acknowledge_cloud_events( path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -701,7 +744,7 @@ def acknowledge_cloud_events( if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore @@ -710,21 +753,25 @@ def release_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: _models.ReleaseOptions, + release_options: _models.ReleaseOptions, *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one - event is successfully released. The response body will include the set of successfully released + """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: ReleaseOptions. Required. - :type lock_tokens: ~azure.eventgrid.models.ReleaseOptions + :param release_options: ReleaseOptions. Required. + :type release_options: ~azure.eventgrid.models.ReleaseOptions + :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. + Known values are: 0, 10, 60, 600, and 3600. Default value is None. + :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -740,21 +787,25 @@ def release_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: JSON, + release_options: JSON, *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one - event is successfully released. The response body will include the set of successfully released + """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: ReleaseOptions. Required. - :type lock_tokens: JSON + :param release_options: ReleaseOptions. Required. + :type release_options: JSON + :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. + Known values are: 0, 10, 60, 600, and 3600. Default value is None. + :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -770,21 +821,25 @@ def release_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: IO, + release_options: IO, *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one - event is successfully released. The response body will include the set of successfully released + """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: ReleaseOptions. Required. - :type lock_tokens: IO + :param release_options: ReleaseOptions. Required. + :type release_options: IO + :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. + Known values are: 0, 10, 60, 600, and 3600. Default value is None. + :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -801,21 +856,27 @@ def release_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: Union[_models.ReleaseOptions, JSON, IO], + release_options: Union[_models.ReleaseOptions, JSON, IO], + *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, **kwargs: Any ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one - event is successfully released. The response body will include the set of successfully released + """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: ReleaseOptions. Is one of the following types: ReleaseOptions, JSON, IO + :param release_options: ReleaseOptions. Is one of the following types: ReleaseOptions, JSON, IO Required. - :type lock_tokens: ~azure.eventgrid.models.ReleaseOptions or JSON or IO - :keyword content_type: content type. Default value is None. + :type release_options: ~azure.eventgrid.models.ReleaseOptions or JSON or IO + :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. + Known values are: 0, 10, 60, 600, and 3600. Default value is None. + :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay + :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default + value is None. :paramtype content_type: str :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You will have to context manage the returned stream. @@ -831,21 +892,22 @@ def release_cloud_events( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('content-type', None)) + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) cls: ClsType[_models.ReleaseResult] = kwargs.pop( 'cls', None ) content_type = content_type or "application/json" _content = None - if isinstance(lock_tokens, (IOBase, bytes)): - _content = lock_tokens + if isinstance(release_options, (IOBase, bytes)): + _content = release_options else: - _content = json.dumps(lock_tokens, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(release_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_event_grid_release_cloud_events_request( + _request = build_event_grid_release_cloud_events_request( topic_name=topic_name, event_subscription_name=event_subscription_name, + release_delay_in_seconds=release_delay_in_seconds, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -855,11 +917,11 @@ def release_cloud_events( path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -883,7 +945,7 @@ def release_cloud_events( if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore @@ -892,19 +954,21 @@ def reject_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: _models.RejectOptions, + reject_options: _models.RejectOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. + """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully rejected + lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: RejectOptions. Required. - :type lock_tokens: ~azure.eventgrid.models.RejectOptions + :param reject_options: RejectOptions. Required. + :type reject_options: ~azure.eventgrid.models.RejectOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -920,19 +984,21 @@ def reject_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: JSON, + reject_options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. + """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully rejected + lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: RejectOptions. Required. - :type lock_tokens: JSON + :param reject_options: RejectOptions. Required. + :type reject_options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -948,19 +1014,21 @@ def reject_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: IO, + reject_options: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. + """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully rejected + lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: RejectOptions. Required. - :type lock_tokens: IO + :param reject_options: RejectOptions. Required. + :type reject_options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -977,19 +1045,22 @@ def reject_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: Union[_models.RejectOptions, JSON, IO], + reject_options: Union[_models.RejectOptions, JSON, IO], **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. + """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully rejected + lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: RejectOptions. Is one of the following types: RejectOptions, JSON, IO + :param reject_options: RejectOptions. Is one of the following types: RejectOptions, JSON, IO Required. - :type lock_tokens: ~azure.eventgrid.models.RejectOptions or JSON or IO - :keyword content_type: content type. Default value is None. + :type reject_options: ~azure.eventgrid.models.RejectOptions or JSON or IO + :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default + value is None. :paramtype content_type: str :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You will have to context manage the returned stream. @@ -1005,19 +1076,19 @@ def reject_cloud_events( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('content-type', None)) + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) cls: ClsType[_models.RejectResult] = kwargs.pop( 'cls', None ) content_type = content_type or "application/json" _content = None - if isinstance(lock_tokens, (IOBase, bytes)): - _content = lock_tokens + if isinstance(reject_options, (IOBase, bytes)): + _content = reject_options else: - _content = json.dumps(lock_tokens, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(reject_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_event_grid_reject_cloud_events_request( + _request = build_event_grid_reject_cloud_events_request( topic_name=topic_name, event_subscription_name=event_subscription_name, content_type=content_type, @@ -1029,11 +1100,11 @@ def reject_cloud_events( path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -1057,6 +1128,197 @@ def reject_cloud_events( if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore + + + + @overload + def renew_cloud_event_locks( + self, + topic_name: str, + event_subscription_name: str, + renew_lock_options: _models.RenewLockOptions, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RenewCloudEventLocksResult: + """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + renewed lockTokens, along with other failed lockTokens with their corresponding error + information. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param event_subscription_name: Event Subscription Name. Required. + :type event_subscription_name: str + :param renew_lock_options: RenewLockOptions. Required. + :type renew_lock_options: ~azure.eventgrid.models.RenewLockOptions + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with + MutableMapping + :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def renew_cloud_event_locks( + self, + topic_name: str, + event_subscription_name: str, + renew_lock_options: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RenewCloudEventLocksResult: + """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + renewed lockTokens, along with other failed lockTokens with their corresponding error + information. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param event_subscription_name: Event Subscription Name. Required. + :type event_subscription_name: str + :param renew_lock_options: RenewLockOptions. Required. + :type renew_lock_options: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with + MutableMapping + :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def renew_cloud_event_locks( + self, + topic_name: str, + event_subscription_name: str, + renew_lock_options: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RenewCloudEventLocksResult: + """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + renewed lockTokens, along with other failed lockTokens with their corresponding error + information. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param event_subscription_name: Event Subscription Name. Required. + :type event_subscription_name: str + :param renew_lock_options: RenewLockOptions. Required. + :type renew_lock_options: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with + MutableMapping + :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + + @distributed_trace + def renew_cloud_event_locks( + self, + topic_name: str, + event_subscription_name: str, + renew_lock_options: Union[_models.RenewLockOptions, JSON, IO], + **kwargs: Any + ) -> _models.RenewCloudEventLocksResult: + """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + renewed lockTokens, along with other failed lockTokens with their corresponding error + information. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param event_subscription_name: Event Subscription Name. Required. + :type event_subscription_name: str + :param renew_lock_options: RenewLockOptions. Is one of the following types: RenewLockOptions, + JSON, IO Required. + :type renew_lock_options: ~azure.eventgrid.models.RenewLockOptions or JSON or IO + :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default + value is None. + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with + MutableMapping + :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult + :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: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) + cls: ClsType[_models.RenewCloudEventLocksResult] = kwargs.pop( + 'cls', None + ) + + content_type = content_type or "application/json" + _content = None + if isinstance(renew_lock_options, (IOBase, bytes)): + _content = renew_lock_options + else: + _content = json.dumps(renew_lock_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_event_grid_renew_cloud_event_locks_request( + topic_name=topic_name, + event_subscription_name=event_subscription_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, + stream=_stream, + **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models.RenewCloudEventLocksResult, + response.json() + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py index 79d4cd307960..3b2a6afdde76 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_operations/_patch.py @@ -63,8 +63,6 @@ def publish_cloud_events( :keyword content_type: content type. Default value is "application/cloudevents-batch+json; charset=utf-8". :paramtype content_type: str - :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: @@ -97,8 +95,6 @@ def publish_cloud_events( :keyword content_type: content type. Default value is "application/cloudevents+json; charset=utf-8". :paramtype content_type: str - :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: @@ -131,8 +127,6 @@ def publish_cloud_events( :keyword content_type: content type. Default value is "application/cloudevents+json; charset=utf-8". :paramtype content_type: str - :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: @@ -164,8 +158,6 @@ def publish_cloud_events( Requires CloudEvent data to be passed in as bytes. :keyword content_type: content type. Default value is "application/cloudevents-batch+json; charset=utf-8". :paramtype content_type: str - :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: @@ -197,8 +189,6 @@ def publish_cloud_events( :keyword content_type: content type. Default value is "application/cloudevents+json; charset=utf-8". :paramtype content_type: str - :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: diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py index 7fd392a19926..c33dabefd203 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/_serialization.py @@ -63,8 +63,8 @@ import isodate # type: ignore -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback -from azure.core.serialization import NULL as AzureCoreNull +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull _BOM = codecs.BOM_UTF8.decode(encoding="utf-8") @@ -124,7 +124,7 @@ def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: pass return ET.fromstring(data_as_str) # nosec - except ET.ParseError: + except ET.ParseError as err: # It might be because the server has an issue, and returned JSON with # content-type XML.... # So let's try a JSON load, and if it's still broken @@ -143,7 +143,7 @@ def _json_attemp(data): # The function hack is because Py2.7 messes up with exception # context otherwise. _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") + raise DeserializationError("XML is invalid") from err raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) @classmethod @@ -295,7 +295,7 @@ class Model(object): _validation: Dict[str, Dict[str, Any]] = {} def __init__(self, **kwargs: Any) -> None: - self.additional_properties: Dict[str, Any] = {} + self.additional_properties: Optional[Dict[str, Any]] = {} for k in kwargs: if k not in self._attribute_map: _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) @@ -340,7 +340,7 @@ def _create_xml_node(cls): return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: - """Return the JSON that would be sent to azure from this model. + """Return the JSON that would be sent to server from this model. This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. @@ -351,7 +351,7 @@ def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore def as_dict( self, @@ -392,7 +392,7 @@ def my_key_transformer(key, attr_desc, value): :rtype: dict """ serializer = Serializer(self._infer_class_models()) - return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) + return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore @classmethod def _infer_class_models(cls): @@ -417,7 +417,7 @@ def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = N :raises: DeserializationError if something went wrong """ deserializer = Deserializer(cls._infer_class_models()) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def from_dict( @@ -447,7 +447,7 @@ def from_dict( if key_extractors is None else key_extractors ) - return deserializer(cls.__name__, data, content_type=content_type) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore @classmethod def _flatten_subtype(cls, key, objects): @@ -670,7 +670,7 @@ def _serialize(self, target_obj, data_type=None, **kwargs): except (AttributeError, KeyError, TypeError) as err: msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err else: return serialized @@ -712,7 +712,7 @@ def body(self, data, data_type, **kwargs): ] data = deserializer._deserialize(data_type, data) except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) + raise SerializationError("Unable to build a model: " + str(err)) from err return self._serialize(data, data_type, **kwargs) @@ -732,7 +732,6 @@ def url(self, name, data, data_type, **kwargs): if kwargs.get("skip_quote") is True: output = str(output) - # https://github.com/Azure/autorest.python/issues/2063 output = output.replace("{", quote("{")).replace("}", quote("}")) else: output = quote(str(output), safe="") @@ -757,7 +756,7 @@ def query(self, name, data, data_type, **kwargs): if data_type.startswith("["): internal_data_type = data_type[1:-1] do_quote = not kwargs.get('skip_quote', False) - return str(self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs)) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) # Not a list, regular serialization output = self.serialize_data(data, data_type, **kwargs) @@ -808,7 +807,7 @@ def serialize_data(self, data, data_type, **kwargs): raise ValueError("No value for given attribute") try: - if data is AzureCoreNull: + if data is CoreNull: return None if data_type in self.basic_types.values(): return self.serialize_basic(data, data_type, **kwargs) @@ -828,7 +827,7 @@ def serialize_data(self, data, data_type, **kwargs): except (ValueError, TypeError) as err: msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) + raise SerializationError(msg.format(data, data_type)) from err else: return self._serialize(data, **kwargs) @@ -1178,10 +1177,10 @@ def serialize_iso(attr, **kwargs): return date + microseconds + "Z" except (ValueError, OverflowError) as err: msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) + raise SerializationError(msg) from err except AttributeError as err: msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) + raise TypeError(msg) from err @staticmethod def serialize_unix(attr, **kwargs): @@ -1217,7 +1216,6 @@ def rest_key_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1238,7 +1236,6 @@ def rest_key_case_insensitive_extractor(attr, attr_desc, data): if working_data is None: # If at any point while following flatten JSON path see None, it means # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 return None key = ".".join(dict_keys[1:]) @@ -1489,7 +1486,7 @@ def _deserialize(self, target_obj, data): d_attrs[attr] = value except (AttributeError, TypeError, KeyError) as err: msg = "Unable to deserialize to object: " + class_name # type: ignore - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: additional_properties = self._build_additional_properties(attributes, data) return self._instantiate_model(response, d_attrs, additional_properties) @@ -1660,7 +1657,7 @@ def deserialize_data(self, data, data_type): except (ValueError, TypeError, AttributeError) as err: msg = "Unable to deserialize response data." msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return self._deserialize(obj_type, data) @@ -1816,7 +1813,6 @@ def deserialize_enum(data, enum_obj): data = data.value if isinstance(data, int): # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 try: return list(enum_obj.__members__.values())[data] except IndexError: @@ -1873,7 +1869,7 @@ def deserialize_decimal(attr): return decimal.Decimal(attr) # type: ignore except decimal.DecimalException as err: msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err @staticmethod def deserialize_long(attr): @@ -1901,7 +1897,7 @@ def deserialize_duration(attr): duration = isodate.parse_duration(attr) except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return duration @@ -1953,7 +1949,7 @@ def deserialize_rfc(attr): date_obj = date_obj.astimezone(tz=TZ_UTC) except ValueError as err: msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj @@ -1990,7 +1986,7 @@ def deserialize_iso(attr): raise OverflowError("Hit max or min date") except (ValueError, OverflowError, AttributeError) as err: msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj @@ -2009,6 +2005,6 @@ def deserialize_unix(attr): date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) except ValueError as err: msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) + raise DeserializationError(msg) from err else: return date_obj diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py index e1d0a000fbde..064da9dbacfb 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_client.py @@ -11,6 +11,7 @@ from azure.core import AsyncPipelineClient from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline import policies from azure.core.rest import AsyncHttpResponse, HttpRequest from .._serialization import Deserializer, Serializer @@ -32,7 +33,7 @@ class EventGridClient(EventGridClientOperationsMixin): # pylint: disable=client :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential :keyword api_version: The API version to use for this operation. Default value is - "2023-06-01-preview". Note that overriding this default value may result in unsupported + "2023-10-01-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ @@ -45,7 +46,11 @@ def __init__( ) -> None: _endpoint = '{endpoint}' self._config = EventGridClientConfiguration(endpoint=endpoint, credential=credential, **kwargs) - self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) + _policies = kwargs.pop('policies', None) + if _policies is None: + _policies = [policies.RequestIdPolicy(**kwargs),self._config.headers_policy,self._config.user_agent_policy,self._config.proxy_policy,policies.ContentDecodePolicy(**kwargs),self._config.redirect_policy,self._config.retry_policy,self._config.authentication_policy,self._config.custom_hook_policy,self._config.logging_policy,policies.DistributedTracingPolicy(**kwargs),policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None,self._config.http_logging_policy] + self._client: AsyncPipelineClient = AsyncPipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + self._serialize = Serializer() self._deserialize = Deserializer() @@ -54,7 +59,7 @@ def __init__( def send_request( self, - request: HttpRequest, + request: HttpRequest, *, stream: bool = False, **kwargs: Any ) -> Awaitable[AsyncHttpResponse]: """Runs the network request through the client's chained policies. @@ -80,7 +85,7 @@ def send_request( } request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore async def close(self) -> None: await self._client.close() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_configuration.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_configuration.py index b06679bc2d67..847e9019f9dc 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_configuration.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_configuration.py @@ -8,7 +8,6 @@ from typing import Any, TYPE_CHECKING, Union -from azure.core.configuration import Configuration from azure.core.credentials import AzureKeyCredential from azure.core.pipeline import policies @@ -19,9 +18,7 @@ from azure.core.credentials_async import AsyncTokenCredential -class EventGridClientConfiguration( # pylint: disable=too-many-instance-attributes,name-too-long - Configuration -): +class EventGridClientConfiguration: # pylint: disable=too-many-instance-attributes,name-too-long """Configuration for EventGridClient. Note that all parameters used to create this instance are saved as instance @@ -35,7 +32,7 @@ class EventGridClientConfiguration( # pylint: disable=too-many-instance-attri :type credential: ~azure.core.credentials.AzureKeyCredential or ~azure.core.credentials_async.AsyncTokenCredential :keyword api_version: The API version to use for this operation. Default value is - "2023-06-01-preview". Note that overriding this default value may result in unsupported + "2023-10-01-preview". Note that overriding this default value may result in unsupported behavior. :paramtype api_version: str """ @@ -46,8 +43,7 @@ def __init__( credential: Union[AzureKeyCredential, "AsyncTokenCredential"], **kwargs: Any ) -> None: - super(EventGridClientConfiguration, self).__init__(**kwargs) - api_version: str = kwargs.pop('api_version', "2023-06-01-preview") + api_version: str = kwargs.pop('api_version', "2023-10-01-preview") if endpoint is None: raise ValueError("Parameter 'endpoint' must not be None.") @@ -59,6 +55,7 @@ def __init__( self.api_version = api_version self.credential_scopes = kwargs.pop('credential_scopes', ['https://eventgrid.azure.net/.default']) kwargs.setdefault('sdk_moniker', 'eventgrid/{}'.format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) self._configure(**kwargs) def _infer_policy(self, **kwargs): @@ -77,9 +74,9 @@ def _configure( self.proxy_policy = kwargs.get('proxy_policy') or policies.ProxyPolicy(**kwargs) self.logging_policy = kwargs.get('logging_policy') or policies.NetworkTraceLoggingPolicy(**kwargs) self.http_logging_policy = kwargs.get('http_logging_policy') or policies.HttpLoggingPolicy(**kwargs) - self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) self.custom_hook_policy = kwargs.get('custom_hook_policy') or policies.CustomHookPolicy(**kwargs) self.redirect_policy = kwargs.get('redirect_policy') or policies.AsyncRedirectPolicy(**kwargs) + self.retry_policy = kwargs.get('retry_policy') or policies.AsyncRetryPolicy(**kwargs) self.authentication_policy = kwargs.get('authentication_policy') if self.credential and not self.authentication_policy: self.authentication_policy = self._infer_policy(**kwargs) diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py index 5d63b0e4eaa0..c166e5de9c64 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/__init__.py @@ -6,7 +6,7 @@ # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- -from ._patch import EventGridClientOperationsMixin +from ._operations import EventGridClientOperationsMixin from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py index eb2c6cc3182f..aab392f5cf99 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_operations.py @@ -18,8 +18,8 @@ from azure.core.utils import case_insensitive_dict from ... import models as _models -from ..._model_base import AzureJSONEncoder, _deserialize -from ..._operations._operations import build_event_grid_acknowledge_cloud_events_request, build_event_grid_publish_cloud_event_request, build_event_grid_publish_cloud_events_request, build_event_grid_receive_cloud_events_request, build_event_grid_reject_cloud_events_request, build_event_grid_release_cloud_events_request +from ..._model_base import SdkJSONEncoder, _deserialize +from ..._operations._operations import build_event_grid_acknowledge_cloud_events_request, build_event_grid_publish_cloud_event_request, build_event_grid_publish_cloud_events_request, build_event_grid_receive_cloud_events_request, build_event_grid_reject_cloud_events_request, build_event_grid_release_cloud_events_request, build_event_grid_renew_cloud_event_locks_request from .._vendor import EventGridClientMixinABC if sys.version_info >= (3, 9): @@ -73,9 +73,9 @@ async def _publish_cloud_event( # pylint: disable=protected-access 'cls', None ) - _content = json.dumps(event, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(event, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_event_grid_publish_cloud_event_request( + _request = build_event_grid_publish_cloud_event_request( topic_name=topic_name, content_type=content_type, api_version=self._config.api_version, @@ -86,11 +86,11 @@ async def _publish_cloud_event( # pylint: disable=protected-access path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -114,7 +114,7 @@ async def _publish_cloud_event( # pylint: disable=protected-access if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore @@ -157,9 +157,9 @@ async def _publish_cloud_events( # pylint: disable=protected-access 'cls', None ) - _content = json.dumps(events, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(events, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_event_grid_publish_cloud_events_request( + _request = build_event_grid_publish_cloud_events_request( topic_name=topic_name, content_type=content_type, api_version=self._config.api_version, @@ -170,11 +170,11 @@ async def _publish_cloud_events( # pylint: disable=protected-access path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -198,7 +198,7 @@ async def _publish_cloud_events( # pylint: disable=protected-access if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore @@ -246,7 +246,7 @@ async def _receive_cloud_events( # pylint: disable=protected-access ) - request = build_event_grid_receive_cloud_events_request( + _request = build_event_grid_receive_cloud_events_request( topic_name=topic_name, event_subscription_name=event_subscription_name, max_events=max_events, @@ -258,11 +258,11 @@ async def _receive_cloud_events( # pylint: disable=protected-access path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -286,7 +286,7 @@ async def _receive_cloud_events( # pylint: disable=protected-access if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore @@ -295,13 +295,13 @@ async def acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: _models.AcknowledgeOptions, + acknowledge_options: _models.AcknowledgeOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if at least - one event is successfully acknowledged. The response body will include the set of successfully + """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully acknowledged lockTokens, along with other failed lockTokens with their corresponding error information. Successfully acknowledged events will no longer be available to any consumer. @@ -309,8 +309,8 @@ async def acknowledge_cloud_events( :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: AcknowledgeOptions. Required. - :type lock_tokens: ~azure.eventgrid.models.AcknowledgeOptions + :param acknowledge_options: AcknowledgeOptions. Required. + :type acknowledge_options: ~azure.eventgrid.models.AcknowledgeOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -326,13 +326,13 @@ async def acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: JSON, + acknowledge_options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if at least - one event is successfully acknowledged. The response body will include the set of successfully + """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully acknowledged lockTokens, along with other failed lockTokens with their corresponding error information. Successfully acknowledged events will no longer be available to any consumer. @@ -340,8 +340,8 @@ async def acknowledge_cloud_events( :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: AcknowledgeOptions. Required. - :type lock_tokens: JSON + :param acknowledge_options: AcknowledgeOptions. Required. + :type acknowledge_options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -357,13 +357,13 @@ async def acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: IO, + acknowledge_options: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if at least - one event is successfully acknowledged. The response body will include the set of successfully + """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully acknowledged lockTokens, along with other failed lockTokens with their corresponding error information. Successfully acknowledged events will no longer be available to any consumer. @@ -371,8 +371,8 @@ async def acknowledge_cloud_events( :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: AcknowledgeOptions. Required. - :type lock_tokens: IO + :param acknowledge_options: AcknowledgeOptions. Required. + :type acknowledge_options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -389,11 +389,11 @@ async def acknowledge_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: Union[_models.AcknowledgeOptions, JSON, IO], + acknowledge_options: Union[_models.AcknowledgeOptions, JSON, IO], **kwargs: Any ) -> _models.AcknowledgeResult: - """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if at least - one event is successfully acknowledged. The response body will include the set of successfully + """Acknowledge batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully acknowledged lockTokens, along with other failed lockTokens with their corresponding error information. Successfully acknowledged events will no longer be available to any consumer. @@ -401,10 +401,11 @@ async def acknowledge_cloud_events( :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: AcknowledgeOptions. Is one of the following types: AcknowledgeOptions, - JSON, IO Required. - :type lock_tokens: ~azure.eventgrid.models.AcknowledgeOptions or JSON or IO - :keyword content_type: content type. Default value is None. + :param acknowledge_options: AcknowledgeOptions. Is one of the following types: + AcknowledgeOptions, JSON, IO Required. + :type acknowledge_options: ~azure.eventgrid.models.AcknowledgeOptions or JSON or IO + :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default + value is None. :paramtype content_type: str :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You will have to context manage the returned stream. @@ -420,19 +421,19 @@ async def acknowledge_cloud_events( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('content-type', None)) + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) cls: ClsType[_models.AcknowledgeResult] = kwargs.pop( 'cls', None ) content_type = content_type or "application/json" _content = None - if isinstance(lock_tokens, (IOBase, bytes)): - _content = lock_tokens + if isinstance(acknowledge_options, (IOBase, bytes)): + _content = acknowledge_options else: - _content = json.dumps(lock_tokens, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(acknowledge_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_event_grid_acknowledge_cloud_events_request( + _request = build_event_grid_acknowledge_cloud_events_request( topic_name=topic_name, event_subscription_name=event_subscription_name, content_type=content_type, @@ -444,11 +445,11 @@ async def acknowledge_cloud_events( path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -472,7 +473,7 @@ async def acknowledge_cloud_events( if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore @@ -481,21 +482,25 @@ async def release_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: _models.ReleaseOptions, + release_options: _models.ReleaseOptions, *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one - event is successfully released. The response body will include the set of successfully released + """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: ReleaseOptions. Required. - :type lock_tokens: ~azure.eventgrid.models.ReleaseOptions + :param release_options: ReleaseOptions. Required. + :type release_options: ~azure.eventgrid.models.ReleaseOptions + :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. + Known values are: 0, 10, 60, 600, and 3600. Default value is None. + :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -511,21 +516,25 @@ async def release_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: JSON, + release_options: JSON, *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one - event is successfully released. The response body will include the set of successfully released + """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: ReleaseOptions. Required. - :type lock_tokens: JSON + :param release_options: ReleaseOptions. Required. + :type release_options: JSON + :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. + Known values are: 0, 10, 60, 600, and 3600. Default value is None. + :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -541,21 +550,25 @@ async def release_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: IO, + release_options: IO, *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, content_type: str = "application/json", **kwargs: Any ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one - event is successfully released. The response body will include the set of successfully released + """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: ReleaseOptions. Required. - :type lock_tokens: IO + :param release_options: ReleaseOptions. Required. + :type release_options: IO + :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. + Known values are: 0, 10, 60, 600, and 3600. Default value is None. + :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -572,21 +585,27 @@ async def release_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: Union[_models.ReleaseOptions, JSON, IO], + release_options: Union[_models.ReleaseOptions, JSON, IO], + *, + release_delay_in_seconds: Optional[Union[int, _models.ReleaseDelay]] = None, **kwargs: Any ) -> _models.ReleaseResult: - """Release batch of Cloud Events. The server responds with an HTTP 200 status code if at least one - event is successfully released. The response body will include the set of successfully released + """Release batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully released lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: ReleaseOptions. Is one of the following types: ReleaseOptions, JSON, IO + :param release_options: ReleaseOptions. Is one of the following types: ReleaseOptions, JSON, IO Required. - :type lock_tokens: ~azure.eventgrid.models.ReleaseOptions or JSON or IO - :keyword content_type: content type. Default value is None. + :type release_options: ~azure.eventgrid.models.ReleaseOptions or JSON or IO + :keyword release_delay_in_seconds: Release cloud events with the specified delay in seconds. + Known values are: 0, 10, 60, 600, and 3600. Default value is None. + :paramtype release_delay_in_seconds: int or ~azure.eventgrid.models.ReleaseDelay + :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default + value is None. :paramtype content_type: str :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You will have to context manage the returned stream. @@ -602,21 +621,22 @@ async def release_cloud_events( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('content-type', None)) + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) cls: ClsType[_models.ReleaseResult] = kwargs.pop( 'cls', None ) content_type = content_type or "application/json" _content = None - if isinstance(lock_tokens, (IOBase, bytes)): - _content = lock_tokens + if isinstance(release_options, (IOBase, bytes)): + _content = release_options else: - _content = json.dumps(lock_tokens, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(release_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_event_grid_release_cloud_events_request( + _request = build_event_grid_release_cloud_events_request( topic_name=topic_name, event_subscription_name=event_subscription_name, + release_delay_in_seconds=release_delay_in_seconds, content_type=content_type, api_version=self._config.api_version, content=_content, @@ -626,11 +646,11 @@ async def release_cloud_events( path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -654,7 +674,7 @@ async def release_cloud_events( if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore @@ -663,19 +683,21 @@ async def reject_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: _models.RejectOptions, + reject_options: _models.RejectOptions, *, content_type: str = "application/json", **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. + """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully rejected + lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: RejectOptions. Required. - :type lock_tokens: ~azure.eventgrid.models.RejectOptions + :param reject_options: RejectOptions. Required. + :type reject_options: ~azure.eventgrid.models.RejectOptions :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -691,19 +713,21 @@ async def reject_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: JSON, + reject_options: JSON, *, content_type: str = "application/json", **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. + """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully rejected + lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: RejectOptions. Required. - :type lock_tokens: JSON + :param reject_options: RejectOptions. Required. + :type reject_options: JSON :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. Default value is "application/json". :paramtype content_type: str @@ -719,19 +743,21 @@ async def reject_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: IO, + reject_options: IO, *, content_type: str = "application/json", **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. + """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully rejected + lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: RejectOptions. Required. - :type lock_tokens: IO + :param reject_options: RejectOptions. Required. + :type reject_options: IO :keyword content_type: Body Parameter content-type. Content type parameter for binary body. Default value is "application/json". :paramtype content_type: str @@ -748,19 +774,22 @@ async def reject_cloud_events( self, topic_name: str, event_subscription_name: str, - lock_tokens: Union[_models.RejectOptions, JSON, IO], + reject_options: Union[_models.RejectOptions, JSON, IO], **kwargs: Any ) -> _models.RejectResult: - """Reject batch of Cloud Events. + """Reject batch of Cloud Events. The server responds with an HTTP 200 status code if the request + is successfully accepted. The response body will include the set of successfully rejected + lockTokens, along with other failed lockTokens with their corresponding error information. :param topic_name: Topic Name. Required. :type topic_name: str :param event_subscription_name: Event Subscription Name. Required. :type event_subscription_name: str - :param lock_tokens: RejectOptions. Is one of the following types: RejectOptions, JSON, IO + :param reject_options: RejectOptions. Is one of the following types: RejectOptions, JSON, IO Required. - :type lock_tokens: ~azure.eventgrid.models.RejectOptions or JSON or IO - :keyword content_type: content type. Default value is None. + :type reject_options: ~azure.eventgrid.models.RejectOptions or JSON or IO + :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default + value is None. :paramtype content_type: str :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You will have to context manage the returned stream. @@ -776,19 +805,19 @@ async def reject_cloud_events( _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) _params = kwargs.pop("params", {}) or {} - content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('content-type', None)) + content_type: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) cls: ClsType[_models.RejectResult] = kwargs.pop( 'cls', None ) content_type = content_type or "application/json" _content = None - if isinstance(lock_tokens, (IOBase, bytes)): - _content = lock_tokens + if isinstance(reject_options, (IOBase, bytes)): + _content = reject_options else: - _content = json.dumps(lock_tokens, cls=AzureJSONEncoder, exclude_readonly=True) # type: ignore + _content = json.dumps(reject_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore - request = build_event_grid_reject_cloud_events_request( + _request = build_event_grid_reject_cloud_events_request( topic_name=topic_name, event_subscription_name=event_subscription_name, content_type=content_type, @@ -800,11 +829,11 @@ async def reject_cloud_events( path_format_arguments = { "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), } - request.url = self._client.format_url(request.url, **path_format_arguments) + _request.url = self._client.format_url(_request.url, **path_format_arguments) _stream = kwargs.pop("stream", False) pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access - request, + _request, stream=_stream, **kwargs ) @@ -828,6 +857,197 @@ async def reject_cloud_events( if cls: return cls(pipeline_response, deserialized, {}) # type: ignore - return deserialized # type: ignore + return deserialized # type: ignore + + + + @overload + async def renew_cloud_event_locks( + self, + topic_name: str, + event_subscription_name: str, + renew_lock_options: _models.RenewLockOptions, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RenewCloudEventLocksResult: + """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + renewed lockTokens, along with other failed lockTokens with their corresponding error + information. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param event_subscription_name: Event Subscription Name. Required. + :type event_subscription_name: str + :param renew_lock_options: RenewLockOptions. Required. + :type renew_lock_options: ~azure.eventgrid.models.RenewLockOptions + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with + MutableMapping + :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def renew_cloud_event_locks( + self, + topic_name: str, + event_subscription_name: str, + renew_lock_options: JSON, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RenewCloudEventLocksResult: + """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + renewed lockTokens, along with other failed lockTokens with their corresponding error + information. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param event_subscription_name: Event Subscription Name. Required. + :type event_subscription_name: str + :param renew_lock_options: RenewLockOptions. Required. + :type renew_lock_options: JSON + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with + MutableMapping + :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + async def renew_cloud_event_locks( + self, + topic_name: str, + event_subscription_name: str, + renew_lock_options: IO, + *, + content_type: str = "application/json", + **kwargs: Any + ) -> _models.RenewCloudEventLocksResult: + """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + renewed lockTokens, along with other failed lockTokens with their corresponding error + information. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param event_subscription_name: Event Subscription Name. Required. + :type event_subscription_name: str + :param renew_lock_options: RenewLockOptions. Required. + :type renew_lock_options: IO + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with + MutableMapping + :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult + :raises ~azure.core.exceptions.HttpResponseError: + """ + + + @distributed_trace_async + async def renew_cloud_event_locks( + self, + topic_name: str, + event_subscription_name: str, + renew_lock_options: Union[_models.RenewLockOptions, JSON, IO], + **kwargs: Any + ) -> _models.RenewCloudEventLocksResult: + """Renew lock for batch of Cloud Events. The server responds with an HTTP 200 status code if the + request is successfully accepted. The response body will include the set of successfully + renewed lockTokens, along with other failed lockTokens with their corresponding error + information. + + :param topic_name: Topic Name. Required. + :type topic_name: str + :param event_subscription_name: Event Subscription Name. Required. + :type event_subscription_name: str + :param renew_lock_options: RenewLockOptions. Is one of the following types: RenewLockOptions, + JSON, IO Required. + :type renew_lock_options: ~azure.eventgrid.models.RenewLockOptions or JSON or IO + :keyword content_type: Body parameter Content-Type. Known values are: application/json. Default + value is None. + :paramtype content_type: str + :keyword bool stream: Whether to stream the response of this operation. Defaults to False. You + will have to context manage the returned stream. + :return: RenewCloudEventLocksResult. The RenewCloudEventLocksResult is compatible with + MutableMapping + :rtype: ~azure.eventgrid.models.RenewCloudEventLocksResult + :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: Optional[str] = kwargs.pop('content_type', _headers.pop('Content-Type', None)) + cls: ClsType[_models.RenewCloudEventLocksResult] = kwargs.pop( + 'cls', None + ) + + content_type = content_type or "application/json" + _content = None + if isinstance(renew_lock_options, (IOBase, bytes)): + _content = renew_lock_options + else: + _content = json.dumps(renew_lock_options, cls=SdkJSONEncoder, exclude_readonly=True) # type: ignore + + _request = build_event_grid_renew_cloud_event_locks_request( + topic_name=topic_name, + event_subscription_name=event_subscription_name, + content_type=content_type, + api_version=self._config.api_version, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, 'str', skip_quote=True), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = kwargs.pop("stream", False) + pipeline_response: PipelineResponse = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access + _request, + stream=_stream, + **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + await response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + raise HttpResponseError(response=response) + + if _stream: + deserialized = response.iter_bytes() + else: + deserialized = _deserialize( + _models.RenewCloudEventLocksResult, + response.json() + ) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py index 6dc63a1bdfe0..6b20e911093d 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/aio/_operations/_patch.py @@ -55,8 +55,6 @@ async def publish_cloud_events( :keyword content_type: content type. Default value is "application/cloudevents-batch+json; charset=utf-8". :paramtype content_type: str - :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: @@ -89,8 +87,6 @@ async def publish_cloud_events( :keyword content_type: content type. Default value is "application/cloudevents+json; charset=utf-8". :paramtype content_type: str - :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: @@ -123,8 +119,6 @@ async def publish_cloud_events( :keyword content_type: content type. Default value is "application/cloudevents+json; charset=utf-8". :paramtype content_type: str - :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: @@ -157,8 +151,6 @@ async def publish_cloud_events( :keyword content_type: content type. Default value is "application/cloudevents+json; charset=utf-8". :paramtype content_type: str - :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: @@ -190,8 +182,6 @@ async def publish_cloud_events( :keyword content_type: content type. Default value is "application/cloudevents+json; charset=utf-8". :paramtype content_type: str - :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: diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py index bb787a2e0c74..7d7d97b1ac12 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/__init__.py @@ -8,22 +8,33 @@ from ._models import AcknowledgeOptions from ._models import AcknowledgeResult +from ._models import Error from ._models import FailedLockToken +from ._models import InnerError from ._models import RejectOptions from ._models import RejectResult from ._models import ReleaseOptions from ._models import ReleaseResult +from ._models import RenewCloudEventLocksResult +from ._models import RenewLockOptions + +from ._enums import ReleaseDelay from ._patch import __all__ as _patch_all from ._patch import * # pylint: disable=unused-wildcard-import from ._patch import patch_sdk as _patch_sdk __all__ = [ 'AcknowledgeOptions', 'AcknowledgeResult', + 'Error', 'FailedLockToken', + 'InnerError', 'RejectOptions', 'RejectResult', 'ReleaseOptions', 'ReleaseResult', + 'RenewCloudEventLocksResult', + 'RenewLockOptions', + 'ReleaseDelay', ] __all__.extend([p for p in _patch_all if p not in __all__]) _patch_sdk() diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_enums.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_enums.py new file mode 100644 index 000000000000..74f1f5e2eaf7 --- /dev/null +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_enums.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 enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class ReleaseDelay(int, Enum, metaclass=CaseInsensitiveEnumMeta): + """Supported delays for release operation. + """ + + BY0_SECONDS = 0 + """Release the event after 0 seconds.""" + BY10_SECONDS = 10 + """Release the event after 10 seconds.""" + BY60_SECONDS = 60 + """Release the event after 60 seconds.""" + BY600_SECONDS = 600 + """Release the event after 600 seconds.""" + BY3600_SECONDS = 3600 + """Release the event after 3600 seconds.""" diff --git a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py index 5cf7dd673acd..588b90e04c7d 100644 --- a/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py +++ b/sdk/eventgrid/azure-eventgrid/azure/eventgrid/models/_models.py @@ -19,16 +19,16 @@ class AcknowledgeOptions(_model_base.Model): - """Array of lock token strings for the corresponding received Cloud Events to be acknowledged. + """Array of lock tokens for the corresponding received Cloud Events to be acknowledged. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar lock_tokens: String array of lock tokens. Required. + :ivar lock_tokens: Array of lock tokens. Required. :vartype lock_tokens: list[str] """ lock_tokens: List[str] = rest_field(name="lockTokens") - """String array of lock tokens. Required.""" + """Array of lock tokens. Required.""" @overload def __init__( @@ -52,22 +52,22 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless- class AcknowledgeResult(_model_base.Model): """The result of the Acknowledge operation. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar failed_lock_tokens: Array of LockToken values for failed cloud events. Each LockToken - includes the lock token value along with the related error information (namely, the error code - and description). Required. + :ivar failed_lock_tokens: Array of FailedLockToken for failed cloud events. Each + FailedLockToken includes the lock token along with the related error information (namely, the + error code and description). Required. :vartype failed_lock_tokens: list[~azure.eventgrid.models.FailedLockToken] - :ivar succeeded_lock_tokens: Array of lock tokens values for the successfully acknowledged - cloud events. Required. + :ivar succeeded_lock_tokens: Array of lock tokens for the successfully acknowledged cloud + events. Required. :vartype succeeded_lock_tokens: list[str] """ failed_lock_tokens: List["_models.FailedLockToken"] = rest_field(name="failedLockTokens") - """Array of LockToken values for failed cloud events. Each LockToken includes the lock token value + """Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token along with the related error information (namely, the error code and description). Required.""" succeeded_lock_tokens: List[str] = rest_field(name="succeededLockTokens") - """Array of lock tokens values for the successfully acknowledged cloud events. Required.""" + """Array of lock tokens for the successfully acknowledged cloud events. Required.""" @overload def __init__( @@ -92,16 +92,16 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless- class BrokerProperties(_model_base.Model): """Properties of the Event Broker operation. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar lock_token: The token used to lock the event. Required. + :ivar lock_token: The token of the lock on the event. Required. :vartype lock_token: str :ivar delivery_count: The attempt count for delivering the event. Required. :vartype delivery_count: int """ lock_token: str = rest_field(name="lockToken") - """The token used to lock the event. Required.""" + """The token of the lock on the event. Required.""" delivery_count: int = rest_field(name="deliveryCount") """The attempt count for delivering the event. Required.""" @@ -111,7 +111,7 @@ class CloudEvent(_model_base.Model): """Properties of an event published to an Azure Messaging EventGrid Namespace topic using the CloudEvent 1.0 Schema. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar id: An identifier for the event. The combination of id and source must be unique for each distinct event. Required. @@ -164,37 +164,117 @@ class CloudEvent(_model_base.Model): +class Error(_model_base.Model): + """The error object. + + All required parameters must be populated in order to send to server. + + :ivar code: One of a server-defined set of error codes. Required. + :vartype code: str + :ivar message: A human-readable representation of the error. Required. + :vartype message: str + :ivar target: The target of the error. + :vartype target: str + :ivar details: An array of details about specific errors that led to this reported error. + :vartype details: list[~azure.eventgrid.models.Error] + :ivar innererror: An object containing more specific information than the current object about + the error. + :vartype innererror: ~azure.eventgrid.models.InnerError + """ + + code: str = rest_field() + """One of a server-defined set of error codes. Required.""" + message: str = rest_field() + """A human-readable representation of the error. Required.""" + target: Optional[str] = rest_field() + """The target of the error.""" + details: Optional[List["_models.Error"]] = rest_field() + """An array of details about specific errors that led to this reported error.""" + innererror: Optional["_models.InnerError"] = rest_field() + """An object containing more specific information than the current object about the error.""" + + @overload + def __init__( + self, + *, + code: str, + message: str, + target: Optional[str] = None, + details: Optional[List["_models.Error"]] = None, + innererror: Optional["_models.InnerError"] = None, + ): + ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + class FailedLockToken(_model_base.Model): """Failed LockToken information. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar lock_token: LockToken value. Required. + :ivar lock_token: The lock token of an entry in the request. Required. :vartype lock_token: str - :ivar error_code: Error code related to the token. Example of such error codes are BadToken: - which indicates the Token is not formatted correctly, TokenLost: which indicates that token is - not found, and InternalServerError: For any internal server errors. Required. - :vartype error_code: str - :ivar error_description: Description of the token error. Required. - :vartype error_description: str + :ivar error: Error information of the failed operation result for the lock token in the + request. Required. + :vartype error: ~azure.eventgrid.models.Error """ lock_token: str = rest_field(name="lockToken") - """LockToken value. Required.""" - error_code: str = rest_field(name="errorCode") - """Error code related to the token. Example of such error codes are BadToken: which indicates the - Token is not formatted correctly, TokenLost: which indicates that token is not found, and - InternalServerError: For any internal server errors. Required.""" - error_description: str = rest_field(name="errorDescription") - """Description of the token error. Required.""" + """The lock token of an entry in the request. Required.""" + error: "_models.Error" = rest_field() + """Error information of the failed operation result for the lock token in the request. Required.""" @overload def __init__( self, *, lock_token: str, - error_code: str, - error_description: str, + error: "_models.Error", + ): + ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class InnerError(_model_base.Model): + """An object containing more specific information about the error. As per Microsoft One API + guidelines - + https://github.com/Microsoft/api-guidelines/blob/vNext/Guidelines.md#7102-error-condition-responses. + + :ivar code: One of a server-defined set of error codes. + :vartype code: str + :ivar innererror: Inner error. + :vartype innererror: ~azure.eventgrid.models.InnerError + """ + + code: Optional[str] = rest_field() + """One of a server-defined set of error codes.""" + innererror: Optional["_models.InnerError"] = rest_field() + """Inner error.""" + + @overload + def __init__( + self, + *, + code: Optional[str] = None, + innererror: Optional["_models.InnerError"] = None, ): ... @@ -220,7 +300,7 @@ class PublishResult(_model_base.Model): class ReceiveDetails(_model_base.Model): """Receive operation details per Cloud Event. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar broker_properties: The Event Broker details. Required. :vartype broker_properties: ~azure.eventgrid.models.BrokerProperties @@ -238,7 +318,7 @@ class ReceiveDetails(_model_base.Model): class ReceiveResult(_model_base.Model): """Details of the Receive operation response. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. :ivar value: Array of receive responses, one per cloud event. Required. :vartype value: list[~azure.eventgrid.models.ReceiveDetails] @@ -250,16 +330,16 @@ class ReceiveResult(_model_base.Model): class RejectOptions(_model_base.Model): - """Array of lock token strings for the corresponding received Cloud Events to be rejected. + """Array of lock tokens for the corresponding received Cloud Events to be rejected. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar lock_tokens: String array of lock tokens. Required. + :ivar lock_tokens: Array of lock tokens. Required. :vartype lock_tokens: list[str] """ lock_tokens: List[str] = rest_field(name="lockTokens") - """String array of lock tokens. Required.""" + """Array of lock tokens. Required.""" @overload def __init__( @@ -283,22 +363,22 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless- class RejectResult(_model_base.Model): """The result of the Reject operation. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar failed_lock_tokens: Array of LockToken values for failed cloud events. Each LockToken - includes the lock token value along with the related error information (namely, the error code - and description). Required. + :ivar failed_lock_tokens: Array of FailedLockToken for failed cloud events. Each + FailedLockToken includes the lock token along with the related error information (namely, the + error code and description). Required. :vartype failed_lock_tokens: list[~azure.eventgrid.models.FailedLockToken] - :ivar succeeded_lock_tokens: Array of lock tokens values for the successfully rejected cloud - events. Required. + :ivar succeeded_lock_tokens: Array of lock tokens for the successfully rejected cloud events. + Required. :vartype succeeded_lock_tokens: list[str] """ failed_lock_tokens: List["_models.FailedLockToken"] = rest_field(name="failedLockTokens") - """Array of LockToken values for failed cloud events. Each LockToken includes the lock token value + """Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token along with the related error information (namely, the error code and description). Required.""" succeeded_lock_tokens: List[str] = rest_field(name="succeededLockTokens") - """Array of lock tokens values for the successfully rejected cloud events. Required.""" + """Array of lock tokens for the successfully rejected cloud events. Required.""" @overload def __init__( @@ -321,16 +401,16 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless- class ReleaseOptions(_model_base.Model): - """Array of lock token strings for the corresponding received Cloud Events to be released. + """Array of lock tokens for the corresponding received Cloud Events to be released. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar lock_tokens: String array of lock tokens. Required. + :ivar lock_tokens: Array of lock tokens. Required. :vartype lock_tokens: list[str] """ lock_tokens: List[str] = rest_field(name="lockTokens") - """String array of lock tokens. Required.""" + """Array of lock tokens. Required.""" @overload def __init__( @@ -354,22 +434,61 @@ def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless- class ReleaseResult(_model_base.Model): """The result of the Release operation. - All required parameters must be populated in order to send to Azure. + All required parameters must be populated in order to send to server. - :ivar failed_lock_tokens: Array of LockToken values for failed cloud events. Each LockToken - includes the lock token value along with the related error information (namely, the error code - and description). Required. + :ivar failed_lock_tokens: Array of FailedLockToken for failed cloud events. Each + FailedLockToken includes the lock token along with the related error information (namely, the + error code and description). Required. :vartype failed_lock_tokens: list[~azure.eventgrid.models.FailedLockToken] - :ivar succeeded_lock_tokens: Array of lock tokens values for the successfully released cloud - events. Required. + :ivar succeeded_lock_tokens: Array of lock tokens for the successfully released cloud events. + Required. + :vartype succeeded_lock_tokens: list[str] + """ + + failed_lock_tokens: List["_models.FailedLockToken"] = rest_field(name="failedLockTokens") + """Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token + along with the related error information (namely, the error code and description). Required.""" + succeeded_lock_tokens: List[str] = rest_field(name="succeededLockTokens") + """Array of lock tokens for the successfully released cloud events. Required.""" + + @overload + def __init__( + self, + *, + failed_lock_tokens: List["_models.FailedLockToken"], + succeeded_lock_tokens: List[str], + ): + ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) + + +class RenewCloudEventLocksResult(_model_base.Model): + """The result of the RenewLock operation. + + All required parameters must be populated in order to send to server. + + :ivar failed_lock_tokens: Array of FailedLockToken for failed cloud events. Each + FailedLockToken includes the lock token along with the related error information (namely, the + error code and description). Required. + :vartype failed_lock_tokens: list[~azure.eventgrid.models.FailedLockToken] + :ivar succeeded_lock_tokens: Array of lock tokens for the successfully renewed locks. Required. :vartype succeeded_lock_tokens: list[str] """ failed_lock_tokens: List["_models.FailedLockToken"] = rest_field(name="failedLockTokens") - """Array of LockToken values for failed cloud events. Each LockToken includes the lock token value + """Array of FailedLockToken for failed cloud events. Each FailedLockToken includes the lock token along with the related error information (namely, the error code and description). Required.""" succeeded_lock_tokens: List[str] = rest_field(name="succeededLockTokens") - """Array of lock tokens values for the successfully released cloud events. Required.""" + """Array of lock tokens for the successfully renewed locks. Required.""" @overload def __init__( @@ -389,3 +508,34 @@ def __init__(self, mapping: Mapping[str, Any]): def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation super().__init__(*args, **kwargs) + + +class RenewLockOptions(_model_base.Model): + """Array of lock tokens for the corresponding received Cloud Events to be renewed. + + All required parameters must be populated in order to send to server. + + :ivar lock_tokens: Array of lock tokens. Required. + :vartype lock_tokens: list[str] + """ + + lock_tokens: List[str] = rest_field(name="lockTokens") + """Array of lock tokens. Required.""" + + @overload + def __init__( + self, + *, + lock_tokens: List[str], + ): + ... + + @overload + def __init__(self, mapping: Mapping[str, Any]): + """ + :param mapping: raw JSON to initialize the model. + :type mapping: Mapping[str, Any] + """ + + def __init__(self, *args: Any, **kwargs: Any) -> None:# pylint: disable=useless-super-delegation + super().__init__(*args, **kwargs) diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_acknowledge_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_acknowledge_operation_async.py index bea9e4c5cb7e..bc53812fa804 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_acknowledge_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_acknowledge_operation_async.py @@ -12,8 +12,8 @@ EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] -TOPIC_NAME: str = os.environ["TOPIC_NAME"] -EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENT_SUBSCRIPTION_NAME"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] # Create a client client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) @@ -27,7 +27,7 @@ async def run(): ack_events = await client.acknowledge_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=lock_tokens, + acknowledge_options=lock_tokens, ) print(ack_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py index 19e5863f7f2b..d31666095998 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_all_operations_async.py @@ -13,8 +13,8 @@ EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] -TOPIC_NAME: str = os.environ["TOPIC_NAME"] -EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENT_SUBSCRIPTION_NAME"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] # Create a client @@ -86,7 +86,7 @@ async def run(): release_result = await client.release_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=release_tokens, + release_options=release_tokens, ) except HttpResponseError: raise @@ -100,7 +100,7 @@ async def run(): ack_result = await client.acknowledge_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=ack_tokens, + acknowledge_options=ack_tokens, ) except HttpResponseError: raise @@ -114,7 +114,7 @@ async def run(): reject_result = await client.reject_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=reject_tokens, + reject_options=reject_tokens, ) except HttpResponseError: raise diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py new file mode 100644 index 000000000000..62d02f707f80 --- /dev/null +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_receive_renew_async.py @@ -0,0 +1,49 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os +import asyncio +from azure.core.credentials import AzureKeyCredential +from azure.eventgrid.aio import EventGridClient +from azure.eventgrid.models import * +from azure.core.messaging import CloudEvent +from azure.core.exceptions import HttpResponseError + + +EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] +EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] + + +async def run(): + # Create a client + client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) + + async with client: + try: + # Publish a CloudEvent + cloud_event = CloudEvent(data="hello", source="https://example.com", type="example") + await client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event) + + # Receive CloudEvents and parse out lock tokens + receive_result = await client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10) + lock_tokens_to_release = [] + for item in receive_result.value: + lock_tokens_to_release.append(item.broker_properties.lock_token) + + # Renew lock tokens + lock_tokens = RenewLockOptions(lock_tokens=lock_tokens_to_release) + renew_events = await client.renew_cloud_event_locks( + topic_name=TOPIC_NAME, + event_subscription_name=EVENT_SUBSCRIPTION_NAME, + renew_lock_options=lock_tokens, + ) + print("Renewed Event:", renew_events) + except HttpResponseError: + raise + +if __name__ == "__main__": + asyncio.get_event_loop().run_until_complete(run()) \ No newline at end of file diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py new file mode 100644 index 000000000000..895640a9d8f6 --- /dev/null +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_publish_release_receive_async.py @@ -0,0 +1,65 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os +import asyncio +from azure.core.credentials import AzureKeyCredential +from azure.eventgrid.aio import EventGridClient +from azure.eventgrid.models import * +from azure.core.messaging import CloudEvent +from azure.core.exceptions import HttpResponseError + + +EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] +EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] + + +async def run(): + # Create a client + client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) + + async with client: + try: + # Publish a CloudEvent + cloud_event = CloudEvent(data="hello", source="https://example.com", type="example") + await client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event) + + # Receive CloudEvents and parse out lock tokens + receive_result = await client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + lock_tokens_to_release = [] + for item in receive_result.value: + lock_tokens_to_release.append(item.broker_properties.lock_token) + + print("Received events:", receive_result.value) + + # Release a LockToken + release_token = ReleaseOptions(lock_tokens=lock_tokens_to_release) + release_events = await client.release_cloud_events( + topic_name=TOPIC_NAME, + event_subscription_name=EVENT_SUBSCRIPTION_NAME, + release_delay_in_seconds=60, + release_options=release_token, + ) + print("Released Event:", release_events) + + # Receive CloudEvents again + receive_result = await client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + print("Received events after release:", receive_result.value) + + # Acknowledge LockTokens + acknowledge_token = AcknowledgeOptions(lock_tokens=lock_tokens_to_release) + acknowledge_events = await client.acknowledge_cloud_events( + topic_name=TOPIC_NAME, + event_subscription_name=EVENT_SUBSCRIPTION_NAME, + acknowledge_options=acknowledge_token, + ) + print("Acknowledged events after release:", acknowledge_events) + except HttpResponseError: + raise + +if __name__ == "__main__": + asyncio.get_event_loop().run_until_complete(run()) \ No newline at end of file diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_receive_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_receive_operation_async.py index a25f09a40fed..6d136c5ff5e4 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_receive_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_receive_operation_async.py @@ -12,8 +12,8 @@ EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] -TOPIC_NAME: str = os.environ["TOPIC_NAME"] -EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENT_SUBSCRIPTION_NAME"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] # Create a client client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_reject_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_reject_operation_async.py index e46356e08fbf..c1ea4b70c3dd 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_reject_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_reject_operation_async.py @@ -12,22 +12,22 @@ EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] -TOPIC_NAME: str = os.environ["TOPIC_NAME"] -EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENT_SUBSCRIPTION_NAME"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] # Create a client client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) async def run(): - # Release a LockToken + # Reject a LockToken try: async with client: tokens = RejectOptions(lock_tokens=["token"]) reject_events = await client.reject_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=tokens, + reject_options=tokens, ) print(reject_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_release_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_release_operation_async.py index 117dadf79287..0ef5fc8dd4ab 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_release_operation_async.py +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_release_operation_async.py @@ -12,8 +12,8 @@ EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] -TOPIC_NAME: str = os.environ["TOPIC_NAME"] -EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENT_SUBSCRIPTION_NAME"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] # Create a client client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) @@ -27,7 +27,8 @@ async def run(): release_events = await client.release_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=tokens, + release_delay_in_seconds=10, + release_options=tokens, ) print(release_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py new file mode 100644 index 000000000000..89938ee40978 --- /dev/null +++ b/sdk/eventgrid/azure-eventgrid/samples/async_samples/eventgrid_client_samples/sample_renew_locks_operation_async.py @@ -0,0 +1,35 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os +import asyncio +from azure.core.credentials import AzureKeyCredential +from azure.eventgrid.aio import EventGridClient +from azure.eventgrid.models import * +from azure.core.exceptions import HttpResponseError + +EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] +EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] + +# Create a client +client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) + +async def run(): + # Renew a lockToken + try: + lock_tokens = RenewLockOptions(lock_tokens=["token"]) + release_events = await client.renew_cloud_event_locks( + topic_name=TOPIC_NAME, + event_subscription_name=EVENT_SUBSCRIPTION_NAME, + renew_lock_options=lock_tokens, + ) + print(release_events) + except HttpResponseError: + raise + +if __name__ == "__main__": + asyncio.get_event_loop().run_until_complete(run()) diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_aad_auth_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_aad_auth_operation.py new file mode 100644 index 000000000000..780c9cc975e2 --- /dev/null +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_aad_auth_operation.py @@ -0,0 +1,14 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os +from azure.eventgrid import EventGridClient +from azure.eventgrid.models import * +from azure.identity import DefaultAzureCredential + +EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] + +# Create a client using DefaultAzureCredential +client = EventGridClient(EVENTGRID_ENDPOINT, DefaultAzureCredential()) \ No newline at end of file diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_acknowledge_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_acknowledge_operation.py index 78bfdc1162fb..72a5518c6228 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_acknowledge_operation.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_acknowledge_operation.py @@ -11,20 +11,20 @@ EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] -TOPIC_NAME: str = os.environ["TOPIC_NAME"] -EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENT_SUBSCRIPTION_NAME"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] # Create a client client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) -# Acknowledge a batch of CloudEvents +# Acknowledge a CloudEvent try: lock_tokens = AcknowledgeOptions(lock_tokens=["token"]) ack_events = client.acknowledge_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=lock_tokens, + acknowledge_options=lock_tokens, ) print(ack_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py index db6863811b7f..52d12730c41d 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_all_operations.py @@ -13,8 +13,8 @@ EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] -TOPIC_NAME: str = os.environ["TOPIC_NAME"] -EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENT_SUBSCRIPTION_NAME"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] # Create a client @@ -79,7 +79,7 @@ release_result = client.release_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=release_tokens, + release_options=release_tokens, ) except HttpResponseError: raise @@ -93,7 +93,7 @@ ack_result = client.acknowledge_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=ack_tokens, + acknowledge_options=ack_tokens, ) except HttpResponseError: raise @@ -107,7 +107,7 @@ reject_result = client.reject_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=reject_tokens, + reject_options=reject_tokens, ) except HttpResponseError: raise diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py new file mode 100644 index 000000000000..38492b231d7b --- /dev/null +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_receive_renew.py @@ -0,0 +1,43 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os +from azure.core.credentials import AzureKeyCredential +from azure.eventgrid import EventGridClient +from azure.eventgrid.models import * +from azure.core.messaging import CloudEvent +from azure.core.exceptions import HttpResponseError + + +EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] +EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] + +# Create a client +client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) + + +try: + # Publish a CloudEvent + cloud_event = CloudEvent(data="hello", source="https://example.com", type="example") + client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event) + + # Receive CloudEvents and parse out lock tokens + receive_result = client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=10, max_wait_time=10) + lock_tokens_to_release = [] + for item in receive_result.value: + lock_tokens_to_release.append(item.broker_properties.lock_token) + + # Renew a lock token + lock_tokens = RenewLockOptions(lock_tokens=lock_tokens_to_release) + renew_events = client.renew_cloud_event_locks( + topic_name=TOPIC_NAME, + event_subscription_name=EVENT_SUBSCRIPTION_NAME, + renew_lock_options=lock_tokens, + ) + print("Renewed Event:", renew_events) +except HttpResponseError: + raise diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py new file mode 100644 index 000000000000..ef97375c3f0b --- /dev/null +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_publish_release_receive.py @@ -0,0 +1,59 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os +from azure.core.credentials import AzureKeyCredential +from azure.eventgrid import EventGridClient +from azure.eventgrid.models import * +from azure.core.messaging import CloudEvent +from azure.core.exceptions import HttpResponseError + + +EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] +EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] + +# Create a client +client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) + + +try: + # Publish a CloudEvent + cloud_event = CloudEvent(data="hello", source="https://example.com", type="example") + client.publish_cloud_events(topic_name=TOPIC_NAME, body=cloud_event) + + # Receive CloudEvents and parse out lock tokens + receive_result = client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + lock_tokens_to_release = [] + for item in receive_result.value: + lock_tokens_to_release.append(item.broker_properties.lock_token) + + print("Received events:", receive_result.value) + + # Release a LockToken + release_token = ReleaseOptions(lock_tokens=lock_tokens_to_release) + release_events = client.release_cloud_events( + topic_name=TOPIC_NAME, + event_subscription_name=EVENT_SUBSCRIPTION_NAME, + release_delay_in_seconds=60, + release_options=release_token, + ) + print("Released Event:", release_events) + + # Receive CloudEvents again + receive_result = client.receive_cloud_events(topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, max_events=1, max_wait_time=15) + print("Received events after release:", receive_result.value) + + # Acknowledge a LockToken + acknowledge_token = AcknowledgeOptions(lock_tokens=lock_tokens_to_release) + acknowledge_events = client.acknowledge_cloud_events( + topic_name=TOPIC_NAME, + event_subscription_name=EVENT_SUBSCRIPTION_NAME, + acknowledge_options=acknowledge_token, + ) + print("Acknowledged events after release:", acknowledge_events) +except HttpResponseError: + raise diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_receive_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_receive_operation.py index aefd6c39275f..20252bda9cac 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_receive_operation.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_receive_operation.py @@ -11,8 +11,8 @@ EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] -TOPIC_NAME: str = os.environ["TOPIC_NAME"] -EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENT_SUBSCRIPTION_NAME"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] # Create a client client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_reject_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_reject_operation.py index a24a07a8ed74..3f6e87b8e050 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_reject_operation.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_reject_operation.py @@ -11,8 +11,8 @@ EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] -TOPIC_NAME: str = os.environ["TOPIC_NAME"] -EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENT_SUBSCRIPTION_NAME"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] # Create a client client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) @@ -23,7 +23,7 @@ reject_events = client.reject_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=lock_tokens, + reject_options=lock_tokens, ) print(reject_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_release_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_release_operation.py index 60db8ed9f5e6..8d7df562004a 100644 --- a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_release_operation.py +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_release_operation.py @@ -11,8 +11,8 @@ EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] -TOPIC_NAME: str = os.environ["TOPIC_NAME"] -EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENT_SUBSCRIPTION_NAME"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] # Create a client client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) @@ -23,7 +23,8 @@ release_events = client.release_cloud_events( topic_name=TOPIC_NAME, event_subscription_name=EVENT_SUBSCRIPTION_NAME, - lock_tokens=lock_tokens, + release_delay_in_seconds=3600, + release_options=lock_tokens, ) print(release_events) except HttpResponseError: diff --git a/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_renew_locks_operation.py b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_renew_locks_operation.py new file mode 100644 index 000000000000..82a4fd9f5f47 --- /dev/null +++ b/sdk/eventgrid/azure-eventgrid/samples/sync_samples/eventgrid_client_samples/sample_renew_locks_operation.py @@ -0,0 +1,30 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- +import os +from azure.core.credentials import AzureKeyCredential +from azure.eventgrid import EventGridClient +from azure.eventgrid.models import * +from azure.core.exceptions import HttpResponseError + +EVENTGRID_KEY: str = os.environ["EVENTGRID_KEY"] +EVENTGRID_ENDPOINT: str = os.environ["EVENTGRID_ENDPOINT"] +TOPIC_NAME: str = os.environ["EVENTGRID_TOPIC_NAME"] +EVENT_SUBSCRIPTION_NAME: str = os.environ["EVENTGRID_EVENT_SUBSCRIPTION_NAME"] + +# Create a client +client = EventGridClient(EVENTGRID_ENDPOINT, AzureKeyCredential(EVENTGRID_KEY)) + +# Renew a lockToken +try: + lock_tokens = RenewLockOptions(lock_tokens=["token"]) + release_events = client.renew_cloud_event_locks( + topic_name=TOPIC_NAME, + event_subscription_name=EVENT_SUBSCRIPTION_NAME, + renew_lock_options=lock_tokens, + ) + print(release_events) +except HttpResponseError: + raise diff --git a/sdk/eventgrid/azure-eventgrid/setup.py b/sdk/eventgrid/azure-eventgrid/setup.py index 7a861fa486eb..adf215e92d0e 100644 --- a/sdk/eventgrid/azure-eventgrid/setup.py +++ b/sdk/eventgrid/azure-eventgrid/setup.py @@ -60,7 +60,7 @@ ), include_package_data=True, package_data={ - "pytyped": ["py.typed"], + "azure.eventgrid": ["py.typed"], }, install_requires=[ "isodate>=0.6.1", diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py index ed092f4e3b39..d08679335a42 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client.py @@ -23,12 +23,10 @@ def create_eg_client(self, endpoint, key): return client - @pytest.mark.live_test_only - def test_publish_binary_mode_xml(self): - eventgrid_endpoint = os.environ['EVENTGRID_ENDPOINT'] - eventgrid_key = os.environ['EVENTGRID_KEY'] - eventgrid_topic_name = os.environ['EVENTGRID_TOPIC_NAME'] - eventgrid_event_subscription_name = os.environ['EVENTGRID_EVENT_SUBSCRIPTION_NAME'] + @pytest.mark.live_test_only() + @EventGridPreparer() + @recorded_by_proxy + def test_publish_binary_mode_xml(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) from xml.etree import ElementTree as ET @@ -55,13 +53,18 @@ def test_publish_binary_mode_xml(self): assert my_returned_event.datacontenttype == 'text/xml' assert my_returned_event.type == "Contoso.Items.ItemReceived" + tokens = [] + for detail in events.value: + token = detail.broker_properties.lock_token + tokens.append(token) + rejected_result = client.reject_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, reject_options=RejectOptions(lock_tokens=tokens)) + + - @pytest.mark.live_test_only - def test_publish_binary_mode_cloud_event(self): - eventgrid_endpoint = os.environ['EVENTGRID_ENDPOINT'] - eventgrid_key = os.environ['EVENTGRID_KEY'] - eventgrid_topic_name = os.environ['EVENTGRID_TOPIC_NAME'] - eventgrid_event_subscription_name = os.environ['EVENTGRID_EVENT_SUBSCRIPTION_NAME'] + @pytest.mark.live_test_only() + @EventGridPreparer() + @recorded_by_proxy + def test_publish_binary_mode_cloud_event(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) event = CloudEvent( @@ -84,12 +87,16 @@ def test_publish_binary_mode_cloud_event(self): assert my_returned_event.datacontenttype == 'text/plain' assert my_returned_event.type == "Contoso.Items.ItemReceived" + tokens = [] + for detail in events.value: + token = detail.broker_properties.lock_token + tokens.append(token) + rejected_result = client.reject_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, reject_options=RejectOptions(lock_tokens=tokens)) - @pytest.mark.live_test_only - def test_publish_binary_mode_incorrect_cloud_event(self): - eventgrid_endpoint = os.environ['EVENTGRID_ENDPOINT'] - eventgrid_key = os.environ['EVENTGRID_KEY'] - eventgrid_topic_name = os.environ['EVENTGRID_TOPIC_NAME'] + + @EventGridPreparer() + @recorded_by_proxy + def test_publish_binary_mode_incorrect_cloud_event(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) event = CloudEvent( @@ -105,12 +112,9 @@ def test_publish_binary_mode_incorrect_cloud_event(self): eventgrid_topic_name, body=event, binary_mode=True ) - @pytest.mark.live_test_only - def test_publish_binary_mode_list_cloud_event(self): - eventgrid_endpoint = os.environ['EVENTGRID_ENDPOINT'] - eventgrid_key = os.environ['EVENTGRID_KEY'] - eventgrid_topic_name = os.environ['EVENTGRID_TOPIC_NAME'] - eventgrid_event_subscription_name = os.environ['EVENTGRID_EVENT_SUBSCRIPTION_NAME'] + @EventGridPreparer() + @recorded_by_proxy + def test_publish_binary_mode_list_cloud_event(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) event = CloudEvent( @@ -126,12 +130,10 @@ def test_publish_binary_mode_list_cloud_event(self): eventgrid_topic_name, body=[event], binary_mode=True ) - @pytest.mark.live_test_only - def test_publish_binary_mode_combinations(self): - eventgrid_endpoint = os.environ['EVENTGRID_ENDPOINT'] - eventgrid_key = os.environ['EVENTGRID_KEY'] - eventgrid_topic_name = os.environ['EVENTGRID_TOPIC_NAME'] - eventgrid_event_subscription_name = os.environ['EVENTGRID_EVENT_SUBSCRIPTION_NAME'] + @pytest.mark.live_test_only() + @EventGridPreparer() + @recorded_by_proxy + def test_publish_binary_mode_combinations(self, eventgrid_endpoint, eventgrid_key, eventgrid_topic_name, eventgrid_event_subscription_name): client = self.create_eg_client(eventgrid_endpoint, eventgrid_key) event = CloudEvent( @@ -153,6 +155,14 @@ def test_publish_binary_mode_combinations(self): eventgrid_topic_name, body=dict_event, binary_mode=True ) + events = client.receive_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name,max_events=1) + tokens = [] + for detail in events.value: + token = detail.broker_properties.lock_token + tokens.append(token) + rejected_result = client.reject_cloud_events(eventgrid_topic_name, eventgrid_event_subscription_name, reject_options=RejectOptions(lock_tokens=tokens)) + + @pytest.mark.skip("need to update conftest") @EventGridPreparer() @recorded_by_proxy diff --git a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py index 108b2c1a8e71..cfdec3f1c34d 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py +++ b/sdk/eventgrid/azure-eventgrid/tests/test_eg_client_exceptions.py @@ -107,7 +107,7 @@ def test_acknowledge_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_k with pytest.raises(ResourceNotFoundError): lock_tokens = AcknowledgeOptions(lock_tokens=["faketoken"]) client.acknowledge_cloud_events( - "faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens + "faketopic", eventgrid_event_subscription_name, acknowledge_options=lock_tokens ) @EventGridPreparer() @@ -118,7 +118,7 @@ def test_release_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key, with pytest.raises(ResourceNotFoundError): lock_tokens = ReleaseOptions(lock_tokens=["faketoken"]) client.release_cloud_events( - "faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens + "faketopic", eventgrid_event_subscription_name, release_options=lock_tokens ) @EventGridPreparer() @@ -129,7 +129,7 @@ def test_reject_cloud_event_not_found(self, eventgrid_endpoint, eventgrid_key, e with pytest.raises(ResourceNotFoundError): client.reject_cloud_events( - "faketopic", eventgrid_event_subscription_name, lock_tokens=lock_tokens + "faketopic", eventgrid_event_subscription_name, reject_options=lock_tokens ) @EventGridPreparer() @@ -139,7 +139,7 @@ def test_acknowledge_cloud_event_invalid_token(self, eventgrid_endpoint, eventgr lock_tokens = AcknowledgeOptions(lock_tokens=["faketoken"]) ack = client.acknowledge_cloud_events( - eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=lock_tokens + eventgrid_topic_name, eventgrid_event_subscription_name, acknowledge_options=lock_tokens ) assert type(ack) == AcknowledgeResult assert ack.succeeded_lock_tokens == [] @@ -153,7 +153,7 @@ def test_release_cloud_event_invalid_token(self, eventgrid_endpoint, eventgrid_k lock_tokens = ReleaseOptions(lock_tokens=["faketoken"]) release = client.release_cloud_events( - eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=lock_tokens + eventgrid_topic_name, eventgrid_event_subscription_name, release_options=lock_tokens ) assert type(release) == ReleaseResult assert release.succeeded_lock_tokens == [] @@ -167,7 +167,7 @@ def test_reject_cloud_event_invalid_token(self, eventgrid_endpoint, eventgrid_ke lock_tokens = RejectOptions(lock_tokens=["faketoken"]) reject = client.reject_cloud_events( - eventgrid_topic_name, eventgrid_event_subscription_name, lock_tokens=lock_tokens + eventgrid_topic_name, eventgrid_event_subscription_name, reject_options=lock_tokens ) assert type(reject) == RejectResult assert reject.succeeded_lock_tokens == [] diff --git a/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py b/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py index 5cbcdc2c8f39..168feb277b4f 100644 --- a/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py +++ b/sdk/eventgrid/azure-eventgrid/tests/unittests/test_binary_mode.py @@ -7,7 +7,6 @@ import json import base64 from azure.eventgrid._operations._patch import _to_http_request -from azure.eventgrid._model_base import AzureJSONEncoder from azure.eventgrid.models import * from azure.core.messaging import CloudEvent diff --git a/sdk/eventgrid/azure-eventgrid/tsp-location.yaml b/sdk/eventgrid/azure-eventgrid/tsp-location.yaml index 94b72d10f055..e5a84555e08a 100644 --- a/sdk/eventgrid/azure-eventgrid/tsp-location.yaml +++ b/sdk/eventgrid/azure-eventgrid/tsp-location.yaml @@ -1,4 +1,4 @@ cleanup: false -commit: a48dbfd411ddcb91ad1e09c47d1def14e79b8905 +commit: 116c17a841a9b37a3fce426558099b5ad5fe16de directory: specification/eventgrid/Azure.Messaging.EventGrid repo: Azure/azure-rest-api-specs \ No newline at end of file diff --git a/sdk/eventgrid/test-resources.json b/sdk/eventgrid/test-resources.json index e41dbdec3be1..a346523e7fd9 100644 --- a/sdk/eventgrid/test-resources.json +++ b/sdk/eventgrid/test-resources.json @@ -27,13 +27,7 @@ "description": "The application client secret used to run tests." } }, - "location": { - "type": "string", - "defaultValue": "eastus", - "metadata": { - "description": "The resource location" - } - } + }, "variables": { "namespaceName": "[format('{0}-2', parameters('baseName'))]", @@ -55,9 +49,9 @@ "resources": [ { "type": "Microsoft.EventGrid/namespaces", - "apiVersion": "2023-06-01-preview", + "apiVersion": "2023-12-15-preview", "name": "[variables('namespaceName')]", - "location": "[parameters('location')]", + "location": "[resourceGroup().location]", "sku": { "name": "Standard", "capacity": 1 @@ -69,7 +63,7 @@ }, { "type": "Microsoft.EventGrid/namespaces/topics", - "apiVersion": "2023-06-01-preview", + "apiVersion": "2023-12-15-preview", "name": "[format('{0}/{1}', variables('namespaceName'), variables('topicName'))]", "properties": { "publisherType": "Custom", @@ -82,7 +76,7 @@ }, { "type": "Microsoft.EventGrid/namespaces/topics/eventSubscriptions", - "apiVersion": "2023-06-01-preview", + "apiVersion": "2023-12-15-preview", "name": "[format('{0}/{1}/{2}', variables('namespaceName'), variables('topicName'), variables('subscriptionName'))]", "properties": { "deliveryConfiguration": { @@ -289,11 +283,11 @@ }, "EVENTGRID_KEY": { "type": "string", - "value": "[listKeys(resourceId('Microsoft.EventGrid/namespaces', variables('namespaceName')), '2023-06-01-preview').key1]" + "value": "[listKeys(resourceId('Microsoft.EventGrid/namespaces', variables('namespaceName')), '2023-12-15-preview').key1]" }, "EVENTGRID_ENDPOINT": { "type": "string", - "value": "[format('https://{0}', reference(resourceId('Microsoft.EventGrid/namespaces', variables('namespaceName')), '2023-06-01-preview').topicsConfiguration.hostname)]" + "value": "[format('https://{0}', reference(resourceId('Microsoft.EventGrid/namespaces', variables('namespaceName')), '2023-12-15-preview').topicsConfiguration.hostname)]" }, "EVENTGRID_TOPIC_NAME": { "type": "string", diff --git a/sdk/eventgrid/tests.yml b/sdk/eventgrid/tests.yml index 0d2e952c0c24..cf20c2c1580a 100644 --- a/sdk/eventgrid/tests.yml +++ b/sdk/eventgrid/tests.yml @@ -5,6 +5,7 @@ extends: parameters: ServiceDirectory: eventgrid BuildTargetingString: azure-eventgrid* + Location: eastus MatrixReplace: - TestSamples=.*/true EnvVars: