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 json
17import logging as std_logging
18import pickle
19from typing import Callable, Dict, Optional, Sequence, Tuple, Union
20import warnings
21
22from google.api_core import gapic_v1, grpc_helpers
23import google.auth # type: ignore
24from google.auth import credentials as ga_credentials # type: ignore
25from google.auth.transport.grpc import SslCredentials # type: ignore
26from google.cloud.location import locations_pb2 # type: ignore
27from google.iam.v1 import iam_policy_pb2 # type: ignore
28from google.iam.v1 import policy_pb2 # type: ignore
29from google.protobuf import empty_pb2 # type: ignore
30from google.protobuf.json_format import MessageToJson
31import google.protobuf.message
32import grpc # type: ignore
33import proto # type: ignore
34
35from google.cloud.tasks_v2.types import cloudtasks
36from google.cloud.tasks_v2.types import queue
37from google.cloud.tasks_v2.types import queue as gct_queue
38from google.cloud.tasks_v2.types import task
39from google.cloud.tasks_v2.types import task as gct_task
40
41from .base import DEFAULT_CLIENT_INFO, CloudTasksTransport
42
43try:
44 from google.api_core import client_logging # type: ignore
45
46 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
47except ImportError: # pragma: NO COVER
48 CLIENT_LOGGING_SUPPORTED = False
49
50_LOGGER = std_logging.getLogger(__name__)
51
52
53class _LoggingClientInterceptor(grpc.UnaryUnaryClientInterceptor): # pragma: NO COVER
54 def intercept_unary_unary(self, continuation, client_call_details, request):
55 logging_enabled = CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
56 std_logging.DEBUG
57 )
58 if logging_enabled: # pragma: NO COVER
59 request_metadata = client_call_details.metadata
60 if isinstance(request, proto.Message):
61 request_payload = type(request).to_json(request)
62 elif isinstance(request, google.protobuf.message.Message):
63 request_payload = MessageToJson(request)
64 else:
65 request_payload = f"{type(request).__name__}: {pickle.dumps(request)}"
66
67 request_metadata = {
68 key: value.decode("utf-8") if isinstance(value, bytes) else value
69 for key, value in request_metadata
70 }
71 grpc_request = {
72 "payload": request_payload,
73 "requestMethod": "grpc",
74 "metadata": dict(request_metadata),
75 }
76 _LOGGER.debug(
77 f"Sending request for {client_call_details.method}",
78 extra={
79 "serviceName": "google.cloud.tasks.v2.CloudTasks",
80 "rpcName": str(client_call_details.method),
81 "request": grpc_request,
82 "metadata": grpc_request["metadata"],
83 },
84 )
85 response = continuation(client_call_details, request)
86 if logging_enabled: # pragma: NO COVER
87 response_metadata = response.trailing_metadata()
88 # Convert gRPC metadata `<class 'grpc.aio._metadata.Metadata'>` to list of tuples
89 metadata = (
90 dict([(k, str(v)) for k, v in response_metadata])
91 if response_metadata
92 else None
93 )
94 result = response.result()
95 if isinstance(result, proto.Message):
96 response_payload = type(result).to_json(result)
97 elif isinstance(result, google.protobuf.message.Message):
98 response_payload = MessageToJson(result)
99 else:
100 response_payload = f"{type(result).__name__}: {pickle.dumps(result)}"
101 grpc_response = {
102 "payload": response_payload,
103 "metadata": metadata,
104 "status": "OK",
105 }
106 _LOGGER.debug(
107 f"Received response for {client_call_details.method}.",
108 extra={
109 "serviceName": "google.cloud.tasks.v2.CloudTasks",
110 "rpcName": client_call_details.method,
111 "response": grpc_response,
112 "metadata": grpc_response["metadata"],
113 },
114 )
115 return response
116
117
118class CloudTasksGrpcTransport(CloudTasksTransport):
119 """gRPC backend transport for CloudTasks.
120
121 Cloud Tasks allows developers to manage the execution of
122 background work in their applications.
123
124 This class defines the same methods as the primary client, so the
125 primary client can load the underlying transport implementation
126 and call it.
127
128 It sends protocol buffers over the wire using gRPC (which is built on
129 top of HTTP/2); the ``grpcio`` package must be installed.
130 """
131
132 _stubs: Dict[str, Callable]
133
134 def __init__(
135 self,
136 *,
137 host: str = "cloudtasks.googleapis.com",
138 credentials: Optional[ga_credentials.Credentials] = None,
139 credentials_file: Optional[str] = None,
140 scopes: Optional[Sequence[str]] = None,
141 channel: Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]] = None,
142 api_mtls_endpoint: Optional[str] = None,
143 client_cert_source: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
144 ssl_channel_credentials: Optional[grpc.ChannelCredentials] = None,
145 client_cert_source_for_mtls: Optional[Callable[[], Tuple[bytes, bytes]]] = None,
146 quota_project_id: Optional[str] = None,
147 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
148 always_use_jwt_access: Optional[bool] = False,
149 api_audience: Optional[str] = None,
150 ) -> None:
151 """Instantiate the transport.
152
153 Args:
154 host (Optional[str]):
155 The hostname to connect to (default: 'cloudtasks.googleapis.com').
156 credentials (Optional[google.auth.credentials.Credentials]): The
157 authorization credentials to attach to requests. These
158 credentials identify the application to the service; if none
159 are specified, the client will attempt to ascertain the
160 credentials from the environment.
161 This argument is ignored if a ``channel`` instance is provided.
162 credentials_file (Optional[str]): A file with credentials that can
163 be loaded with :func:`google.auth.load_credentials_from_file`.
164 This argument is ignored if a ``channel`` instance is provided.
165 scopes (Optional(Sequence[str])): A list of scopes. This argument is
166 ignored if a ``channel`` instance is provided.
167 channel (Optional[Union[grpc.Channel, Callable[..., grpc.Channel]]]):
168 A ``Channel`` instance through which to make calls, or a Callable
169 that constructs and returns one. If set to None, ``self.create_channel``
170 is used to create the channel. If a Callable is given, it will be called
171 with the same arguments as used in ``self.create_channel``.
172 api_mtls_endpoint (Optional[str]): Deprecated. The mutual TLS endpoint.
173 If provided, it overrides the ``host`` argument and tries to create
174 a mutual TLS channel with client SSL credentials from
175 ``client_cert_source`` or application default SSL credentials.
176 client_cert_source (Optional[Callable[[], Tuple[bytes, bytes]]]):
177 Deprecated. A callback to provide client SSL certificate bytes and
178 private key bytes, both in PEM format. It is ignored if
179 ``api_mtls_endpoint`` is None.
180 ssl_channel_credentials (grpc.ChannelCredentials): SSL credentials
181 for the grpc channel. It is ignored if a ``channel`` instance is provided.
182 client_cert_source_for_mtls (Optional[Callable[[], Tuple[bytes, bytes]]]):
183 A callback to provide client certificate bytes and private key bytes,
184 both in PEM format. It is used to configure a mutual TLS channel. It is
185 ignored if a ``channel`` instance or ``ssl_channel_credentials`` is provided.
186 quota_project_id (Optional[str]): An optional project to use for billing
187 and quota.
188 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
189 The client info used to send a user-agent string along with
190 API requests. If ``None``, then default info will be used.
191 Generally, you only need to set this if you're developing
192 your own client library.
193 always_use_jwt_access (Optional[bool]): Whether self signed JWT should
194 be used for service account credentials.
195
196 Raises:
197 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
198 creation failed for any reason.
199 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
200 and ``credentials_file`` are passed.
201 """
202 self._grpc_channel = None
203 self._ssl_channel_credentials = ssl_channel_credentials
204 self._stubs: Dict[str, Callable] = {}
205
206 if api_mtls_endpoint:
207 warnings.warn("api_mtls_endpoint is deprecated", DeprecationWarning)
208 if client_cert_source:
209 warnings.warn("client_cert_source is deprecated", DeprecationWarning)
210
211 if isinstance(channel, grpc.Channel):
212 # Ignore credentials if a channel was passed.
213 credentials = None
214 self._ignore_credentials = True
215 # If a channel was explicitly provided, set it.
216 self._grpc_channel = channel
217 self._ssl_channel_credentials = None
218
219 else:
220 if api_mtls_endpoint:
221 host = api_mtls_endpoint
222
223 # Create SSL credentials with client_cert_source or application
224 # default SSL credentials.
225 if client_cert_source:
226 cert, key = client_cert_source()
227 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
228 certificate_chain=cert, private_key=key
229 )
230 else:
231 self._ssl_channel_credentials = SslCredentials().ssl_credentials
232
233 else:
234 if client_cert_source_for_mtls and not ssl_channel_credentials:
235 cert, key = client_cert_source_for_mtls()
236 self._ssl_channel_credentials = grpc.ssl_channel_credentials(
237 certificate_chain=cert, private_key=key
238 )
239
240 # The base transport sets the host, credentials and scopes
241 super().__init__(
242 host=host,
243 credentials=credentials,
244 credentials_file=credentials_file,
245 scopes=scopes,
246 quota_project_id=quota_project_id,
247 client_info=client_info,
248 always_use_jwt_access=always_use_jwt_access,
249 api_audience=api_audience,
250 )
251
252 if not self._grpc_channel:
253 # initialize with the provided callable or the default channel
254 channel_init = channel or type(self).create_channel
255 self._grpc_channel = channel_init(
256 self._host,
257 # use the credentials which are saved
258 credentials=self._credentials,
259 # Set ``credentials_file`` to ``None`` here as
260 # the credentials that we saved earlier should be used.
261 credentials_file=None,
262 scopes=self._scopes,
263 ssl_credentials=self._ssl_channel_credentials,
264 quota_project_id=quota_project_id,
265 options=[
266 ("grpc.max_send_message_length", -1),
267 ("grpc.max_receive_message_length", -1),
268 ],
269 )
270
271 self._interceptor = _LoggingClientInterceptor()
272 self._logged_channel = grpc.intercept_channel(
273 self._grpc_channel, self._interceptor
274 )
275
276 # Wrap messages. This must be done after self._logged_channel exists
277 self._prep_wrapped_messages(client_info)
278
279 @classmethod
280 def create_channel(
281 cls,
282 host: str = "cloudtasks.googleapis.com",
283 credentials: Optional[ga_credentials.Credentials] = None,
284 credentials_file: Optional[str] = None,
285 scopes: Optional[Sequence[str]] = None,
286 quota_project_id: Optional[str] = None,
287 **kwargs,
288 ) -> grpc.Channel:
289 """Create and return a gRPC channel object.
290 Args:
291 host (Optional[str]): The host for the channel to use.
292 credentials (Optional[~.Credentials]): The
293 authorization credentials to attach to requests. These
294 credentials identify this application to the service. If
295 none are specified, the client will attempt to ascertain
296 the credentials from the environment.
297 credentials_file (Optional[str]): A file with credentials that can
298 be loaded with :func:`google.auth.load_credentials_from_file`.
299 This argument is mutually exclusive with credentials.
300 scopes (Optional[Sequence[str]]): A optional list of scopes needed for this
301 service. These are only used when credentials are not specified and
302 are passed to :func:`google.auth.default`.
303 quota_project_id (Optional[str]): An optional project to use for billing
304 and quota.
305 kwargs (Optional[dict]): Keyword arguments, which are passed to the
306 channel creation.
307 Returns:
308 grpc.Channel: A gRPC channel object.
309
310 Raises:
311 google.api_core.exceptions.DuplicateCredentialArgs: If both ``credentials``
312 and ``credentials_file`` are passed.
313 """
314
315 return grpc_helpers.create_channel(
316 host,
317 credentials=credentials,
318 credentials_file=credentials_file,
319 quota_project_id=quota_project_id,
320 default_scopes=cls.AUTH_SCOPES,
321 scopes=scopes,
322 default_host=cls.DEFAULT_HOST,
323 **kwargs,
324 )
325
326 @property
327 def grpc_channel(self) -> grpc.Channel:
328 """Return the channel designed to connect to this service."""
329 return self._grpc_channel
330
331 @property
332 def list_queues(
333 self,
334 ) -> Callable[[cloudtasks.ListQueuesRequest], cloudtasks.ListQueuesResponse]:
335 r"""Return a callable for the list queues method over gRPC.
336
337 Lists queues.
338
339 Queues are returned in lexicographical order.
340
341 Returns:
342 Callable[[~.ListQueuesRequest],
343 ~.ListQueuesResponse]:
344 A function that, when called, will call the underlying RPC
345 on the server.
346 """
347 # Generate a "stub function" on-the-fly which will actually make
348 # the request.
349 # gRPC handles serialization and deserialization, so we just need
350 # to pass in the functions for each.
351 if "list_queues" not in self._stubs:
352 self._stubs["list_queues"] = self._logged_channel.unary_unary(
353 "/google.cloud.tasks.v2.CloudTasks/ListQueues",
354 request_serializer=cloudtasks.ListQueuesRequest.serialize,
355 response_deserializer=cloudtasks.ListQueuesResponse.deserialize,
356 )
357 return self._stubs["list_queues"]
358
359 @property
360 def get_queue(self) -> Callable[[cloudtasks.GetQueueRequest], queue.Queue]:
361 r"""Return a callable for the get queue method over gRPC.
362
363 Gets a queue.
364
365 Returns:
366 Callable[[~.GetQueueRequest],
367 ~.Queue]:
368 A function that, when called, will call the underlying RPC
369 on the server.
370 """
371 # Generate a "stub function" on-the-fly which will actually make
372 # the request.
373 # gRPC handles serialization and deserialization, so we just need
374 # to pass in the functions for each.
375 if "get_queue" not in self._stubs:
376 self._stubs["get_queue"] = self._logged_channel.unary_unary(
377 "/google.cloud.tasks.v2.CloudTasks/GetQueue",
378 request_serializer=cloudtasks.GetQueueRequest.serialize,
379 response_deserializer=queue.Queue.deserialize,
380 )
381 return self._stubs["get_queue"]
382
383 @property
384 def create_queue(
385 self,
386 ) -> Callable[[cloudtasks.CreateQueueRequest], gct_queue.Queue]:
387 r"""Return a callable for the create queue method over gRPC.
388
389 Creates a queue.
390
391 Queues created with this method allow tasks to live for a
392 maximum of 31 days. After a task is 31 days old, the task will
393 be deleted regardless of whether it was dispatched or not.
394
395 WARNING: Using this method may have unintended side effects if
396 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file
397 to manage your queues. Read `Overview of Queue Management and
398 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__
399 before using this method.
400
401 Returns:
402 Callable[[~.CreateQueueRequest],
403 ~.Queue]:
404 A function that, when called, will call the underlying RPC
405 on the server.
406 """
407 # Generate a "stub function" on-the-fly which will actually make
408 # the request.
409 # gRPC handles serialization and deserialization, so we just need
410 # to pass in the functions for each.
411 if "create_queue" not in self._stubs:
412 self._stubs["create_queue"] = self._logged_channel.unary_unary(
413 "/google.cloud.tasks.v2.CloudTasks/CreateQueue",
414 request_serializer=cloudtasks.CreateQueueRequest.serialize,
415 response_deserializer=gct_queue.Queue.deserialize,
416 )
417 return self._stubs["create_queue"]
418
419 @property
420 def update_queue(
421 self,
422 ) -> Callable[[cloudtasks.UpdateQueueRequest], gct_queue.Queue]:
423 r"""Return a callable for the update queue method over gRPC.
424
425 Updates a queue.
426
427 This method creates the queue if it does not exist and updates
428 the queue if it does exist.
429
430 Queues created with this method allow tasks to live for a
431 maximum of 31 days. After a task is 31 days old, the task will
432 be deleted regardless of whether it was dispatched or not.
433
434 WARNING: Using this method may have unintended side effects if
435 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file
436 to manage your queues. Read `Overview of Queue Management and
437 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__
438 before using this method.
439
440 Returns:
441 Callable[[~.UpdateQueueRequest],
442 ~.Queue]:
443 A function that, when called, will call the underlying RPC
444 on the server.
445 """
446 # Generate a "stub function" on-the-fly which will actually make
447 # the request.
448 # gRPC handles serialization and deserialization, so we just need
449 # to pass in the functions for each.
450 if "update_queue" not in self._stubs:
451 self._stubs["update_queue"] = self._logged_channel.unary_unary(
452 "/google.cloud.tasks.v2.CloudTasks/UpdateQueue",
453 request_serializer=cloudtasks.UpdateQueueRequest.serialize,
454 response_deserializer=gct_queue.Queue.deserialize,
455 )
456 return self._stubs["update_queue"]
457
458 @property
459 def delete_queue(
460 self,
461 ) -> Callable[[cloudtasks.DeleteQueueRequest], empty_pb2.Empty]:
462 r"""Return a callable for the delete queue method over gRPC.
463
464 Deletes a queue.
465
466 This command will delete the queue even if it has tasks in it.
467
468 Note: If you delete a queue, a queue with the same name can't be
469 created for 7 days.
470
471 WARNING: Using this method may have unintended side effects if
472 you are using an App Engine ``queue.yaml`` or ``queue.xml`` file
473 to manage your queues. Read `Overview of Queue Management and
474 queue.yaml <https://cloud.google.com/tasks/docs/queue-yaml>`__
475 before using this method.
476
477 Returns:
478 Callable[[~.DeleteQueueRequest],
479 ~.Empty]:
480 A function that, when called, will call the underlying RPC
481 on the server.
482 """
483 # Generate a "stub function" on-the-fly which will actually make
484 # the request.
485 # gRPC handles serialization and deserialization, so we just need
486 # to pass in the functions for each.
487 if "delete_queue" not in self._stubs:
488 self._stubs["delete_queue"] = self._logged_channel.unary_unary(
489 "/google.cloud.tasks.v2.CloudTasks/DeleteQueue",
490 request_serializer=cloudtasks.DeleteQueueRequest.serialize,
491 response_deserializer=empty_pb2.Empty.FromString,
492 )
493 return self._stubs["delete_queue"]
494
495 @property
496 def purge_queue(self) -> Callable[[cloudtasks.PurgeQueueRequest], queue.Queue]:
497 r"""Return a callable for the purge queue method over gRPC.
498
499 Purges a queue by deleting all of its tasks.
500
501 All tasks created before this method is called are
502 permanently deleted.
503
504 Purge operations can take up to one minute to take
505 effect. Tasks might be dispatched before the purge takes
506 effect. A purge is irreversible.
507
508 Returns:
509 Callable[[~.PurgeQueueRequest],
510 ~.Queue]:
511 A function that, when called, will call the underlying RPC
512 on the server.
513 """
514 # Generate a "stub function" on-the-fly which will actually make
515 # the request.
516 # gRPC handles serialization and deserialization, so we just need
517 # to pass in the functions for each.
518 if "purge_queue" not in self._stubs:
519 self._stubs["purge_queue"] = self._logged_channel.unary_unary(
520 "/google.cloud.tasks.v2.CloudTasks/PurgeQueue",
521 request_serializer=cloudtasks.PurgeQueueRequest.serialize,
522 response_deserializer=queue.Queue.deserialize,
523 )
524 return self._stubs["purge_queue"]
525
526 @property
527 def pause_queue(self) -> Callable[[cloudtasks.PauseQueueRequest], queue.Queue]:
528 r"""Return a callable for the pause queue method over gRPC.
529
530 Pauses the queue.
531
532 If a queue is paused then the system will stop dispatching tasks
533 until the queue is resumed via
534 [ResumeQueue][google.cloud.tasks.v2.CloudTasks.ResumeQueue].
535 Tasks can still be added when the queue is paused. A queue is
536 paused if its [state][google.cloud.tasks.v2.Queue.state] is
537 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED].
538
539 Returns:
540 Callable[[~.PauseQueueRequest],
541 ~.Queue]:
542 A function that, when called, will call the underlying RPC
543 on the server.
544 """
545 # Generate a "stub function" on-the-fly which will actually make
546 # the request.
547 # gRPC handles serialization and deserialization, so we just need
548 # to pass in the functions for each.
549 if "pause_queue" not in self._stubs:
550 self._stubs["pause_queue"] = self._logged_channel.unary_unary(
551 "/google.cloud.tasks.v2.CloudTasks/PauseQueue",
552 request_serializer=cloudtasks.PauseQueueRequest.serialize,
553 response_deserializer=queue.Queue.deserialize,
554 )
555 return self._stubs["pause_queue"]
556
557 @property
558 def resume_queue(self) -> Callable[[cloudtasks.ResumeQueueRequest], queue.Queue]:
559 r"""Return a callable for the resume queue method over gRPC.
560
561 Resume a queue.
562
563 This method resumes a queue after it has been
564 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED] or
565 [DISABLED][google.cloud.tasks.v2.Queue.State.DISABLED]. The
566 state of a queue is stored in the queue's
567 [state][google.cloud.tasks.v2.Queue.state]; after calling this
568 method it will be set to
569 [RUNNING][google.cloud.tasks.v2.Queue.State.RUNNING].
570
571 WARNING: Resuming many high-QPS queues at the same time can lead
572 to target overloading. If you are resuming high-QPS queues,
573 follow the 500/50/5 pattern described in `Managing Cloud Tasks
574 Scaling
575 Risks <https://cloud.google.com/tasks/docs/manage-cloud-task-scaling>`__.
576
577 Returns:
578 Callable[[~.ResumeQueueRequest],
579 ~.Queue]:
580 A function that, when called, will call the underlying RPC
581 on the server.
582 """
583 # Generate a "stub function" on-the-fly which will actually make
584 # the request.
585 # gRPC handles serialization and deserialization, so we just need
586 # to pass in the functions for each.
587 if "resume_queue" not in self._stubs:
588 self._stubs["resume_queue"] = self._logged_channel.unary_unary(
589 "/google.cloud.tasks.v2.CloudTasks/ResumeQueue",
590 request_serializer=cloudtasks.ResumeQueueRequest.serialize,
591 response_deserializer=queue.Queue.deserialize,
592 )
593 return self._stubs["resume_queue"]
594
595 @property
596 def get_iam_policy(
597 self,
598 ) -> Callable[[iam_policy_pb2.GetIamPolicyRequest], policy_pb2.Policy]:
599 r"""Return a callable for the get iam policy method over gRPC.
600
601 Gets the access control policy for a
602 [Queue][google.cloud.tasks.v2.Queue]. Returns an empty policy if
603 the resource exists and does not have a policy set.
604
605 Authorization requires the following `Google
606 IAM <https://cloud.google.com/iam>`__ permission on the
607 specified resource parent:
608
609 - ``cloudtasks.queues.getIamPolicy``
610
611 Returns:
612 Callable[[~.GetIamPolicyRequest],
613 ~.Policy]:
614 A function that, when called, will call the underlying RPC
615 on the server.
616 """
617 # Generate a "stub function" on-the-fly which will actually make
618 # the request.
619 # gRPC handles serialization and deserialization, so we just need
620 # to pass in the functions for each.
621 if "get_iam_policy" not in self._stubs:
622 self._stubs["get_iam_policy"] = self._logged_channel.unary_unary(
623 "/google.cloud.tasks.v2.CloudTasks/GetIamPolicy",
624 request_serializer=iam_policy_pb2.GetIamPolicyRequest.SerializeToString,
625 response_deserializer=policy_pb2.Policy.FromString,
626 )
627 return self._stubs["get_iam_policy"]
628
629 @property
630 def set_iam_policy(
631 self,
632 ) -> Callable[[iam_policy_pb2.SetIamPolicyRequest], policy_pb2.Policy]:
633 r"""Return a callable for the set iam policy method over gRPC.
634
635 Sets the access control policy for a
636 [Queue][google.cloud.tasks.v2.Queue]. Replaces any existing
637 policy.
638
639 Note: The Cloud Console does not check queue-level IAM
640 permissions yet. Project-level permissions are required to use
641 the Cloud Console.
642
643 Authorization requires the following `Google
644 IAM <https://cloud.google.com/iam>`__ permission on the
645 specified resource parent:
646
647 - ``cloudtasks.queues.setIamPolicy``
648
649 Returns:
650 Callable[[~.SetIamPolicyRequest],
651 ~.Policy]:
652 A function that, when called, will call the underlying RPC
653 on the server.
654 """
655 # Generate a "stub function" on-the-fly which will actually make
656 # the request.
657 # gRPC handles serialization and deserialization, so we just need
658 # to pass in the functions for each.
659 if "set_iam_policy" not in self._stubs:
660 self._stubs["set_iam_policy"] = self._logged_channel.unary_unary(
661 "/google.cloud.tasks.v2.CloudTasks/SetIamPolicy",
662 request_serializer=iam_policy_pb2.SetIamPolicyRequest.SerializeToString,
663 response_deserializer=policy_pb2.Policy.FromString,
664 )
665 return self._stubs["set_iam_policy"]
666
667 @property
668 def test_iam_permissions(
669 self,
670 ) -> Callable[
671 [iam_policy_pb2.TestIamPermissionsRequest],
672 iam_policy_pb2.TestIamPermissionsResponse,
673 ]:
674 r"""Return a callable for the test iam permissions method over gRPC.
675
676 Returns permissions that a caller has on a
677 [Queue][google.cloud.tasks.v2.Queue]. If the resource does not
678 exist, this will return an empty set of permissions, not a
679 [NOT_FOUND][google.rpc.Code.NOT_FOUND] error.
680
681 Note: This operation is designed to be used for building
682 permission-aware UIs and command-line tools, not for
683 authorization checking. This operation may "fail open" without
684 warning.
685
686 Returns:
687 Callable[[~.TestIamPermissionsRequest],
688 ~.TestIamPermissionsResponse]:
689 A function that, when called, will call the underlying RPC
690 on the server.
691 """
692 # Generate a "stub function" on-the-fly which will actually make
693 # the request.
694 # gRPC handles serialization and deserialization, so we just need
695 # to pass in the functions for each.
696 if "test_iam_permissions" not in self._stubs:
697 self._stubs["test_iam_permissions"] = self._logged_channel.unary_unary(
698 "/google.cloud.tasks.v2.CloudTasks/TestIamPermissions",
699 request_serializer=iam_policy_pb2.TestIamPermissionsRequest.SerializeToString,
700 response_deserializer=iam_policy_pb2.TestIamPermissionsResponse.FromString,
701 )
702 return self._stubs["test_iam_permissions"]
703
704 @property
705 def list_tasks(
706 self,
707 ) -> Callable[[cloudtasks.ListTasksRequest], cloudtasks.ListTasksResponse]:
708 r"""Return a callable for the list tasks method over gRPC.
709
710 Lists the tasks in a queue.
711
712 By default, only the
713 [BASIC][google.cloud.tasks.v2.Task.View.BASIC] view is retrieved
714 due to performance considerations;
715 [response_view][google.cloud.tasks.v2.ListTasksRequest.response_view]
716 controls the subset of information which is returned.
717
718 The tasks may be returned in any order. The ordering may change
719 at any time.
720
721 Returns:
722 Callable[[~.ListTasksRequest],
723 ~.ListTasksResponse]:
724 A function that, when called, will call the underlying RPC
725 on the server.
726 """
727 # Generate a "stub function" on-the-fly which will actually make
728 # the request.
729 # gRPC handles serialization and deserialization, so we just need
730 # to pass in the functions for each.
731 if "list_tasks" not in self._stubs:
732 self._stubs["list_tasks"] = self._logged_channel.unary_unary(
733 "/google.cloud.tasks.v2.CloudTasks/ListTasks",
734 request_serializer=cloudtasks.ListTasksRequest.serialize,
735 response_deserializer=cloudtasks.ListTasksResponse.deserialize,
736 )
737 return self._stubs["list_tasks"]
738
739 @property
740 def get_task(self) -> Callable[[cloudtasks.GetTaskRequest], task.Task]:
741 r"""Return a callable for the get task method over gRPC.
742
743 Gets a task.
744
745 Returns:
746 Callable[[~.GetTaskRequest],
747 ~.Task]:
748 A function that, when called, will call the underlying RPC
749 on the server.
750 """
751 # Generate a "stub function" on-the-fly which will actually make
752 # the request.
753 # gRPC handles serialization and deserialization, so we just need
754 # to pass in the functions for each.
755 if "get_task" not in self._stubs:
756 self._stubs["get_task"] = self._logged_channel.unary_unary(
757 "/google.cloud.tasks.v2.CloudTasks/GetTask",
758 request_serializer=cloudtasks.GetTaskRequest.serialize,
759 response_deserializer=task.Task.deserialize,
760 )
761 return self._stubs["get_task"]
762
763 @property
764 def create_task(self) -> Callable[[cloudtasks.CreateTaskRequest], gct_task.Task]:
765 r"""Return a callable for the create task method over gRPC.
766
767 Creates a task and adds it to a queue.
768
769 Tasks cannot be updated after creation; there is no UpdateTask
770 command.
771
772 - The maximum task size is 100KB.
773
774 Returns:
775 Callable[[~.CreateTaskRequest],
776 ~.Task]:
777 A function that, when called, will call the underlying RPC
778 on the server.
779 """
780 # Generate a "stub function" on-the-fly which will actually make
781 # the request.
782 # gRPC handles serialization and deserialization, so we just need
783 # to pass in the functions for each.
784 if "create_task" not in self._stubs:
785 self._stubs["create_task"] = self._logged_channel.unary_unary(
786 "/google.cloud.tasks.v2.CloudTasks/CreateTask",
787 request_serializer=cloudtasks.CreateTaskRequest.serialize,
788 response_deserializer=gct_task.Task.deserialize,
789 )
790 return self._stubs["create_task"]
791
792 @property
793 def delete_task(self) -> Callable[[cloudtasks.DeleteTaskRequest], empty_pb2.Empty]:
794 r"""Return a callable for the delete task method over gRPC.
795
796 Deletes a task.
797
798 A task can be deleted if it is scheduled or dispatched.
799 A task cannot be deleted if it has executed successfully
800 or permanently failed.
801
802 Returns:
803 Callable[[~.DeleteTaskRequest],
804 ~.Empty]:
805 A function that, when called, will call the underlying RPC
806 on the server.
807 """
808 # Generate a "stub function" on-the-fly which will actually make
809 # the request.
810 # gRPC handles serialization and deserialization, so we just need
811 # to pass in the functions for each.
812 if "delete_task" not in self._stubs:
813 self._stubs["delete_task"] = self._logged_channel.unary_unary(
814 "/google.cloud.tasks.v2.CloudTasks/DeleteTask",
815 request_serializer=cloudtasks.DeleteTaskRequest.serialize,
816 response_deserializer=empty_pb2.Empty.FromString,
817 )
818 return self._stubs["delete_task"]
819
820 @property
821 def run_task(self) -> Callable[[cloudtasks.RunTaskRequest], task.Task]:
822 r"""Return a callable for the run task method over gRPC.
823
824 Forces a task to run now.
825
826 When this method is called, Cloud Tasks will dispatch the task,
827 even if the task is already running, the queue has reached its
828 [RateLimits][google.cloud.tasks.v2.RateLimits] or is
829 [PAUSED][google.cloud.tasks.v2.Queue.State.PAUSED].
830
831 This command is meant to be used for manual debugging. For
832 example, [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] can
833 be used to retry a failed task after a fix has been made or to
834 manually force a task to be dispatched now.
835
836 The dispatched task is returned. That is, the task that is
837 returned contains the [status][Task.status] after the task is
838 dispatched but before the task is received by its target.
839
840 If Cloud Tasks receives a successful response from the task's
841 target, then the task will be deleted; otherwise the task's
842 [schedule_time][google.cloud.tasks.v2.Task.schedule_time] will
843 be reset to the time that
844 [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] was called
845 plus the retry delay specified in the queue's
846 [RetryConfig][google.cloud.tasks.v2.RetryConfig].
847
848 [RunTask][google.cloud.tasks.v2.CloudTasks.RunTask] returns
849 [NOT_FOUND][google.rpc.Code.NOT_FOUND] when it is called on a
850 task that has already succeeded or permanently failed.
851
852 Returns:
853 Callable[[~.RunTaskRequest],
854 ~.Task]:
855 A function that, when called, will call the underlying RPC
856 on the server.
857 """
858 # Generate a "stub function" on-the-fly which will actually make
859 # the request.
860 # gRPC handles serialization and deserialization, so we just need
861 # to pass in the functions for each.
862 if "run_task" not in self._stubs:
863 self._stubs["run_task"] = self._logged_channel.unary_unary(
864 "/google.cloud.tasks.v2.CloudTasks/RunTask",
865 request_serializer=cloudtasks.RunTaskRequest.serialize,
866 response_deserializer=task.Task.deserialize,
867 )
868 return self._stubs["run_task"]
869
870 def close(self):
871 self._logged_channel.close()
872
873 @property
874 def list_locations(
875 self,
876 ) -> Callable[
877 [locations_pb2.ListLocationsRequest], locations_pb2.ListLocationsResponse
878 ]:
879 r"""Return a callable for the list locations method over gRPC."""
880 # Generate a "stub function" on-the-fly which will actually make
881 # the request.
882 # gRPC handles serialization and deserialization, so we just need
883 # to pass in the functions for each.
884 if "list_locations" not in self._stubs:
885 self._stubs["list_locations"] = self._logged_channel.unary_unary(
886 "/google.cloud.location.Locations/ListLocations",
887 request_serializer=locations_pb2.ListLocationsRequest.SerializeToString,
888 response_deserializer=locations_pb2.ListLocationsResponse.FromString,
889 )
890 return self._stubs["list_locations"]
891
892 @property
893 def get_location(
894 self,
895 ) -> Callable[[locations_pb2.GetLocationRequest], locations_pb2.Location]:
896 r"""Return a callable for the list locations method over gRPC."""
897 # Generate a "stub function" on-the-fly which will actually make
898 # the request.
899 # gRPC handles serialization and deserialization, so we just need
900 # to pass in the functions for each.
901 if "get_location" not in self._stubs:
902 self._stubs["get_location"] = self._logged_channel.unary_unary(
903 "/google.cloud.location.Locations/GetLocation",
904 request_serializer=locations_pb2.GetLocationRequest.SerializeToString,
905 response_deserializer=locations_pb2.Location.FromString,
906 )
907 return self._stubs["get_location"]
908
909 @property
910 def kind(self) -> str:
911 return "grpc"
912
913
914__all__ = ("CloudTasksGrpcTransport",)