Team Ai
Datasetpublic

codekingpro/portable-devtools

sourceHugging Faceupdated 5mo agoView on Hugging Face
1likes14kdownloads
operations_client.py379 linesDownload Raw Back to operations_v1
1# Copyright 2017 Google LLC2#3# Licensed under the Apache License, Version 2.0 (the "License");4# you may not use this file except in compliance with the License.5# You may obtain a copy of the License at6#7#     http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# distributed under the License is distributed on an "AS IS" BASIS,11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12# See the License for the specific language governing permissions and13# limitations under the License.14 15"""A client for the google.longrunning.operations meta-API.16 17This is a client that deals with long-running operations that follow the18pattern outlined by the `Google API Style Guide`_.19 20When an API method normally takes long time to complete, it can be designed to21return ``Operation`` to the client, and the client can use this interface to22receive the real response asynchronously by polling the operation resource to23receive the response.24 25It is not a separate service, but rather an interface implemented by a larger26service. The protocol-level definition is available at27`google/longrunning/operations.proto`_. Typically, this will be constructed28automatically by another client class to deal with operations.29 30.. _Google API Style Guide:31    https://cloud.google.com/apis/design/design_pattern32    s#long_running_operations33.. _google/longrunning/operations.proto:34    https://github.com/googleapis/googleapis/blob/master/google/longrunning35    /operations.proto36"""37 38import functools39 40from google.api_core import exceptions as core_exceptions41from google.api_core import gapic_v142from google.api_core import page_iterator43from google.api_core import retry as retries44from google.api_core import timeout as timeouts45from google.longrunning import operations_pb246from grpc import Compression47 48 49class OperationsClient(object):50    """Client for interacting with long-running operations within a service.51 52    Args:53        channel (grpc.Channel): The gRPC channel associated with the service54            that implements the ``google.longrunning.operations`` interface.55        client_config (dict):56            A dictionary of call options for each method. If not specified57            the default configuration is used.58    """59 60    def __init__(self, channel, client_config=None):61        # Create the gRPC client stub.62        self.operations_stub = operations_pb2.OperationsStub(channel)63 64        default_retry = retries.Retry(65            initial=0.1,  # seconds66            maximum=60.0,  # seconds67            multiplier=1.3,68            predicate=retries.if_exception_type(69                core_exceptions.DeadlineExceeded,70                core_exceptions.ServiceUnavailable,71            ),72            timeout=600.0,  # seconds73        )74        default_timeout = timeouts.TimeToDeadlineTimeout(timeout=600.0)75 76        default_compression = Compression.NoCompression77 78        self._get_operation = gapic_v1.method.wrap_method(79            self.operations_stub.GetOperation,80            default_retry=default_retry,81            default_timeout=default_timeout,82            default_compression=default_compression,83        )84 85        self._list_operations = gapic_v1.method.wrap_method(86            self.operations_stub.ListOperations,87            default_retry=default_retry,88            default_timeout=default_timeout,89            default_compression=default_compression,90        )91 92        self._cancel_operation = gapic_v1.method.wrap_method(93            self.operations_stub.CancelOperation,94            default_retry=default_retry,95            default_timeout=default_timeout,96            default_compression=default_compression,97        )98 99        self._delete_operation = gapic_v1.method.wrap_method(100            self.operations_stub.DeleteOperation,101            default_retry=default_retry,102            default_timeout=default_timeout,103            default_compression=default_compression,104        )105 106    # Service calls107    def get_operation(108        self,109        name,110        retry=gapic_v1.method.DEFAULT,111        timeout=gapic_v1.method.DEFAULT,112        compression=gapic_v1.method.DEFAULT,113        metadata=None,114    ):115        """Gets the latest state of a long-running operation.116 117        Clients can use this method to poll the operation result at intervals118        as recommended by the API service.119 120        Example:121            >>> from google.api_core import operations_v1122            >>> api = operations_v1.OperationsClient()123            >>> name = ''124            >>> response = api.get_operation(name)125 126        Args:127            name (str): The name of the operation resource.128            retry (google.api_core.retry.Retry): The retry strategy to use129                when invoking the RPC. If unspecified, the default retry from130                the client configuration will be used. If ``None``, then this131                method will not retry the RPC at all.132            timeout (float): The amount of time in seconds to wait for the RPC133                to complete. Note that if ``retry`` is used, this timeout134                applies to each individual attempt and the overall time it135                takes for this method to complete may be longer. If136                unspecified, the the default timeout in the client137                configuration is used. If ``None``, then the RPC method will138                not time out.139            compression (grpc.Compression): An element of grpc.compression140                e.g. grpc.compression.Gzip.141            metadata (Optional[List[Tuple[str, str]]]):142                Additional gRPC metadata.143 144        Returns:145            google.longrunning.operations_pb2.Operation: The state of the146                operation.147 148        Raises:149            google.api_core.exceptions.GoogleAPICallError: If an error occurred150                while invoking the RPC, the appropriate ``GoogleAPICallError``151                subclass will be raised.152        """153        request = operations_pb2.GetOperationRequest(name=name)154 155        # Add routing header156        metadata = metadata or []157        metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))158 159        return self._get_operation(160            request,161            retry=retry,162            timeout=timeout,163            compression=compression,164            metadata=metadata,165        )166 167    def list_operations(168        self,169        name,170        filter_,171        retry=gapic_v1.method.DEFAULT,172        timeout=gapic_v1.method.DEFAULT,173        compression=gapic_v1.method.DEFAULT,174        metadata=None,175    ):176        """177        Lists operations that match the specified filter in the request.178 179        Example:180            >>> from google.api_core import operations_v1181            >>> api = operations_v1.OperationsClient()182            >>> name = ''183            >>>184            >>> # Iterate over all results185            >>> for operation in api.list_operations(name):186            >>>   # process operation187            >>>   pass188            >>>189            >>> # Or iterate over results one page at a time190            >>> iter = api.list_operations(name)191            >>> for page in iter.pages:192            >>>   for operation in page:193            >>>     # process operation194            >>>     pass195 196        Args:197            name (str): The name of the operation collection.198            filter_ (str): The standard list filter.199            retry (google.api_core.retry.Retry): The retry strategy to use200                when invoking the RPC. If unspecified, the default retry from201                the client configuration will be used. If ``None``, then this202                method will not retry the RPC at all.203            timeout (float): The amount of time in seconds to wait for the RPC204                to complete. Note that if ``retry`` is used, this timeout205                applies to each individual attempt and the overall time it206                takes for this method to complete may be longer. If207                unspecified, the the default timeout in the client208                configuration is used. If ``None``, then the RPC method will209                not time out.210            compression (grpc.Compression): An element of grpc.compression211                e.g. grpc.compression.Gzip.212            metadata (Optional[List[Tuple[str, str]]]): Additional gRPC213                metadata.214 215        Returns:216            google.api_core.page_iterator.Iterator: An iterator that yields217                :class:`google.longrunning.operations_pb2.Operation` instances.218 219        Raises:220            google.api_core.exceptions.MethodNotImplemented: If the server221                does not support this method. Services are not required to222                implement this method.223            google.api_core.exceptions.GoogleAPICallError: If an error occurred224                while invoking the RPC, the appropriate ``GoogleAPICallError``225                subclass will be raised.226        """227        # Create the request object.228        request = operations_pb2.ListOperationsRequest(name=name, filter=filter_)229 230        # Add routing header231        metadata = metadata or []232        metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))233 234        # Create the method used to fetch pages235        method = functools.partial(236            self._list_operations,237            retry=retry,238            timeout=timeout,239            compression=compression,240            metadata=metadata,241        )242 243        iterator = page_iterator.GRPCIterator(244            client=None,245            method=method,246            request=request,247            items_field="operations",248            request_token_field="page_token",249            response_token_field="next_page_token",250        )251 252        return iterator253 254    def cancel_operation(255        self,256        name,257        retry=gapic_v1.method.DEFAULT,258        timeout=gapic_v1.method.DEFAULT,259        compression=gapic_v1.method.DEFAULT,260        metadata=None,261    ):262        """Starts asynchronous cancellation on a long-running operation.263 264        The server makes a best effort to cancel the operation, but success is265        not guaranteed. Clients can use :meth:`get_operation` or service-266        specific methods to check whether the cancellation succeeded or whether267        the operation completed despite cancellation. On successful268        cancellation, the operation is not deleted; instead, it becomes an269        operation with an ``Operation.error`` value with a270        ``google.rpc.Status.code`` of ``1``, corresponding to271        ``Code.CANCELLED``.272 273        Example:274            >>> from google.api_core import operations_v1275            >>> api = operations_v1.OperationsClient()276            >>> name = ''277            >>> api.cancel_operation(name)278 279        Args:280            name (str): The name of the operation resource to be cancelled.281            retry (google.api_core.retry.Retry): The retry strategy to use282                when invoking the RPC. If unspecified, the default retry from283                the client configuration will be used. If ``None``, then this284                method will not retry the RPC at all.285            timeout (float): The amount of time in seconds to wait for the RPC286                to complete. Note that if ``retry`` is used, this timeout287                applies to each individual attempt and the overall time it288                takes for this method to complete may be longer. If289                unspecified, the the default timeout in the client290                configuration is used. If ``None``, then the RPC method will291                not time out.292            compression (grpc.Compression): An element of grpc.compression293                e.g. grpc.compression.Gzip.294            metadata (Optional[List[Tuple[str, str]]]): Additional gRPC295                metadata.296 297        Raises:298            google.api_core.exceptions.MethodNotImplemented: If the server299                does not support this method. Services are not required to300                implement this method.301            google.api_core.exceptions.GoogleAPICallError: If an error occurred302                while invoking the RPC, the appropriate ``GoogleAPICallError``303                subclass will be raised.304        """305        # Create the request object.306        request = operations_pb2.CancelOperationRequest(name=name)307 308        # Add routing header309        metadata = metadata or []310        metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))311 312        self._cancel_operation(313            request,314            retry=retry,315            timeout=timeout,316            compression=compression,317            metadata=metadata,318        )319 320    def delete_operation(321        self,322        name,323        retry=gapic_v1.method.DEFAULT,324        timeout=gapic_v1.method.DEFAULT,325        compression=gapic_v1.method.DEFAULT,326        metadata=None,327    ):328        """Deletes a long-running operation.329 330        This method indicates that the client is no longer interested in the331        operation result. It does not cancel the operation.332 333        Example:334            >>> from google.api_core import operations_v1335            >>> api = operations_v1.OperationsClient()336            >>> name = ''337            >>> api.delete_operation(name)338 339        Args:340            name (str): The name of the operation resource to be deleted.341            retry (google.api_core.retry.Retry): The retry strategy to use342                when invoking the RPC. If unspecified, the default retry from343                the client configuration will be used. If ``None``, then this344                method will not retry the RPC at all.345            timeout (float): The amount of time in seconds to wait for the RPC346                to complete. Note that if ``retry`` is used, this timeout347                applies to each individual attempt and the overall time it348                takes for this method to complete may be longer. If349                unspecified, the the default timeout in the client350                configuration is used. If ``None``, then the RPC method will351                not time out.352            compression (grpc.Compression): An element of grpc.compression353                e.g. grpc.compression.Gzip.354            metadata (Optional[List[Tuple[str, str]]]): Additional gRPC355                metadata.356 357        Raises:358            google.api_core.exceptions.MethodNotImplemented: If the server359                does not support this method. Services are not required to360                implement this method.361            google.api_core.exceptions.GoogleAPICallError: If an error occurred362                while invoking the RPC, the appropriate ``GoogleAPICallError``363                subclass will be raised.364        """365        # Create the request object.366        request = operations_pb2.DeleteOperationRequest(name=name)367 368        # Add routing header369        metadata = metadata or []370        metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))371 372        self._delete_operation(373            request,374            retry=retry,375            timeout=timeout,376            compression=compression,377            metadata=metadata,378        )379 
codekingpro/portable-devtools · Team Ai