1# Copyright 2020 Google LLC
2#
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 at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# 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 and
13# limitations under the License.
14
15"""An async client for the google.longrunning.operations meta-API.
16
17.. _Google API Style Guide:
18 https://cloud.google.com/apis/design/design_pattern
19 s#long_running_operations
20.. _google/longrunning/operations.proto:
21 https://github.com/googleapis/googleapis/blob/master/google/longrunning
22 /operations.proto
23"""
24
25import functools
26
27from google.api_core import exceptions as core_exceptions
28from google.api_core import gapic_v1, page_iterator_async
29from google.api_core import retry_async as retries
30from google.api_core import timeout as timeouts
31from google.longrunning import operations_pb2
32from grpc import Compression
33
34
35class OperationsAsyncClient:
36 """Async client for interacting with long-running operations.
37
38 Args:
39 channel (aio.Channel): The gRPC AsyncIO channel associated with the
40 service that implements the ``google.longrunning.operations``
41 interface.
42 client_config (dict):
43 A dictionary of call options for each method. If not specified
44 the default configuration is used.
45 """
46
47 def __init__(self, channel, client_config=None):
48 # Create the gRPC client stub with gRPC AsyncIO channel.
49 self.operations_stub = operations_pb2.OperationsStub(channel)
50
51 default_retry = retries.AsyncRetry(
52 initial=0.1, # seconds
53 maximum=60.0, # seconds
54 multiplier=1.3,
55 predicate=retries.if_exception_type(
56 core_exceptions.DeadlineExceeded,
57 core_exceptions.ServiceUnavailable,
58 ),
59 timeout=600.0, # seconds
60 )
61 default_timeout = timeouts.TimeToDeadlineTimeout(timeout=600.0)
62
63 default_compression = Compression.NoCompression
64
65 self._get_operation = gapic_v1.method_async.wrap_method(
66 self.operations_stub.GetOperation,
67 default_retry=default_retry,
68 default_timeout=default_timeout,
69 default_compression=default_compression,
70 )
71
72 self._list_operations = gapic_v1.method_async.wrap_method(
73 self.operations_stub.ListOperations,
74 default_retry=default_retry,
75 default_timeout=default_timeout,
76 default_compression=default_compression,
77 )
78
79 self._cancel_operation = gapic_v1.method_async.wrap_method(
80 self.operations_stub.CancelOperation,
81 default_retry=default_retry,
82 default_timeout=default_timeout,
83 default_compression=default_compression,
84 )
85
86 self._delete_operation = gapic_v1.method_async.wrap_method(
87 self.operations_stub.DeleteOperation,
88 default_retry=default_retry,
89 default_timeout=default_timeout,
90 default_compression=default_compression,
91 )
92
93 async def get_operation(
94 self,
95 name,
96 retry=gapic_v1.method_async.DEFAULT,
97 timeout=gapic_v1.method_async.DEFAULT,
98 compression=gapic_v1.method_async.DEFAULT,
99 metadata=None,
100 ):
101 """Gets the latest state of a long-running operation.
102
103 Clients can use this method to poll the operation result at intervals
104 as recommended by the API service.
105
106 Example:
107 >>> from google.api_core import operations_v1
108 >>> api = operations_v1.OperationsClient()
109 >>> name = ''
110 >>> response = await api.get_operation(name)
111
112 Args:
113 name (str): The name of the operation resource.
114 retry (google.api_core.retry.Retry): The retry strategy to use
115 when invoking the RPC. If unspecified, the default retry from
116 the client configuration will be used. If ``None``, then this
117 method will not retry the RPC at all.
118 timeout (float): The amount of time in seconds to wait for the RPC
119 to complete. Note that if ``retry`` is used, this timeout
120 applies to each individual attempt and the overall time it
121 takes for this method to complete may be longer. If
122 unspecified, the the default timeout in the client
123 configuration is used. If ``None``, then the RPC method will
124 not time out.
125 compression (grpc.Compression): An element of grpc.compression
126 e.g. grpc.compression.Gzip.
127 metadata (Optional[List[Tuple[str, str]]]):
128 Additional gRPC metadata.
129
130 Returns:
131 google.longrunning.operations_pb2.Operation: The state of the
132 operation.
133
134 Raises:
135 google.api_core.exceptions.GoogleAPICallError: If an error occurred
136 while invoking the RPC, the appropriate ``GoogleAPICallError``
137 subclass will be raised.
138 """
139 request = operations_pb2.GetOperationRequest(name=name)
140
141 # Add routing header
142 metadata = metadata or []
143 metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
144
145 return await self._get_operation(
146 request,
147 retry=retry,
148 timeout=timeout,
149 compression=compression,
150 metadata=metadata,
151 )
152
153 async def list_operations(
154 self,
155 name,
156 filter_,
157 retry=gapic_v1.method_async.DEFAULT,
158 timeout=gapic_v1.method_async.DEFAULT,
159 compression=gapic_v1.method_async.DEFAULT,
160 metadata=None,
161 ):
162 """
163 Lists operations that match the specified filter in the request.
164
165 Example:
166 >>> from google.api_core import operations_v1
167 >>> api = operations_v1.OperationsClient()
168 >>> name = ''
169 >>>
170 >>> # Iterate over all results
171 >>> for operation in await api.list_operations(name):
172 >>> # process operation
173 >>> pass
174 >>>
175 >>> # Or iterate over results one page at a time
176 >>> iter = await api.list_operations(name)
177 >>> for page in iter.pages:
178 >>> for operation in page:
179 >>> # process operation
180 >>> pass
181
182 Args:
183 name (str): The name of the operation collection.
184 filter_ (str): The standard list filter.
185 retry (google.api_core.retry.Retry): The retry strategy to use
186 when invoking the RPC. If unspecified, the default retry from
187 the client configuration will be used. If ``None``, then this
188 method will not retry the RPC at all.
189 timeout (float): The amount of time in seconds to wait for the RPC
190 to complete. Note that if ``retry`` is used, this timeout
191 applies to each individual attempt and the overall time it
192 takes for this method to complete may be longer. If
193 unspecified, the the default timeout in the client
194 configuration is used. If ``None``, then the RPC method will
195 not time out.
196 compression (grpc.Compression): An element of grpc.compression
197 e.g. grpc.compression.Gzip.
198 metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
199 metadata.
200
201 Returns:
202 google.api_core.page_iterator.Iterator: An iterator that yields
203 :class:`google.longrunning.operations_pb2.Operation` instances.
204
205 Raises:
206 google.api_core.exceptions.MethodNotImplemented: If the server
207 does not support this method. Services are not required to
208 implement this method.
209 google.api_core.exceptions.GoogleAPICallError: If an error occurred
210 while invoking the RPC, the appropriate ``GoogleAPICallError``
211 subclass will be raised.
212 """
213 # Create the request object.
214 request = operations_pb2.ListOperationsRequest(name=name, filter=filter_)
215
216 # Add routing header
217 metadata = metadata or []
218 metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
219
220 # Create the method used to fetch pages
221 method = functools.partial(
222 self._list_operations,
223 retry=retry,
224 timeout=timeout,
225 compression=compression,
226 metadata=metadata,
227 )
228
229 iterator = page_iterator_async.AsyncGRPCIterator(
230 client=None,
231 method=method,
232 request=request,
233 items_field="operations",
234 request_token_field="page_token",
235 response_token_field="next_page_token",
236 )
237
238 return iterator
239
240 async def cancel_operation(
241 self,
242 name,
243 retry=gapic_v1.method_async.DEFAULT,
244 timeout=gapic_v1.method_async.DEFAULT,
245 compression=gapic_v1.method_async.DEFAULT,
246 metadata=None,
247 ):
248 """Starts asynchronous cancellation on a long-running operation.
249
250 The server makes a best effort to cancel the operation, but success is
251 not guaranteed. Clients can use :meth:`get_operation` or service-
252 specific methods to check whether the cancellation succeeded or whether
253 the operation completed despite cancellation. On successful
254 cancellation, the operation is not deleted; instead, it becomes an
255 operation with an ``Operation.error`` value with a
256 ``google.rpc.Status.code`` of ``1``, corresponding to
257 ``Code.CANCELLED``.
258
259 Example:
260 >>> from google.api_core import operations_v1
261 >>> api = operations_v1.OperationsClient()
262 >>> name = ''
263 >>> api.cancel_operation(name)
264
265 Args:
266 name (str): The name of the operation resource to be cancelled.
267 retry (google.api_core.retry.Retry): The retry strategy to use
268 when invoking the RPC. If unspecified, the default retry from
269 the client configuration will be used. If ``None``, then this
270 method will not retry the RPC at all.
271 timeout (float): The amount of time in seconds to wait for the RPC
272 to complete. Note that if ``retry`` is used, this timeout
273 applies to each individual attempt and the overall time it
274 takes for this method to complete may be longer. If
275 unspecified, the the default timeout in the client
276 configuration is used. If ``None``, then the RPC method will
277 not time out.
278
279 Raises:
280 google.api_core.exceptions.MethodNotImplemented: If the server
281 does not support this method. Services are not required to
282 implement this method.
283 google.api_core.exceptions.GoogleAPICallError: If an error occurred
284 while invoking the RPC, the appropriate ``GoogleAPICallError``
285 subclass will be raised.
286 compression (grpc.Compression): An element of grpc.compression
287 e.g. grpc.compression.Gzip.
288 metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
289 metadata.
290 """
291 # Create the request object.
292 request = operations_pb2.CancelOperationRequest(name=name)
293
294 # Add routing header
295 metadata = metadata or []
296 metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
297
298 await self._cancel_operation(
299 request,
300 retry=retry,
301 timeout=timeout,
302 compression=compression,
303 metadata=metadata,
304 )
305
306 async def delete_operation(
307 self,
308 name,
309 retry=gapic_v1.method_async.DEFAULT,
310 timeout=gapic_v1.method_async.DEFAULT,
311 compression=gapic_v1.method_async.DEFAULT,
312 metadata=None,
313 ):
314 """Deletes a long-running operation.
315
316 This method indicates that the client is no longer interested in the
317 operation result. It does not cancel the operation.
318
319 Example:
320 >>> from google.api_core import operations_v1
321 >>> api = operations_v1.OperationsClient()
322 >>> name = ''
323 >>> api.delete_operation(name)
324
325 Args:
326 name (str): The name of the operation resource to be deleted.
327 retry (google.api_core.retry.Retry): The retry strategy to use
328 when invoking the RPC. If unspecified, the default retry from
329 the client configuration will be used. If ``None``, then this
330 method will not retry the RPC at all.
331 timeout (float): The amount of time in seconds to wait for the RPC
332 to complete. Note that if ``retry`` is used, this timeout
333 applies to each individual attempt and the overall time it
334 takes for this method to complete may be longer. If
335 unspecified, the the default timeout in the client
336 configuration is used. If ``None``, then the RPC method will
337 not time out.
338 compression (grpc.Compression): An element of grpc.compression
339 e.g. grpc.compression.Gzip.
340 metadata (Optional[List[Tuple[str, str]]]): Additional gRPC
341 metadata.
342
343 Raises:
344 google.api_core.exceptions.MethodNotImplemented: If the server
345 does not support this method. Services are not required to
346 implement this method.
347 google.api_core.exceptions.GoogleAPICallError: If an error occurred
348 while invoking the RPC, the appropriate ``GoogleAPICallError``
349 subclass will be raised.
350 """
351 # Create the request object.
352 request = operations_pb2.DeleteOperationRequest(name=name)
353
354 # Add routing header
355 metadata = metadata or []
356 metadata.append(gapic_v1.routing_header.to_grpc_metadata({"name": name}))
357
358 await self._delete_operation(
359 request,
360 retry=retry,
361 timeout=timeout,
362 compression=compression,
363 metadata=metadata,
364 )