Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/google/cloud/tasks_v2/services/cloud_tasks/transports/grpc_asyncio.py: 47%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

171 statements  

1# -*- coding: utf-8 -*- 

2# Copyright 2025 Google LLC 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# 

8# http://www.apache.org/licenses/LICENSE-2.0 

9# 

10# Unless required by applicable law or agreed to in writing, software 

11# distributed under the License is distributed on an "AS IS" BASIS, 

12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

13# See the License for the specific language governing permissions and 

14# limitations under the License. 

15# 

16import inspect 

17import json 

18import logging as std_logging 

19import pickle 

20from typing import Awaitable, Callable, Dict, Optional, Sequence, Tuple, Union 

21import warnings 

22 

23from google.api_core import exceptions as core_exceptions 

24from google.api_core import gapic_v1, grpc_helpers_async 

25from google.api_core import retry_async as retries 

26from google.auth import credentials as ga_credentials # type: ignore 

27from google.auth.transport.grpc import SslCredentials # type: ignore 

28from google.cloud.location import locations_pb2 # type: ignore 

29from google.iam.v1 import iam_policy_pb2 # type: ignore 

30from google.iam.v1 import policy_pb2 # type: ignore 

31from google.protobuf import empty_pb2 # type: ignore 

32from google.protobuf.json_format import MessageToJson 

33import google.protobuf.message 

34import grpc # type: ignore 

35from grpc.experimental import aio # type: ignore 

36import proto # type: ignore 

37 

38from google.cloud.tasks_v2.types import cloudtasks 

39from google.cloud.tasks_v2.types import queue 

40from google.cloud.tasks_v2.types import queue as gct_queue 

41from google.cloud.tasks_v2.types import task 

42from google.cloud.tasks_v2.types import task as gct_task 

43 

44from .base import DEFAULT_CLIENT_INFO, CloudTasksTransport 

45from .grpc import CloudTasksGrpcTransport 

46 

47try: 

48 from google.api_core import client_logging # type: ignore 

49 

50 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

51except ImportError: # pragma: NO COVER 

52 CLIENT_LOGGING_SUPPORTED = False 

53 

54_LOGGER = std_logging.getLogger(__name__) 

55 

56 

57class _LoggingClientAIOInterceptor( 

58 grpc.aio.UnaryUnaryClientInterceptor 

59): # pragma: NO COVER 

60 async def intercept_unary_unary(self, continuation, client_call_details, request): 

61 logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

62 std_logging.DEBUG 

63 ) 

64 if logging_enabled: # pragma: NO COVER 

65 request_metadata = client_call_details.metadata 

66 if isinstance(request, proto.Message): 

67 request_payload = type(request).to_json(request) 

68 elif isinstance(request, google.protobuf.message.Message): 

69 request_payload = MessageToJson(request) 

70 else: 

71 request_payload = f"{type(request).__name__}: {pickle.dumps(request)}" 

72 

73 request_metadata = { 

74 key: value.decode("utf-8") if isinstance(value, bytes) else value 

75 for key, value in request_metadata 

76 } 

77 grpc_request = { 

78 "payload": request_payload, 

79 "requestMethod": "grpc", 

80 "metadata": dict(request_metadata), 

81 } 

82 _LOGGER.debug( 

83 f"Sending request for {client_call_details.method}", 

84 extra={ 

85 "serviceName": "google.cloud.tasks.v2.CloudTasks", 

86 "rpcName": str(client_call_details.method), 

87 "request": grpc_request, 

88 "metadata": grpc_request["metadata"], 

89 }, 

90 ) 

91 response = await continuation(client_call_details, request) 

92 if logging_enabled: # pragma: NO COVER 

93 response_metadata = await response.trailing_metadata() 

94 # Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples 

95 metadata = ( 

96 dict([(k, str(v)) for k, v in response_metadata]) 

97 if response_metadata 

98 else None 

99 ) 

100 result = await response 

101 if isinstance(result, proto.Message): 

102 response_payload = type(result).to_json(result) 

103 elif isinstance(result, google.protobuf.message.Message): 

104 response_payload = MessageToJson(result) 

105 else: 

106 response_payload = f"{type(result).__name__}: {pickle.dumps(result)}" 

107 grpc_response = { 

108 "payload": response_payload, 

109 "metadata": metadata, 

110 "status": "OK", 

111 } 

112 _LOGGER.debug( 

113 f"Received response to rpc {client_call_details.method}.", 

114 extra={ 

115 "serviceName": "google.cloud.tasks.v2.CloudTasks", 

116 "rpcName": str(client_call_details.method), 

117 "response": grpc_response, 

118 "metadata": grpc_response["metadata"], 

119 }, 

120 ) 

121 return response 

122 

123 

124class CloudTasksGrpcAsyncIOTransport(CloudTasksTransport): 

125 """gRPC AsyncIO backend transport for CloudTasks. 

126 

127 Cloud Tasks allows developers to manage the execution of 

128 background work in their applications. 

129 

130 This class defines the same methods as the primary client, so the 

131 primary client can load the underlying transport implementation 

132 and call it. 

133 

134 It sends protocol buffers over the wire using gRPC (which is built on 

135 top of HTTP/2); the ``grpcio`` package must be installed. 

136 """ 

137 

138 _grpc_channel: aio.Channel 

139 _stubs: Dict[str, Callable] = {} 

140 

141 @classmethod 

142 def create_channel( 

143 cls, 

144 host: str = "cloudtasks.googleapis.com", 

145 credentials: Optional[ga_credentials.Credentials] = None, 

146 credentials_file: Optional[str] = None, 

147 scopes: Optional[Sequence[str]] = None, 

148 quota_project_id: Optional[str] = None, 

149 **kwargs, 

150 ) -> aio.Channel: 

151 """Create and return a gRPC AsyncIO channel object. 

152 Args: 

153 host (Optional[str]): The host for the channel to use. 

154 credentials (Optional[~.Credentials]): The 

155 authorization credentials to attach to requests. These 

156 credentials identify this application to the service. If 

157 none are specified, the client will attempt to ascertain 

158 the credentials from the environment. 

159 credentials_file (Optional[str]): A file with credentials that can 

160 be loaded with :func:`google.auth.load_credentials_from_file`. 

161 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this 

162 service. These are only used when credentials are not specified and 

163 are passed to :func:`google.auth.default`. 

164 quota_project_id (Optional[str]): An optional project to use for billing 

165 and quota. 

166 kwargs (Optional[dict]): Keyword arguments, which are passed to the 

167 channel creation. 

168 Returns: 

169 aio.Channel: A gRPC AsyncIO channel object. 

170 """ 

171 

172 return grpc_helpers_async.create_channel( 

173 host, 

174 credentials=credentials, 

175 credentials_file=credentials_file, 

176 quota_project_id=quota_project_id, 

177 default_scopes=cls.AUTH_SCOPES, 

178 scopes=scopes, 

179 default_host=cls.DEFAULT_HOST, 

180 **kwargs, 

181 ) 

182 

183 def __init__( 

184 self, 

185 *, 

186 host: str = "cloudtasks.googleapis.com", 

187 credentials: Optional[ga_credentials.Credentials] = None, 

188 credentials_file: Optional[str] = None, 

189 scopes: Optional[Sequence[str]] = None, 

190 channel: Optional[Union[aio.Channel, Callable[..., aio.Channel]]] = None, 

191 api_mtls_endpoint: Optional[str] = None, 

192 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None, 

193 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None, 

194 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None, 

195 quota_project_id: Optional[str] = None, 

196 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

197 always_use_jwt_access: Optional[bool] = False, 

198 api_audience: Optional[str] = None, 

199 ) -> None: 

200 """Instantiate the transport. 

201 

202 Args: 

203 host (Optional[str]): 

204 The hostname to connect to (default: 'cloudtasks.googleapis.com'). 

205 credentials (Optional[google.auth.credentials.Credentials]): The 

206 authorization credentials to attach to requests. These 

207 credentials identify the application to the service; if none 

208 are specified, the client will attempt to ascertain the 

209 credentials from the environment. 

210 This argument is ignored if a ``channel`` instance is provided. 

211 credentials_file (Optional[str]): A file with credentials that can 

212 be loaded with :func:`google.auth.load_credentials_from_file`. 

213 This argument is ignored if a ``channel`` instance is provided. 

214 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this 

215 service. These are only used when credentials are not specified and 

216 are passed to :func:`google.auth.default`. 

217 channel (Optional[Union[aio.Channel, Callable[..., aio.Channel]]]): 

218 A ``Channel`` instance through which to make calls, or a Callable 

219 that constructs and returns one. If set to None, ``self.create_channel`` 

220 is used to create the channel. If a Callable is given, it will be called 

221 with the same arguments as used in ``self.create_channel``. 

222 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint. 

223 If provided, it overrides the ``host`` argument and tries to create 

224 a mutual TLS channel with client SSL credentials from 

225 ``client_cert_source`` or application default SSL credentials. 

226 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]): 

227 Deprecated. A callback to provide client SSL certificate bytes and 

228 private key bytes, both in PEM format. It is ignored if 

229 ``api_mtls_endpoint`` is None. 

230 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials 

231 for the grpc channel. It is ignored if a ``channel`` instance is provided. 

232 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]): 

233 A callback to provide client certificate bytes and private key bytes, 

234 both in PEM format. It is used to configure a mutual TLS channel. It is 

235 ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided. 

236 quota_project_id (Optional[str]): An optional project to use for billing 

237 and quota. 

238 client_info (google.api_core.gapic_v1.client_info.ClientInfo): 

239 The client info used to send a user-agent string along with 

240 API requests. If ``None``, then default info will be used. 

241 Generally, you only need to set this if you're developing 

242 your own client library. 

243 always_use_jwt_access (Optional[bool]): Whether self signed JWT should 

244 be used for service account credentials. 

245 

246 Raises: 

247 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport 

248 creation failed for any reason. 

249 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials`` 

250 and ``credentials_file`` are passed. 

251 """ 

252 self._grpc_channel = None 

253 self._ssl_channel_credentials = ssl_channel_credentials 

254 self._stubs: Dict[str, Callable] = {} 

255 

256 if api_mtls_endpoint: 

257 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning) 

258 if client_cert_source: 

259 warnings.warn("client_cert_source is deprecated", DeprecationWarning) 

260 

261 if isinstance(channel, aio.Channel): 

262 # Ignore credentials if a channel was passed. 

263 credentials = None 

264 self._ignore_credentials = True 

265 # If a channel was explicitly provided, set it. 

266 self._grpc_channel = channel 

267 self._ssl_channel_credentials = None 

268 else: 

269 if api_mtls_endpoint: 

270 host = api_mtls_endpoint 

271 

272 # Create SSL credentials with client_cert_source or application 

273 # default SSL credentials. 

274 if client_cert_source: 

275 cert, key = client_cert_source() 

276 self._ssl_channel_credentials = grpc.ssl_channel_credentials( 

277 certificate_chain=cert, private_key=key 

278 ) 

279 else: 

280 self._ssl_channel_credentials = SslCredentials().ssl_credentials 

281 

282 else: 

283 if client_cert_source_for_mtls and not ssl_channel_credentials: 

284 cert, key = client_cert_source_for_mtls() 

285 self._ssl_channel_credentials = grpc.ssl_channel_credentials( 

286 certificate_chain=cert, private_key=key 

287 ) 

288 

289 # The base transport sets the host, credentials and scopes 

290 super().__init__( 

291 host=host, 

292 credentials=credentials, 

293 credentials_file=credentials_file, 

294 scopes=scopes, 

295 quota_project_id=quota_project_id, 

296 client_info=client_info, 

297 always_use_jwt_access=always_use_jwt_access, 

298 api_audience=api_audience, 

299 ) 

300 

301 if not self._grpc_channel: 

302 # initialize with the provided callable or the default channel 

303 channel_init = channel or type(self).create_channel 

304 self._grpc_channel = channel_init( 

305 self._host, 

306 # use the credentials which are saved 

307 credentials=self._credentials, 

308 # Set ``credentials_file`` to ``None`` here as 

309 # the credentials that we saved earlier should be used. 

310 credentials_file=None, 

311 scopes=self._scopes, 

312 ssl_credentials=self._ssl_channel_credentials, 

313 quota_project_id=quota_project_id, 

314 options=[ 

315 ("grpc.max_send_message_length", -1), 

316 ("grpc.max_receive_message_length", -1), 

317 ], 

318 ) 

319 

320 self._interceptor = _LoggingClientAIOInterceptor() 

321 self._grpc_channel._unary_unary_interceptors.append(self._interceptor) 

322 self._logged_channel = self._grpc_channel 

323 self._wrap_with_kind = ( 

324 "kind" in inspect.signature(gapic_v1.method_async.wrap_method).parameters 

325 ) 

326 # Wrap messages. This must be done after self._logged_channel exists 

327 self._prep_wrapped_messages(client_info) 

328 

329 @property 

330 def grpc_channel(self) -> aio.Channel: 

331 """Create the channel designed to connect to this service. 

332 

333 This property caches on the instance; repeated calls return 

334 the same channel. 

335 """ 

336 # Return the channel from cache. 

337 return self._grpc_channel 

338 

339 @property 

340 def list_queues( 

341 self, 

342 ) -> Callable[ 

343 [cloudtasks.ListQueuesRequest], Awaitable[cloudtasks.ListQueuesResponse] 

344 ]: 

345 r"""Return a callable for the list queues method over gRPC. 

346 

347 Lists queues. 

348 

349 Queues are returned in lexicographical order. 

350 

351 Returns: 

352 Callable[[~.ListQueuesRequest], 

353 Awaitable[~.ListQueuesResponse]]: 

354 A function that, when called, will call the underlying RPC 

355 on the server. 

356 """ 

357 # Generate a "stub function" on-the-fly which will actually make 

358 # the request. 

359 # gRPC handles serialization and deserialization, so we just need 

360 # to pass in the functions for each. 

361 if "list_queues" not in self._stubs: 

362 self._stubs["list_queues"] = self._logged_channel.unary_unary( 

363 "/google.cloud.tasks.v2.CloudTasks/ListQueues", 

364 request_serializer=cloudtasks.ListQueuesRequest.serialize, 

365 response_deserializer=cloudtasks.ListQueuesResponse.deserialize, 

366 ) 

367 return self._stubs["list_queues"] 

368 

369 @property 

370 def get_queue( 

371 self, 

372 ) -> Callable[[cloudtasks.GetQueueRequest], Awaitable[queue.Queue]]: 

373 r"""Return a callable for the get queue method over gRPC. 

374 

375 Gets a queue. 

376 

377 Returns: 

378 Callable[[~.GetQueueRequest], 

379 Awaitable[~.Queue]]: 

380 A function that, when called, will call the underlying RPC 

381 on the server. 

382 """ 

383 # Generate a "stub function" on-the-fly which will actually make 

384 # the request. 

385 # gRPC handles serialization and deserialization, so we just need 

386 # to pass in the functions for each. 

387 if "get_queue" not in self._stubs: 

388 self._stubs["get_queue"] = self._logged_channel.unary_unary( 

389 "/google.cloud.tasks.v2.CloudTasks/GetQueue", 

390 request_serializer=cloudtasks.GetQueueRequest.serialize, 

391 response_deserializer=queue.Queue.deserialize, 

392 ) 

393 return self._stubs["get_queue"] 

394 

395 @property 

396 def create_queue( 

397 self, 

398 ) -> Callable[[cloudtasks.CreateQueueRequest], Awaitable[gct_queue.Queue]]: 

399 r"""Return a callable for the create queue method over gRPC. 

400 

401 Creates a queue. 

402 

403 Queues created with this method allow tasks to live for a 

404 maximum of 31 days. After a task is 31 days old, the task will 

405 be deleted regardless of whether it was dispatched or not. 

406 

407 WARNING: Using this method may have unintended side effects if 

408 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file 

409 to manage your queues. Read `Overview of Queue Management and 

410 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__ 

411 before using this method. 

412 

413 Returns: 

414 Callable[[~.CreateQueueRequest], 

415 Awaitable[~.Queue]]: 

416 A function that, when called, will call the underlying RPC 

417 on the server. 

418 """ 

419 # Generate a "stub function" on-the-fly which will actually make 

420 # the request. 

421 # gRPC handles serialization and deserialization, so we just need 

422 # to pass in the functions for each. 

423 if "create_queue" not in self._stubs: 

424 self._stubs["create_queue"] = self._logged_channel.unary_unary( 

425 "/google.cloud.tasks.v2.CloudTasks/CreateQueue", 

426 request_serializer=cloudtasks.CreateQueueRequest.serialize, 

427 response_deserializer=gct_queue.Queue.deserialize, 

428 ) 

429 return self._stubs["create_queue"] 

430 

431 @property 

432 def update_queue( 

433 self, 

434 ) -> Callable[[cloudtasks.UpdateQueueRequest], Awaitable[gct_queue.Queue]]: 

435 r"""Return a callable for the update queue method over gRPC. 

436 

437 Updates a queue. 

438 

439 This method creates the queue if it does not exist and updates 

440 the queue if it does exist. 

441 

442 Queues created with this method allow tasks to live for a 

443 maximum of 31 days. After a task is 31 days old, the task will 

444 be deleted regardless of whether it was dispatched or not. 

445 

446 WARNING: Using this method may have unintended side effects if 

447 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file 

448 to manage your queues. Read `Overview of Queue Management and 

449 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__ 

450 before using this method. 

451 

452 Returns: 

453 Callable[[~.UpdateQueueRequest], 

454 Awaitable[~.Queue]]: 

455 A function that, when called, will call the underlying RPC 

456 on the server. 

457 """ 

458 # Generate a "stub function" on-the-fly which will actually make 

459 # the request. 

460 # gRPC handles serialization and deserialization, so we just need 

461 # to pass in the functions for each. 

462 if "update_queue" not in self._stubs: 

463 self._stubs["update_queue"] = self._logged_channel.unary_unary( 

464 "/google.cloud.tasks.v2.CloudTasks/UpdateQueue", 

465 request_serializer=cloudtasks.UpdateQueueRequest.serialize, 

466 response_deserializer=gct_queue.Queue.deserialize, 

467 ) 

468 return self._stubs["update_queue"] 

469 

470 @property 

471 def delete_queue( 

472 self, 

473 ) -> Callable[[cloudtasks.DeleteQueueRequest], Awaitable[empty_pb2.Empty]]: 

474 r"""Return a callable for the delete queue method over gRPC. 

475 

476 Deletes a queue. 

477 

478 This command will delete the queue even if it has tasks in it. 

479 

480 Note: If you delete a queue, a queue with the same name can't be 

481 created for 7 days. 

482 

483 WARNING: Using this method may have unintended side effects if 

484 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file 

485 to manage your queues. Read `Overview of Queue Management and 

486 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__ 

487 before using this method. 

488 

489 Returns: 

490 Callable[[~.DeleteQueueRequest], 

491 Awaitable[~.Empty]]: 

492 A function that, when called, will call the underlying RPC 

493 on the server. 

494 """ 

495 # Generate a "stub function" on-the-fly which will actually make 

496 # the request. 

497 # gRPC handles serialization and deserialization, so we just need 

498 # to pass in the functions for each. 

499 if "delete_queue" not in self._stubs: 

500 self._stubs["delete_queue"] = self._logged_channel.unary_unary( 

501 "/google.cloud.tasks.v2.CloudTasks/DeleteQueue", 

502 request_serializer=cloudtasks.DeleteQueueRequest.serialize, 

503 response_deserializer=empty_pb2.Empty.FromString, 

504 ) 

505 return self._stubs["delete_queue"] 

506 

507 @property 

508 def purge_queue( 

509 self, 

510 ) -> Callable[[cloudtasks.PurgeQueueRequest], Awaitable[queue.Queue]]: 

511 r"""Return a callable for the purge queue method over gRPC. 

512 

513 Purges a queue by deleting all of its tasks. 

514 

515 All tasks created before this method is called are 

516 permanently deleted. 

517 

518 Purge operations can take up to one minute to take 

519 effect. Tasks might be dispatched before the purge takes 

520 effect. A purge is irreversible. 

521 

522 Returns: 

523 Callable[[~.PurgeQueueRequest], 

524 Awaitable[~.Queue]]: 

525 A function that, when called, will call the underlying RPC 

526 on the server. 

527 """ 

528 # Generate a "stub function" on-the-fly which will actually make 

529 # the request. 

530 # gRPC handles serialization and deserialization, so we just need 

531 # to pass in the functions for each. 

532 if "purge_queue" not in self._stubs: 

533 self._stubs["purge_queue"] = self._logged_channel.unary_unary( 

534 "/google.cloud.tasks.v2.CloudTasks/PurgeQueue", 

535 request_serializer=cloudtasks.PurgeQueueRequest.serialize, 

536 response_deserializer=queue.Queue.deserialize, 

537 ) 

538 return self._stubs["purge_queue"] 

539 

540 @property 

541 def pause_queue( 

542 self, 

543 ) -> Callable[[cloudtasks.PauseQueueRequest], Awaitable[queue.Queue]]: 

544 r"""Return a callable for the pause queue method over gRPC. 

545 

546 Pauses the queue. 

547 

548 If a queue is paused then the system will stop dispatching tasks 

549 until the queue is resumed via 

550 [ResumeQueue][google.cloud.tasks.v2.CloudTasks.ResumeQueue]. 

551 Tasks can still be added when the queue is paused. A queue is 

552 paused if its [state][google.cloud.tasks.v2.Queue.state] is 

553 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED]. 

554 

555 Returns: 

556 Callable[[~.PauseQueueRequest], 

557 Awaitable[~.Queue]]: 

558 A function that, when called, will call the underlying RPC 

559 on the server. 

560 """ 

561 # Generate a "stub function" on-the-fly which will actually make 

562 # the request. 

563 # gRPC handles serialization and deserialization, so we just need 

564 # to pass in the functions for each. 

565 if "pause_queue" not in self._stubs: 

566 self._stubs["pause_queue"] = self._logged_channel.unary_unary( 

567 "/google.cloud.tasks.v2.CloudTasks/PauseQueue", 

568 request_serializer=cloudtasks.PauseQueueRequest.serialize, 

569 response_deserializer=queue.Queue.deserialize, 

570 ) 

571 return self._stubs["pause_queue"] 

572 

573 @property 

574 def resume_queue( 

575 self, 

576 ) -> Callable[[cloudtasks.ResumeQueueRequest], Awaitable[queue.Queue]]: 

577 r"""Return a callable for the resume queue method over gRPC. 

578 

579 Resume a queue. 

580 

581 This method resumes a queue after it has been 

582 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED] or 

583 [DISABLED][google.cloud.tasks.v2.Queue.State.DISABLED]. The 

584 state of a queue is stored in the queue's 

585 [state][google.cloud.tasks.v2.Queue.state]; after calling this 

586 method it will be set to 

587 [RUNNING][google.cloud.tasks.v2.Queue.State.RUNNING]. 

588 

589 WARNING: Resuming many high-QPS queues at the same time can lead 

590 to target overloading. If you are resuming high-QPS queues, 

591 follow the 500/50/5 pattern described in `Managing Cloud Tasks 

592 Scaling 

593 Risks <https://cloud.google.com/tasks/docs/manage-cloud-task-scaling>`__. 

594 

595 Returns: 

596 Callable[[~.ResumeQueueRequest], 

597 Awaitable[~.Queue]]: 

598 A function that, when called, will call the underlying RPC 

599 on the server. 

600 """ 

601 # Generate a "stub function" on-the-fly which will actually make 

602 # the request. 

603 # gRPC handles serialization and deserialization, so we just need 

604 # to pass in the functions for each. 

605 if "resume_queue" not in self._stubs: 

606 self._stubs["resume_queue"] = self._logged_channel.unary_unary( 

607 "/google.cloud.tasks.v2.CloudTasks/ResumeQueue", 

608 request_serializer=cloudtasks.ResumeQueueRequest.serialize, 

609 response_deserializer=queue.Queue.deserialize, 

610 ) 

611 return self._stubs["resume_queue"] 

612 

613 @property 

614 def get_iam_policy( 

615 self, 

616 ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: 

617 r"""Return a callable for the get iam policy method over gRPC. 

618 

619 Gets the access control policy for a 

620 [Queue][google.cloud.tasks.v2.Queue]. Returns an empty policy if 

621 the resource exists and does not have a policy set. 

622 

623 Authorization requires the following `Google 

624 IAM <https://cloud.google.com/iam>`__ permission on the 

625 specified resource parent: 

626 

627 - ``cloudtasks.queues.getIamPolicy`` 

628 

629 Returns: 

630 Callable[[~.GetIamPolicyRequest], 

631 Awaitable[~.Policy]]: 

632 A function that, when called, will call the underlying RPC 

633 on the server. 

634 """ 

635 # Generate a "stub function" on-the-fly which will actually make 

636 # the request. 

637 # gRPC handles serialization and deserialization, so we just need 

638 # to pass in the functions for each. 

639 if "get_iam_policy" not in self._stubs: 

640 self._stubs["get_iam_policy"] = self._logged_channel.unary_unary( 

641 "/google.cloud.tasks.v2.CloudTasks/GetIamPolicy", 

642 request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString, 

643 response_deserializer=policy_pb2.Policy.FromString, 

644 ) 

645 return self._stubs["get_iam_policy"] 

646 

647 @property 

648 def set_iam_policy( 

649 self, 

650 ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], Awaitable[policy_pb2.Policy]]: 

651 r"""Return a callable for the set iam policy method over gRPC. 

652 

653 Sets the access control policy for a 

654 [Queue][google.cloud.tasks.v2.Queue]. Replaces any existing 

655 policy. 

656 

657 Note: The Cloud Console does not check queue-level IAM 

658 permissions yet. Project-level permissions are required to use 

659 the Cloud Console. 

660 

661 Authorization requires the following `Google 

662 IAM <https://cloud.google.com/iam>`__ permission on the 

663 specified resource parent: 

664 

665 - ``cloudtasks.queues.setIamPolicy`` 

666 

667 Returns: 

668 Callable[[~.SetIamPolicyRequest], 

669 Awaitable[~.Policy]]: 

670 A function that, when called, will call the underlying RPC 

671 on the server. 

672 """ 

673 # Generate a "stub function" on-the-fly which will actually make 

674 # the request. 

675 # gRPC handles serialization and deserialization, so we just need 

676 # to pass in the functions for each. 

677 if "set_iam_policy" not in self._stubs: 

678 self._stubs["set_iam_policy"] = self._logged_channel.unary_unary( 

679 "/google.cloud.tasks.v2.CloudTasks/SetIamPolicy", 

680 request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString, 

681 response_deserializer=policy_pb2.Policy.FromString, 

682 ) 

683 return self._stubs["set_iam_policy"] 

684 

685 @property 

686 def test_iam_permissions( 

687 self, 

688 ) -> Callable[ 

689 [iam_policy_pb2.TestIamPermissionsRequest], 

690 Awaitable[iam_policy_pb2.TestIamPermissionsResponse], 

691 ]: 

692 r"""Return a callable for the test iam permissions method over gRPC. 

693 

694 Returns permissions that a caller has on a 

695 [Queue][google.cloud.tasks.v2.Queue]. If the resource does not 

696 exist, this will return an empty set of permissions, not a 

697 [NOT_FOUND][google.rpc.Code.NOT_FOUND] error. 

698 

699 Note: This operation is designed to be used for building 

700 permission-aware UIs and command-line tools, not for 

701 authorization checking. This operation may "fail open" without 

702 warning. 

703 

704 Returns: 

705 Callable[[~.TestIamPermissionsRequest], 

706 Awaitable[~.TestIamPermissionsResponse]]: 

707 A function that, when called, will call the underlying RPC 

708 on the server. 

709 """ 

710 # Generate a "stub function" on-the-fly which will actually make 

711 # the request. 

712 # gRPC handles serialization and deserialization, so we just need 

713 # to pass in the functions for each. 

714 if "test_iam_permissions" not in self._stubs: 

715 self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary( 

716 "/google.cloud.tasks.v2.CloudTasks/TestIamPermissions", 

717 request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString, 

718 response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString, 

719 ) 

720 return self._stubs["test_iam_permissions"] 

721 

722 @property 

723 def list_tasks( 

724 self, 

725 ) -> Callable[ 

726 [cloudtasks.ListTasksRequest], Awaitable[cloudtasks.ListTasksResponse] 

727 ]: 

728 r"""Return a callable for the list tasks method over gRPC. 

729 

730 Lists the tasks in a queue. 

731 

732 By default, only the 

733 [BASIC][google.cloud.tasks.v2.Task.View.BASIC] view is retrieved 

734 due to performance considerations; 

735 [response_view][google.cloud.tasks.v2.ListTasksRequest.response_view] 

736 controls the subset of information which is returned. 

737 

738 The tasks may be returned in any order. The ordering may change 

739 at any time. 

740 

741 Returns: 

742 Callable[[~.ListTasksRequest], 

743 Awaitable[~.ListTasksResponse]]: 

744 A function that, when called, will call the underlying RPC 

745 on the server. 

746 """ 

747 # Generate a "stub function" on-the-fly which will actually make 

748 # the request. 

749 # gRPC handles serialization and deserialization, so we just need 

750 # to pass in the functions for each. 

751 if "list_tasks" not in self._stubs: 

752 self._stubs["list_tasks"] = self._logged_channel.unary_unary( 

753 "/google.cloud.tasks.v2.CloudTasks/ListTasks", 

754 request_serializer=cloudtasks.ListTasksRequest.serialize, 

755 response_deserializer=cloudtasks.ListTasksResponse.deserialize, 

756 ) 

757 return self._stubs["list_tasks"] 

758 

759 @property 

760 def get_task(self) -> Callable[[cloudtasks.GetTaskRequest], Awaitable[task.Task]]: 

761 r"""Return a callable for the get task method over gRPC. 

762 

763 Gets a task. 

764 

765 Returns: 

766 Callable[[~.GetTaskRequest], 

767 Awaitable[~.Task]]: 

768 A function that, when called, will call the underlying RPC 

769 on the server. 

770 """ 

771 # Generate a "stub function" on-the-fly which will actually make 

772 # the request. 

773 # gRPC handles serialization and deserialization, so we just need 

774 # to pass in the functions for each. 

775 if "get_task" not in self._stubs: 

776 self._stubs["get_task"] = self._logged_channel.unary_unary( 

777 "/google.cloud.tasks.v2.CloudTasks/GetTask", 

778 request_serializer=cloudtasks.GetTaskRequest.serialize, 

779 response_deserializer=task.Task.deserialize, 

780 ) 

781 return self._stubs["get_task"] 

782 

783 @property 

784 def create_task( 

785 self, 

786 ) -> Callable[[cloudtasks.CreateTaskRequest], Awaitable[gct_task.Task]]: 

787 r"""Return a callable for the create task method over gRPC. 

788 

789 Creates a task and adds it to a queue. 

790 

791 Tasks cannot be updated after creation; there is no UpdateTask 

792 command. 

793 

794 - The maximum task size is 100KB. 

795 

796 Returns: 

797 Callable[[~.CreateTaskRequest], 

798 Awaitable[~.Task]]: 

799 A function that, when called, will call the underlying RPC 

800 on the server. 

801 """ 

802 # Generate a "stub function" on-the-fly which will actually make 

803 # the request. 

804 # gRPC handles serialization and deserialization, so we just need 

805 # to pass in the functions for each. 

806 if "create_task" not in self._stubs: 

807 self._stubs["create_task"] = self._logged_channel.unary_unary( 

808 "/google.cloud.tasks.v2.CloudTasks/CreateTask", 

809 request_serializer=cloudtasks.CreateTaskRequest.serialize, 

810 response_deserializer=gct_task.Task.deserialize, 

811 ) 

812 return self._stubs["create_task"] 

813 

814 @property 

815 def delete_task( 

816 self, 

817 ) -> Callable[[cloudtasks.DeleteTaskRequest], Awaitable[empty_pb2.Empty]]: 

818 r"""Return a callable for the delete task method over gRPC. 

819 

820 Deletes a task. 

821 

822 A task can be deleted if it is scheduled or dispatched. 

823 A task cannot be deleted if it has executed successfully 

824 or permanently failed. 

825 

826 Returns: 

827 Callable[[~.DeleteTaskRequest], 

828 Awaitable[~.Empty]]: 

829 A function that, when called, will call the underlying RPC 

830 on the server. 

831 """ 

832 # Generate a "stub function" on-the-fly which will actually make 

833 # the request. 

834 # gRPC handles serialization and deserialization, so we just need 

835 # to pass in the functions for each. 

836 if "delete_task" not in self._stubs: 

837 self._stubs["delete_task"] = self._logged_channel.unary_unary( 

838 "/google.cloud.tasks.v2.CloudTasks/DeleteTask", 

839 request_serializer=cloudtasks.DeleteTaskRequest.serialize, 

840 response_deserializer=empty_pb2.Empty.FromString, 

841 ) 

842 return self._stubs["delete_task"] 

843 

844 @property 

845 def run_task(self) -> Callable[[cloudtasks.RunTaskRequest], Awaitable[task.Task]]: 

846 r"""Return a callable for the run task method over gRPC. 

847 

848 Forces a task to run now. 

849 

850 When this method is called, Cloud Tasks will dispatch the task, 

851 even if the task is already running, the queue has reached its 

852 [RateLimits][google.cloud.tasks.v2.RateLimits] or is 

853 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED]. 

854 

855 This command is meant to be used for manual debugging. For 

856 example, [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] can 

857 be used to retry a failed task after a fix has been made or to 

858 manually force a task to be dispatched now. 

859 

860 The dispatched task is returned. That is, the task that is 

861 returned contains the [status][Task.status] after the task is 

862 dispatched but before the task is received by its target. 

863 

864 If Cloud Tasks receives a successful response from the task's 

865 target, then the task will be deleted; otherwise the task's 

866 [schedule_time][google.cloud.tasks.v2.Task.schedule_time] will 

867 be reset to the time that 

868 [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] was called 

869 plus the retry delay specified in the queue's 

870 [RetryConfig][google.cloud.tasks.v2.RetryConfig]. 

871 

872 [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] returns 

873 [NOT_FOUND][google.rpc.Code.NOT_FOUND] when it is called on a 

874 task that has already succeeded or permanently failed. 

875 

876 Returns: 

877 Callable[[~.RunTaskRequest], 

878 Awaitable[~.Task]]: 

879 A function that, when called, will call the underlying RPC 

880 on the server. 

881 """ 

882 # Generate a "stub function" on-the-fly which will actually make 

883 # the request. 

884 # gRPC handles serialization and deserialization, so we just need 

885 # to pass in the functions for each. 

886 if "run_task" not in self._stubs: 

887 self._stubs["run_task"] = self._logged_channel.unary_unary( 

888 "/google.cloud.tasks.v2.CloudTasks/RunTask", 

889 request_serializer=cloudtasks.RunTaskRequest.serialize, 

890 response_deserializer=task.Task.deserialize, 

891 ) 

892 return self._stubs["run_task"] 

893 

894 def _prep_wrapped_messages(self, client_info): 

895 """Precompute the wrapped methods, overriding the base class method to use async wrappers.""" 

896 self._wrapped_methods = { 

897 self.list_queues: self._wrap_method( 

898 self.list_queues, 

899 default_retry=retries.AsyncRetry( 

900 initial=0.1, 

901 maximum=10.0, 

902 multiplier=1.3, 

903 predicate=retries.if_exception_type( 

904 core_exceptions.DeadlineExceeded, 

905 core_exceptions.ServiceUnavailable, 

906 ), 

907 deadline=20.0, 

908 ), 

909 default_timeout=20.0, 

910 client_info=client_info, 

911 ), 

912 self.get_queue: self._wrap_method( 

913 self.get_queue, 

914 default_retry=retries.AsyncRetry( 

915 initial=0.1, 

916 maximum=10.0, 

917 multiplier=1.3, 

918 predicate=retries.if_exception_type( 

919 core_exceptions.DeadlineExceeded, 

920 core_exceptions.ServiceUnavailable, 

921 ), 

922 deadline=20.0, 

923 ), 

924 default_timeout=20.0, 

925 client_info=client_info, 

926 ), 

927 self.create_queue: self._wrap_method( 

928 self.create_queue, 

929 default_timeout=20.0, 

930 client_info=client_info, 

931 ), 

932 self.update_queue: self._wrap_method( 

933 self.update_queue, 

934 default_timeout=20.0, 

935 client_info=client_info, 

936 ), 

937 self.delete_queue: self._wrap_method( 

938 self.delete_queue, 

939 default_retry=retries.AsyncRetry( 

940 initial=0.1, 

941 maximum=10.0, 

942 multiplier=1.3, 

943 predicate=retries.if_exception_type( 

944 core_exceptions.DeadlineExceeded, 

945 core_exceptions.ServiceUnavailable, 

946 ), 

947 deadline=20.0, 

948 ), 

949 default_timeout=20.0, 

950 client_info=client_info, 

951 ), 

952 self.purge_queue: self._wrap_method( 

953 self.purge_queue, 

954 default_timeout=20.0, 

955 client_info=client_info, 

956 ), 

957 self.pause_queue: self._wrap_method( 

958 self.pause_queue, 

959 default_timeout=20.0, 

960 client_info=client_info, 

961 ), 

962 self.resume_queue: self._wrap_method( 

963 self.resume_queue, 

964 default_timeout=20.0, 

965 client_info=client_info, 

966 ), 

967 self.get_iam_policy: self._wrap_method( 

968 self.get_iam_policy, 

969 default_retry=retries.AsyncRetry( 

970 initial=0.1, 

971 maximum=10.0, 

972 multiplier=1.3, 

973 predicate=retries.if_exception_type( 

974 core_exceptions.DeadlineExceeded, 

975 core_exceptions.ServiceUnavailable, 

976 ), 

977 deadline=20.0, 

978 ), 

979 default_timeout=20.0, 

980 client_info=client_info, 

981 ), 

982 self.set_iam_policy: self._wrap_method( 

983 self.set_iam_policy, 

984 default_timeout=20.0, 

985 client_info=client_info, 

986 ), 

987 self.test_iam_permissions: self._wrap_method( 

988 self.test_iam_permissions, 

989 default_retry=retries.AsyncRetry( 

990 initial=0.1, 

991 maximum=10.0, 

992 multiplier=1.3, 

993 predicate=retries.if_exception_type( 

994 core_exceptions.DeadlineExceeded, 

995 core_exceptions.ServiceUnavailable, 

996 ), 

997 deadline=20.0, 

998 ), 

999 default_timeout=20.0, 

1000 client_info=client_info, 

1001 ), 

1002 self.list_tasks: self._wrap_method( 

1003 self.list_tasks, 

1004 default_retry=retries.AsyncRetry( 

1005 initial=0.1, 

1006 maximum=10.0, 

1007 multiplier=1.3, 

1008 predicate=retries.if_exception_type( 

1009 core_exceptions.DeadlineExceeded, 

1010 core_exceptions.ServiceUnavailable, 

1011 ), 

1012 deadline=20.0, 

1013 ), 

1014 default_timeout=20.0, 

1015 client_info=client_info, 

1016 ), 

1017 self.get_task: self._wrap_method( 

1018 self.get_task, 

1019 default_retry=retries.AsyncRetry( 

1020 initial=0.1, 

1021 maximum=10.0, 

1022 multiplier=1.3, 

1023 predicate=retries.if_exception_type( 

1024 core_exceptions.DeadlineExceeded, 

1025 core_exceptions.ServiceUnavailable, 

1026 ), 

1027 deadline=20.0, 

1028 ), 

1029 default_timeout=20.0, 

1030 client_info=client_info, 

1031 ), 

1032 self.create_task: self._wrap_method( 

1033 self.create_task, 

1034 default_timeout=20.0, 

1035 client_info=client_info, 

1036 ), 

1037 self.delete_task: self._wrap_method( 

1038 self.delete_task, 

1039 default_retry=retries.AsyncRetry( 

1040 initial=0.1, 

1041 maximum=10.0, 

1042 multiplier=1.3, 

1043 predicate=retries.if_exception_type( 

1044 core_exceptions.DeadlineExceeded, 

1045 core_exceptions.ServiceUnavailable, 

1046 ), 

1047 deadline=20.0, 

1048 ), 

1049 default_timeout=20.0, 

1050 client_info=client_info, 

1051 ), 

1052 self.run_task: self._wrap_method( 

1053 self.run_task, 

1054 default_timeout=20.0, 

1055 client_info=client_info, 

1056 ), 

1057 self.get_location: self._wrap_method( 

1058 self.get_location, 

1059 default_timeout=None, 

1060 client_info=client_info, 

1061 ), 

1062 self.list_locations: self._wrap_method( 

1063 self.list_locations, 

1064 default_timeout=None, 

1065 client_info=client_info, 

1066 ), 

1067 } 

1068 

1069 def _wrap_method(self, func, *args, **kwargs): 

1070 if self._wrap_with_kind: # pragma: NO COVER 

1071 kwargs["kind"] = self.kind 

1072 return gapic_v1.method_async.wrap_method(func, *args, **kwargs) 

1073 

1074 def close(self): 

1075 return self._logged_channel.close() 

1076 

1077 @property 

1078 def kind(self) -> str: 

1079 return "grpc_asyncio" 

1080 

1081 @property 

1082 def list_locations( 

1083 self, 

1084 ) -> Callable[ 

1085 [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse 

1086 ]: 

1087 r"""Return a callable for the list locations method over gRPC.""" 

1088 # Generate a "stub function" on-the-fly which will actually make 

1089 # the request. 

1090 # gRPC handles serialization and deserialization, so we just need 

1091 # to pass in the functions for each. 

1092 if "list_locations" not in self._stubs: 

1093 self._stubs["list_locations"] = self._logged_channel.unary_unary( 

1094 "/google.cloud.location.Locations/ListLocations", 

1095 request_serializer=locations_pb2.ListLocationsRequest.SerializeToString, 

1096 response_deserializer=locations_pb2.ListLocationsResponse.FromString, 

1097 ) 

1098 return self._stubs["list_locations"] 

1099 

1100 @property 

1101 def get_location( 

1102 self, 

1103 ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]: 

1104 r"""Return a callable for the list locations method over gRPC.""" 

1105 # Generate a "stub function" on-the-fly which will actually make 

1106 # the request. 

1107 # gRPC handles serialization and deserialization, so we just need 

1108 # to pass in the functions for each. 

1109 if "get_location" not in self._stubs: 

1110 self._stubs["get_location"] = self._logged_channel.unary_unary( 

1111 "/google.cloud.location.Locations/GetLocation", 

1112 request_serializer=locations_pb2.GetLocationRequest.SerializeToString, 

1113 response_deserializer=locations_pb2.Location.FromString, 

1114 ) 

1115 return self._stubs["get_location"] 

1116 

1117 

1118__all__ = ("CloudTasksGrpcAsyncIOTransport",)