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 logging as std_logging
17from collections import OrderedDict
18import re
19from typing import (
20 Dict,
21 Callable,
22 Mapping,
23 MutableMapping,
24 MutableSequence,
25 Optional,
26 Sequence,
27 Tuple,
28 Type,
29 Union,
30)
31
32from google.pubsub_v1 import gapic_version as package_version
33
34from google.api_core.client_options import ClientOptions
35from google.api_core import exceptions as core_exceptions
36from google.api_core import gapic_v1
37from google.api_core import retry_async as retries
38from google.auth import credentials as ga_credentials # type: ignore
39from google.oauth2 import service_account # type: ignore
40import google.protobuf
41
42
43try:
44 OptionalRetry = Union[retries.AsyncRetry, gapic_v1.method._MethodDefault, None]
45except AttributeError: # pragma: NO COVER
46 OptionalRetry = Union[retries.AsyncRetry, object, None] # type: ignore
47
48from google.iam.v1 import iam_policy_pb2 # type: ignore
49from google.iam.v1 import policy_pb2 # type: ignore
50from google.protobuf import duration_pb2 # type: ignore
51from google.protobuf import field_mask_pb2 # type: ignore
52from google.pubsub_v1.services.publisher import pagers
53from google.pubsub_v1.types import pubsub
54from google.pubsub_v1.types import TimeoutType
55from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO
56from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport
57from .client import PublisherClient
58
59try:
60 from google.api_core import client_logging # type: ignore
61
62 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
63except ImportError: # pragma: NO COVER
64 CLIENT_LOGGING_SUPPORTED = False
65
66_LOGGER = std_logging.getLogger(__name__)
67
68
69class PublisherAsyncClient:
70 """The service that an application uses to manipulate topics,
71 and to send messages to a topic.
72 """
73
74 _client: PublisherClient
75
76 # Copy defaults from the synchronous client for use here.
77 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
78 DEFAULT_ENDPOINT = PublisherClient.DEFAULT_ENDPOINT
79 DEFAULT_MTLS_ENDPOINT = PublisherClient.DEFAULT_MTLS_ENDPOINT
80 _DEFAULT_ENDPOINT_TEMPLATE = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE
81 _DEFAULT_UNIVERSE = PublisherClient._DEFAULT_UNIVERSE
82
83 schema_path = staticmethod(PublisherClient.schema_path)
84 parse_schema_path = staticmethod(PublisherClient.parse_schema_path)
85 subscription_path = staticmethod(PublisherClient.subscription_path)
86 parse_subscription_path = staticmethod(PublisherClient.parse_subscription_path)
87 topic_path = staticmethod(PublisherClient.topic_path)
88 parse_topic_path = staticmethod(PublisherClient.parse_topic_path)
89 common_billing_account_path = staticmethod(
90 PublisherClient.common_billing_account_path
91 )
92 parse_common_billing_account_path = staticmethod(
93 PublisherClient.parse_common_billing_account_path
94 )
95 common_folder_path = staticmethod(PublisherClient.common_folder_path)
96 parse_common_folder_path = staticmethod(PublisherClient.parse_common_folder_path)
97 common_organization_path = staticmethod(PublisherClient.common_organization_path)
98 parse_common_organization_path = staticmethod(
99 PublisherClient.parse_common_organization_path
100 )
101 common_project_path = staticmethod(PublisherClient.common_project_path)
102 parse_common_project_path = staticmethod(PublisherClient.parse_common_project_path)
103 common_location_path = staticmethod(PublisherClient.common_location_path)
104 parse_common_location_path = staticmethod(
105 PublisherClient.parse_common_location_path
106 )
107
108 @classmethod
109 def from_service_account_info(cls, info: dict, *args, **kwargs):
110 """Creates an instance of this client using the provided credentials
111 info.
112
113 Args:
114 info (dict): The service account private key info.
115 args: Additional arguments to pass to the constructor.
116 kwargs: Additional arguments to pass to the constructor.
117
118 Returns:
119 PublisherAsyncClient: The constructed client.
120 """
121 return PublisherClient.from_service_account_info.__func__(PublisherAsyncClient, info, *args, **kwargs) # type: ignore
122
123 @classmethod
124 def from_service_account_file(cls, filename: str, *args, **kwargs):
125 """Creates an instance of this client using the provided credentials
126 file.
127
128 Args:
129 filename (str): The path to the service account private key json
130 file.
131 args: Additional arguments to pass to the constructor.
132 kwargs: Additional arguments to pass to the constructor.
133
134 Returns:
135 PublisherAsyncClient: The constructed client.
136 """
137 return PublisherClient.from_service_account_file.__func__(PublisherAsyncClient, filename, *args, **kwargs) # type: ignore
138
139 from_service_account_json = from_service_account_file
140
141 @classmethod
142 def get_mtls_endpoint_and_cert_source(
143 cls, client_options: Optional[ClientOptions] = None
144 ):
145 """Return the API endpoint and client cert source for mutual TLS.
146
147 The client cert source is determined in the following order:
148 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
149 client cert source is None.
150 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
151 default client cert source exists, use the default one; otherwise the client cert
152 source is None.
153
154 The API endpoint is determined in the following order:
155 (1) if `client_options.api_endpoint` if provided, use the provided one.
156 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
157 default mTLS endpoint; if the environment variable is "never", use the default API
158 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
159 use the default API endpoint.
160
161 More details can be found at https://google.aip.dev/auth/4114.
162
163 Args:
164 client_options (google.api_core.client_options.ClientOptions): Custom options for the
165 client. Only the `api_endpoint` and `client_cert_source` properties may be used
166 in this method.
167
168 Returns:
169 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
170 client cert source to use.
171
172 Raises:
173 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
174 """
175 return PublisherClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
176
177 @property
178 def transport(self) -> PublisherTransport:
179 """Returns the transport used by the client instance.
180
181 Returns:
182 PublisherTransport: The transport used by the client instance.
183 """
184 return self._client.transport
185
186 @property
187 def api_endpoint(self):
188 """Return the API endpoint used by the client instance.
189
190 Returns:
191 str: The API endpoint used by the client instance.
192 """
193 return self._client._api_endpoint
194
195 @property
196 def universe_domain(self) -> str:
197 """Return the universe domain used by the client instance.
198
199 Returns:
200 str: The universe domain used
201 by the client instance.
202 """
203 return self._client._universe_domain
204
205 get_transport_class = PublisherClient.get_transport_class
206
207 def __init__(
208 self,
209 *,
210 credentials: Optional[ga_credentials.Credentials] = None,
211 transport: Optional[
212 Union[str, PublisherTransport, Callable[..., PublisherTransport]]
213 ] = "grpc_asyncio",
214 client_options: Optional[ClientOptions] = None,
215 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
216 ) -> None:
217 """Instantiates the publisher async client.
218
219 Args:
220 credentials (Optional[google.auth.credentials.Credentials]): The
221 authorization credentials to attach to requests. These
222 credentials identify the application to the service; if none
223 are specified, the client will attempt to ascertain the
224 credentials from the environment.
225 transport (Optional[Union[str,PublisherTransport,Callable[..., PublisherTransport]]]):
226 The transport to use, or a Callable that constructs and returns a new transport to use.
227 If a Callable is given, it will be called with the same set of initialization
228 arguments as used in the PublisherTransport constructor.
229 If set to None, a transport is chosen automatically.
230 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
231 Custom options for the client.
232
233 1. The ``api_endpoint`` property can be used to override the
234 default endpoint provided by the client when ``transport`` is
235 not explicitly provided. Only if this property is not set and
236 ``transport`` was not explicitly provided, the endpoint is
237 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
238 variable, which have one of the following values:
239 "always" (always use the default mTLS endpoint), "never" (always
240 use the default regular endpoint) and "auto" (auto-switch to the
241 default mTLS endpoint if client certificate is present; this is
242 the default value).
243
244 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
245 is "true", then the ``client_cert_source`` property can be used
246 to provide a client certificate for mTLS transport. If
247 not provided, the default SSL client certificate will be used if
248 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
249 set, no client certificate will be used.
250
251 3. The ``universe_domain`` property can be used to override the
252 default "googleapis.com" universe. Note that ``api_endpoint``
253 property still takes precedence; and ``universe_domain`` is
254 currently not supported for mTLS.
255
256 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
257 The client info used to send a user-agent string along with
258 API requests. If ``None``, then default info will be used.
259 Generally, you only need to set this if you're developing
260 your own client library.
261
262 Raises:
263 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
264 creation failed for any reason.
265 """
266 self._client = PublisherClient(
267 credentials=credentials,
268 transport=transport,
269 client_options=client_options,
270 client_info=client_info,
271 )
272
273 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
274 std_logging.DEBUG
275 ): # pragma: NO COVER
276 _LOGGER.debug(
277 "Created client `google.pubsub_v1.PublisherAsyncClient`.",
278 extra={
279 "serviceName": "google.pubsub.v1.Publisher",
280 "universeDomain": getattr(
281 self._client._transport._credentials, "universe_domain", ""
282 ),
283 "credentialsType": f"{type(self._client._transport._credentials).__module__}.{type(self._client._transport._credentials).__qualname__}",
284 "credentialsInfo": getattr(
285 self.transport._credentials, "get_cred_info", lambda: None
286 )(),
287 }
288 if hasattr(self._client._transport, "_credentials")
289 else {
290 "serviceName": "google.pubsub.v1.Publisher",
291 "credentialsType": None,
292 },
293 )
294
295 async def create_topic(
296 self,
297 request: Optional[Union[pubsub.Topic, dict]] = None,
298 *,
299 name: Optional[str] = None,
300 retry: OptionalRetry = gapic_v1.method.DEFAULT,
301 timeout: TimeoutType = gapic_v1.method.DEFAULT,
302 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
303 ) -> pubsub.Topic:
304 r"""Creates the given topic with the given name. See the [resource
305 name rules]
306 (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names).
307
308 .. code-block:: python
309
310 # This snippet has been automatically generated and should be regarded as a
311 # code template only.
312 # It will require modifications to work:
313 # - It may require correct/in-range values for request initialization.
314 # - It may require specifying regional endpoints when creating the service
315 # client as shown in:
316 # https://googleapis.dev/python/google-api-core/latest/client_options.html
317 from google import pubsub_v1
318
319 async def sample_create_topic():
320 # Create a client
321 client = pubsub_v1.PublisherAsyncClient()
322
323 # Initialize request argument(s)
324 request = pubsub_v1.Topic(
325 name="name_value",
326 )
327
328 # Make the request
329 response = await client.create_topic(request=request)
330
331 # Handle the response
332 print(response)
333
334 Args:
335 request (Optional[Union[google.pubsub_v1.types.Topic, dict]]):
336 The request object. A topic resource.
337 name (:class:`str`):
338 Required. The name of the topic. It must have the format
339 ``"projects/{project}/topics/{topic}"``. ``{topic}``
340 must start with a letter, and contain only letters
341 (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``),
342 underscores (``_``), periods (``.``), tildes (``~``),
343 plus (``+``) or percent signs (``%``). It must be
344 between 3 and 255 characters in length, and it must not
345 start with ``"goog"``.
346
347 This corresponds to the ``name`` field
348 on the ``request`` instance; if ``request`` is provided, this
349 should not be set.
350 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
351 should be retried.
352 timeout (TimeoutType):
353 The timeout for this request.
354 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
355 sent along with the request as metadata. Normally, each value must be of type `str`,
356 but for metadata keys ending with the suffix `-bin`, the corresponding values must
357 be of type `bytes`.
358
359 Returns:
360 google.pubsub_v1.types.Topic:
361 A topic resource.
362 """
363 # Create or coerce a protobuf request object.
364 # - Quick check: If we got a request object, we should *not* have
365 # gotten any keyword arguments that map to the request.
366 flattened_params = [name]
367 has_flattened_params = (
368 len([param for param in flattened_params if param is not None]) > 0
369 )
370 if request is not None and has_flattened_params:
371 raise ValueError(
372 "If the `request` argument is set, then none of "
373 "the individual field arguments should be set."
374 )
375
376 # - Use the request object if provided (there's no risk of modifying the input as
377 # there are no flattened fields), or create one.
378 if not isinstance(request, pubsub.Topic):
379 request = pubsub.Topic(request)
380
381 # If we have keyword arguments corresponding to fields on the
382 # request, apply these.
383 if name is not None:
384 request.name = name
385
386 # Wrap the RPC method; this adds retry and timeout information,
387 # and friendly error handling.
388 rpc = self._client._transport._wrapped_methods[
389 self._client._transport.create_topic
390 ]
391
392 # Certain fields should be provided within the metadata header;
393 # add these here.
394 metadata = tuple(metadata) + (
395 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
396 )
397
398 # Validate the universe domain.
399 self._client._validate_universe_domain()
400
401 # Send the request.
402 response = await rpc(
403 request,
404 retry=retry,
405 timeout=timeout,
406 metadata=metadata,
407 )
408
409 # Done; return the response.
410 return response
411
412 async def update_topic(
413 self,
414 request: Optional[Union[pubsub.UpdateTopicRequest, dict]] = None,
415 *,
416 topic: Optional[pubsub.Topic] = None,
417 update_mask: Optional[field_mask_pb2.FieldMask] = None,
418 retry: OptionalRetry = gapic_v1.method.DEFAULT,
419 timeout: TimeoutType = gapic_v1.method.DEFAULT,
420 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
421 ) -> pubsub.Topic:
422 r"""Updates an existing topic by updating the fields
423 specified in the update mask. Note that certain
424 properties of a topic are not modifiable.
425
426 .. code-block:: python
427
428 # This snippet has been automatically generated and should be regarded as a
429 # code template only.
430 # It will require modifications to work:
431 # - It may require correct/in-range values for request initialization.
432 # - It may require specifying regional endpoints when creating the service
433 # client as shown in:
434 # https://googleapis.dev/python/google-api-core/latest/client_options.html
435 from google import pubsub_v1
436
437 async def sample_update_topic():
438 # Create a client
439 client = pubsub_v1.PublisherAsyncClient()
440
441 # Initialize request argument(s)
442 topic = pubsub_v1.Topic()
443 topic.name = "name_value"
444
445 request = pubsub_v1.UpdateTopicRequest(
446 topic=topic,
447 )
448
449 # Make the request
450 response = await client.update_topic(request=request)
451
452 # Handle the response
453 print(response)
454
455 Args:
456 request (Optional[Union[google.pubsub_v1.types.UpdateTopicRequest, dict]]):
457 The request object. Request for the UpdateTopic method.
458 topic (:class:`google.pubsub_v1.types.Topic`):
459 Required. The updated topic object.
460 This corresponds to the ``topic`` field
461 on the ``request`` instance; if ``request`` is provided, this
462 should not be set.
463 update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
464 Required. Indicates which fields in the provided topic
465 to update. Must be specified and non-empty. Note that if
466 ``update_mask`` contains "message_storage_policy" but
467 the ``message_storage_policy`` is not set in the
468 ``topic`` provided above, then the updated value is
469 determined by the policy configured at the project or
470 organization level.
471
472 This corresponds to the ``update_mask`` field
473 on the ``request`` instance; if ``request`` is provided, this
474 should not be set.
475 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
476 should be retried.
477 timeout (TimeoutType):
478 The timeout for this request.
479 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
480 sent along with the request as metadata. Normally, each value must be of type `str`,
481 but for metadata keys ending with the suffix `-bin`, the corresponding values must
482 be of type `bytes`.
483
484 Returns:
485 google.pubsub_v1.types.Topic:
486 A topic resource.
487 """
488 # Create or coerce a protobuf request object.
489 # - Quick check: If we got a request object, we should *not* have
490 # gotten any keyword arguments that map to the request.
491 flattened_params = [topic, update_mask]
492 has_flattened_params = (
493 len([param for param in flattened_params if param is not None]) > 0
494 )
495 if request is not None and has_flattened_params:
496 raise ValueError(
497 "If the `request` argument is set, then none of "
498 "the individual field arguments should be set."
499 )
500
501 # - Use the request object if provided (there's no risk of modifying the input as
502 # there are no flattened fields), or create one.
503 if not isinstance(request, pubsub.UpdateTopicRequest):
504 request = pubsub.UpdateTopicRequest(request)
505
506 # If we have keyword arguments corresponding to fields on the
507 # request, apply these.
508 if topic is not None:
509 request.topic = topic
510 if update_mask is not None:
511 request.update_mask = update_mask
512
513 # Wrap the RPC method; this adds retry and timeout information,
514 # and friendly error handling.
515 rpc = self._client._transport._wrapped_methods[
516 self._client._transport.update_topic
517 ]
518
519 # Certain fields should be provided within the metadata header;
520 # add these here.
521 metadata = tuple(metadata) + (
522 gapic_v1.routing_header.to_grpc_metadata(
523 (("topic.name", request.topic.name),)
524 ),
525 )
526
527 # Validate the universe domain.
528 self._client._validate_universe_domain()
529
530 # Send the request.
531 response = await rpc(
532 request,
533 retry=retry,
534 timeout=timeout,
535 metadata=metadata,
536 )
537
538 # Done; return the response.
539 return response
540
541 async def publish(
542 self,
543 request: Optional[Union[pubsub.PublishRequest, dict]] = None,
544 *,
545 topic: Optional[str] = None,
546 messages: Optional[MutableSequence[pubsub.PubsubMessage]] = None,
547 retry: OptionalRetry = gapic_v1.method.DEFAULT,
548 timeout: TimeoutType = gapic_v1.method.DEFAULT,
549 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
550 ) -> pubsub.PublishResponse:
551 r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if
552 the topic does not exist.
553
554 .. code-block:: python
555
556 # This snippet has been automatically generated and should be regarded as a
557 # code template only.
558 # It will require modifications to work:
559 # - It may require correct/in-range values for request initialization.
560 # - It may require specifying regional endpoints when creating the service
561 # client as shown in:
562 # https://googleapis.dev/python/google-api-core/latest/client_options.html
563 from google import pubsub_v1
564
565 async def sample_publish():
566 # Create a client
567 client = pubsub_v1.PublisherAsyncClient()
568
569 # Initialize request argument(s)
570 request = pubsub_v1.PublishRequest(
571 topic="topic_value",
572 )
573
574 # Make the request
575 response = await client.publish(request=request)
576
577 # Handle the response
578 print(response)
579
580 Args:
581 request (Optional[Union[google.pubsub_v1.types.PublishRequest, dict]]):
582 The request object. Request for the Publish method.
583 topic (:class:`str`):
584 Required. The messages in the request will be published
585 on this topic. Format is
586 ``projects/{project}/topics/{topic}``.
587
588 This corresponds to the ``topic`` field
589 on the ``request`` instance; if ``request`` is provided, this
590 should not be set.
591 messages (:class:`MutableSequence[google.pubsub_v1.types.PubsubMessage]`):
592 Required. The messages to publish.
593 This corresponds to the ``messages`` field
594 on the ``request`` instance; if ``request`` is provided, this
595 should not be set.
596 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
597 should be retried.
598 timeout (TimeoutType):
599 The timeout for this request.
600 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
601 sent along with the request as metadata. Normally, each value must be of type `str`,
602 but for metadata keys ending with the suffix `-bin`, the corresponding values must
603 be of type `bytes`.
604
605 Returns:
606 google.pubsub_v1.types.PublishResponse:
607 Response for the Publish method.
608 """
609 # Create or coerce a protobuf request object.
610 # - Quick check: If we got a request object, we should *not* have
611 # gotten any keyword arguments that map to the request.
612 flattened_params = [topic, messages]
613 has_flattened_params = (
614 len([param for param in flattened_params if param is not None]) > 0
615 )
616 if request is not None and has_flattened_params:
617 raise ValueError(
618 "If the `request` argument is set, then none of "
619 "the individual field arguments should be set."
620 )
621
622 # - Use the request object if provided (there's no risk of modifying the input as
623 # there are no flattened fields), or create one.
624 if not isinstance(request, pubsub.PublishRequest):
625 request = pubsub.PublishRequest(request)
626
627 # If we have keyword arguments corresponding to fields on the
628 # request, apply these.
629 if topic is not None:
630 request.topic = topic
631 if messages:
632 request.messages.extend(messages)
633
634 # Wrap the RPC method; this adds retry and timeout information,
635 # and friendly error handling.
636 rpc = self._client._transport._wrapped_methods[self._client._transport.publish]
637
638 # Certain fields should be provided within the metadata header;
639 # add these here.
640 metadata = tuple(metadata) + (
641 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)),
642 )
643
644 # Validate the universe domain.
645 self._client._validate_universe_domain()
646
647 # Send the request.
648 response = await rpc(
649 request,
650 retry=retry,
651 timeout=timeout,
652 metadata=metadata,
653 )
654
655 # Done; return the response.
656 return response
657
658 async def get_topic(
659 self,
660 request: Optional[Union[pubsub.GetTopicRequest, dict]] = None,
661 *,
662 topic: Optional[str] = None,
663 retry: OptionalRetry = gapic_v1.method.DEFAULT,
664 timeout: TimeoutType = gapic_v1.method.DEFAULT,
665 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
666 ) -> pubsub.Topic:
667 r"""Gets the configuration of a topic.
668
669 .. code-block:: python
670
671 # This snippet has been automatically generated and should be regarded as a
672 # code template only.
673 # It will require modifications to work:
674 # - It may require correct/in-range values for request initialization.
675 # - It may require specifying regional endpoints when creating the service
676 # client as shown in:
677 # https://googleapis.dev/python/google-api-core/latest/client_options.html
678 from google import pubsub_v1
679
680 async def sample_get_topic():
681 # Create a client
682 client = pubsub_v1.PublisherAsyncClient()
683
684 # Initialize request argument(s)
685 request = pubsub_v1.GetTopicRequest(
686 topic="topic_value",
687 )
688
689 # Make the request
690 response = await client.get_topic(request=request)
691
692 # Handle the response
693 print(response)
694
695 Args:
696 request (Optional[Union[google.pubsub_v1.types.GetTopicRequest, dict]]):
697 The request object. Request for the GetTopic method.
698 topic (:class:`str`):
699 Required. The name of the topic to get. Format is
700 ``projects/{project}/topics/{topic}``.
701
702 This corresponds to the ``topic`` field
703 on the ``request`` instance; if ``request`` is provided, this
704 should not be set.
705 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
706 should be retried.
707 timeout (TimeoutType):
708 The timeout for this request.
709 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
710 sent along with the request as metadata. Normally, each value must be of type `str`,
711 but for metadata keys ending with the suffix `-bin`, the corresponding values must
712 be of type `bytes`.
713
714 Returns:
715 google.pubsub_v1.types.Topic:
716 A topic resource.
717 """
718 # Create or coerce a protobuf request object.
719 # - Quick check: If we got a request object, we should *not* have
720 # gotten any keyword arguments that map to the request.
721 flattened_params = [topic]
722 has_flattened_params = (
723 len([param for param in flattened_params if param is not None]) > 0
724 )
725 if request is not None and has_flattened_params:
726 raise ValueError(
727 "If the `request` argument is set, then none of "
728 "the individual field arguments should be set."
729 )
730
731 # - Use the request object if provided (there's no risk of modifying the input as
732 # there are no flattened fields), or create one.
733 if not isinstance(request, pubsub.GetTopicRequest):
734 request = pubsub.GetTopicRequest(request)
735
736 # If we have keyword arguments corresponding to fields on the
737 # request, apply these.
738 if topic is not None:
739 request.topic = topic
740
741 # Wrap the RPC method; this adds retry and timeout information,
742 # and friendly error handling.
743 rpc = self._client._transport._wrapped_methods[
744 self._client._transport.get_topic
745 ]
746
747 # Certain fields should be provided within the metadata header;
748 # add these here.
749 metadata = tuple(metadata) + (
750 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)),
751 )
752
753 # Validate the universe domain.
754 self._client._validate_universe_domain()
755
756 # Send the request.
757 response = await rpc(
758 request,
759 retry=retry,
760 timeout=timeout,
761 metadata=metadata,
762 )
763
764 # Done; return the response.
765 return response
766
767 async def list_topics(
768 self,
769 request: Optional[Union[pubsub.ListTopicsRequest, dict]] = None,
770 *,
771 project: Optional[str] = None,
772 retry: OptionalRetry = gapic_v1.method.DEFAULT,
773 timeout: TimeoutType = gapic_v1.method.DEFAULT,
774 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
775 ) -> pagers.ListTopicsAsyncPager:
776 r"""Lists matching topics.
777
778 .. code-block:: python
779
780 # This snippet has been automatically generated and should be regarded as a
781 # code template only.
782 # It will require modifications to work:
783 # - It may require correct/in-range values for request initialization.
784 # - It may require specifying regional endpoints when creating the service
785 # client as shown in:
786 # https://googleapis.dev/python/google-api-core/latest/client_options.html
787 from google import pubsub_v1
788
789 async def sample_list_topics():
790 # Create a client
791 client = pubsub_v1.PublisherAsyncClient()
792
793 # Initialize request argument(s)
794 request = pubsub_v1.ListTopicsRequest(
795 project="project_value",
796 )
797
798 # Make the request
799 page_result = client.list_topics(request=request)
800
801 # Handle the response
802 async for response in page_result:
803 print(response)
804
805 Args:
806 request (Optional[Union[google.pubsub_v1.types.ListTopicsRequest, dict]]):
807 The request object. Request for the ``ListTopics`` method.
808 project (:class:`str`):
809 Required. The name of the project in which to list
810 topics. Format is ``projects/{project-id}``.
811
812 This corresponds to the ``project`` field
813 on the ``request`` instance; if ``request`` is provided, this
814 should not be set.
815 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
816 should be retried.
817 timeout (TimeoutType):
818 The timeout for this request.
819 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
820 sent along with the request as metadata. Normally, each value must be of type `str`,
821 but for metadata keys ending with the suffix `-bin`, the corresponding values must
822 be of type `bytes`.
823
824 Returns:
825 google.pubsub_v1.services.publisher.pagers.ListTopicsAsyncPager:
826 Response for the ListTopics method.
827
828 Iterating over this object will yield results and
829 resolve additional pages automatically.
830
831 """
832 # Create or coerce a protobuf request object.
833 # - Quick check: If we got a request object, we should *not* have
834 # gotten any keyword arguments that map to the request.
835 flattened_params = [project]
836 has_flattened_params = (
837 len([param for param in flattened_params if param is not None]) > 0
838 )
839 if request is not None and has_flattened_params:
840 raise ValueError(
841 "If the `request` argument is set, then none of "
842 "the individual field arguments should be set."
843 )
844
845 # - Use the request object if provided (there's no risk of modifying the input as
846 # there are no flattened fields), or create one.
847 if not isinstance(request, pubsub.ListTopicsRequest):
848 request = pubsub.ListTopicsRequest(request)
849
850 # If we have keyword arguments corresponding to fields on the
851 # request, apply these.
852 if project is not None:
853 request.project = project
854
855 # Wrap the RPC method; this adds retry and timeout information,
856 # and friendly error handling.
857 rpc = self._client._transport._wrapped_methods[
858 self._client._transport.list_topics
859 ]
860
861 # Certain fields should be provided within the metadata header;
862 # add these here.
863 metadata = tuple(metadata) + (
864 gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)),
865 )
866
867 # Validate the universe domain.
868 self._client._validate_universe_domain()
869
870 # Send the request.
871 response = await rpc(
872 request,
873 retry=retry,
874 timeout=timeout,
875 metadata=metadata,
876 )
877
878 # This method is paged; wrap the response in a pager, which provides
879 # an `__aiter__` convenience method.
880 response = pagers.ListTopicsAsyncPager(
881 method=rpc,
882 request=request,
883 response=response,
884 retry=retry,
885 timeout=timeout,
886 metadata=metadata,
887 )
888
889 # Done; return the response.
890 return response
891
892 async def list_topic_subscriptions(
893 self,
894 request: Optional[Union[pubsub.ListTopicSubscriptionsRequest, dict]] = None,
895 *,
896 topic: Optional[str] = None,
897 retry: OptionalRetry = gapic_v1.method.DEFAULT,
898 timeout: TimeoutType = gapic_v1.method.DEFAULT,
899 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
900 ) -> pagers.ListTopicSubscriptionsAsyncPager:
901 r"""Lists the names of the attached subscriptions on this
902 topic.
903
904 .. code-block:: python
905
906 # This snippet has been automatically generated and should be regarded as a
907 # code template only.
908 # It will require modifications to work:
909 # - It may require correct/in-range values for request initialization.
910 # - It may require specifying regional endpoints when creating the service
911 # client as shown in:
912 # https://googleapis.dev/python/google-api-core/latest/client_options.html
913 from google import pubsub_v1
914
915 async def sample_list_topic_subscriptions():
916 # Create a client
917 client = pubsub_v1.PublisherAsyncClient()
918
919 # Initialize request argument(s)
920 request = pubsub_v1.ListTopicSubscriptionsRequest(
921 topic="topic_value",
922 )
923
924 # Make the request
925 page_result = client.list_topic_subscriptions(request=request)
926
927 # Handle the response
928 async for response in page_result:
929 print(response)
930
931 Args:
932 request (Optional[Union[google.pubsub_v1.types.ListTopicSubscriptionsRequest, dict]]):
933 The request object. Request for the ``ListTopicSubscriptions`` method.
934 topic (:class:`str`):
935 Required. The name of the topic that subscriptions are
936 attached to. Format is
937 ``projects/{project}/topics/{topic}``.
938
939 This corresponds to the ``topic`` field
940 on the ``request`` instance; if ``request`` is provided, this
941 should not be set.
942 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
943 should be retried.
944 timeout (TimeoutType):
945 The timeout for this request.
946 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
947 sent along with the request as metadata. Normally, each value must be of type `str`,
948 but for metadata keys ending with the suffix `-bin`, the corresponding values must
949 be of type `bytes`.
950
951 Returns:
952 google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsAsyncPager:
953 Response for the ListTopicSubscriptions method.
954
955 Iterating over this object will yield results and
956 resolve additional pages automatically.
957
958 """
959 # Create or coerce a protobuf request object.
960 # - Quick check: If we got a request object, we should *not* have
961 # gotten any keyword arguments that map to the request.
962 flattened_params = [topic]
963 has_flattened_params = (
964 len([param for param in flattened_params if param is not None]) > 0
965 )
966 if request is not None and has_flattened_params:
967 raise ValueError(
968 "If the `request` argument is set, then none of "
969 "the individual field arguments should be set."
970 )
971
972 # - Use the request object if provided (there's no risk of modifying the input as
973 # there are no flattened fields), or create one.
974 if not isinstance(request, pubsub.ListTopicSubscriptionsRequest):
975 request = pubsub.ListTopicSubscriptionsRequest(request)
976
977 # If we have keyword arguments corresponding to fields on the
978 # request, apply these.
979 if topic is not None:
980 request.topic = topic
981
982 # Wrap the RPC method; this adds retry and timeout information,
983 # and friendly error handling.
984 rpc = self._client._transport._wrapped_methods[
985 self._client._transport.list_topic_subscriptions
986 ]
987
988 # Certain fields should be provided within the metadata header;
989 # add these here.
990 metadata = tuple(metadata) + (
991 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)),
992 )
993
994 # Validate the universe domain.
995 self._client._validate_universe_domain()
996
997 # Send the request.
998 response = await rpc(
999 request,
1000 retry=retry,
1001 timeout=timeout,
1002 metadata=metadata,
1003 )
1004
1005 # This method is paged; wrap the response in a pager, which provides
1006 # an `__aiter__` convenience method.
1007 response = pagers.ListTopicSubscriptionsAsyncPager(
1008 method=rpc,
1009 request=request,
1010 response=response,
1011 retry=retry,
1012 timeout=timeout,
1013 metadata=metadata,
1014 )
1015
1016 # Done; return the response.
1017 return response
1018
1019 async def list_topic_snapshots(
1020 self,
1021 request: Optional[Union[pubsub.ListTopicSnapshotsRequest, dict]] = None,
1022 *,
1023 topic: Optional[str] = None,
1024 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1025 timeout: TimeoutType = gapic_v1.method.DEFAULT,
1026 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1027 ) -> pagers.ListTopicSnapshotsAsyncPager:
1028 r"""Lists the names of the snapshots on this topic. Snapshots are
1029 used in
1030 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
1031 operations, which allow you to manage message acknowledgments in
1032 bulk. That is, you can set the acknowledgment state of messages
1033 in an existing subscription to the state captured by a snapshot.
1034
1035 .. code-block:: python
1036
1037 # This snippet has been automatically generated and should be regarded as a
1038 # code template only.
1039 # It will require modifications to work:
1040 # - It may require correct/in-range values for request initialization.
1041 # - It may require specifying regional endpoints when creating the service
1042 # client as shown in:
1043 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1044 from google import pubsub_v1
1045
1046 async def sample_list_topic_snapshots():
1047 # Create a client
1048 client = pubsub_v1.PublisherAsyncClient()
1049
1050 # Initialize request argument(s)
1051 request = pubsub_v1.ListTopicSnapshotsRequest(
1052 topic="topic_value",
1053 )
1054
1055 # Make the request
1056 page_result = client.list_topic_snapshots(request=request)
1057
1058 # Handle the response
1059 async for response in page_result:
1060 print(response)
1061
1062 Args:
1063 request (Optional[Union[google.pubsub_v1.types.ListTopicSnapshotsRequest, dict]]):
1064 The request object. Request for the ``ListTopicSnapshots`` method.
1065 topic (:class:`str`):
1066 Required. The name of the topic that snapshots are
1067 attached to. Format is
1068 ``projects/{project}/topics/{topic}``.
1069
1070 This corresponds to the ``topic`` field
1071 on the ``request`` instance; if ``request`` is provided, this
1072 should not be set.
1073 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1074 should be retried.
1075 timeout (TimeoutType):
1076 The timeout for this request.
1077 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1078 sent along with the request as metadata. Normally, each value must be of type `str`,
1079 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1080 be of type `bytes`.
1081
1082 Returns:
1083 google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsAsyncPager:
1084 Response for the ListTopicSnapshots method.
1085
1086 Iterating over this object will yield results and
1087 resolve additional pages automatically.
1088
1089 """
1090 # Create or coerce a protobuf request object.
1091 # - Quick check: If we got a request object, we should *not* have
1092 # gotten any keyword arguments that map to the request.
1093 flattened_params = [topic]
1094 has_flattened_params = (
1095 len([param for param in flattened_params if param is not None]) > 0
1096 )
1097 if request is not None and has_flattened_params:
1098 raise ValueError(
1099 "If the `request` argument is set, then none of "
1100 "the individual field arguments should be set."
1101 )
1102
1103 # - Use the request object if provided (there's no risk of modifying the input as
1104 # there are no flattened fields), or create one.
1105 if not isinstance(request, pubsub.ListTopicSnapshotsRequest):
1106 request = pubsub.ListTopicSnapshotsRequest(request)
1107
1108 # If we have keyword arguments corresponding to fields on the
1109 # request, apply these.
1110 if topic is not None:
1111 request.topic = topic
1112
1113 # Wrap the RPC method; this adds retry and timeout information,
1114 # and friendly error handling.
1115 rpc = self._client._transport._wrapped_methods[
1116 self._client._transport.list_topic_snapshots
1117 ]
1118
1119 # Certain fields should be provided within the metadata header;
1120 # add these here.
1121 metadata = tuple(metadata) + (
1122 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)),
1123 )
1124
1125 # Validate the universe domain.
1126 self._client._validate_universe_domain()
1127
1128 # Send the request.
1129 response = await rpc(
1130 request,
1131 retry=retry,
1132 timeout=timeout,
1133 metadata=metadata,
1134 )
1135
1136 # This method is paged; wrap the response in a pager, which provides
1137 # an `__aiter__` convenience method.
1138 response = pagers.ListTopicSnapshotsAsyncPager(
1139 method=rpc,
1140 request=request,
1141 response=response,
1142 retry=retry,
1143 timeout=timeout,
1144 metadata=metadata,
1145 )
1146
1147 # Done; return the response.
1148 return response
1149
1150 async def delete_topic(
1151 self,
1152 request: Optional[Union[pubsub.DeleteTopicRequest, dict]] = None,
1153 *,
1154 topic: Optional[str] = None,
1155 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1156 timeout: TimeoutType = gapic_v1.method.DEFAULT,
1157 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1158 ) -> None:
1159 r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if
1160 the topic does not exist. After a topic is deleted, a new topic
1161 may be created with the same name; this is an entirely new topic
1162 with none of the old configuration or subscriptions. Existing
1163 subscriptions to this topic are not deleted, but their ``topic``
1164 field is set to ``_deleted-topic_``.
1165
1166 .. code-block:: python
1167
1168 # This snippet has been automatically generated and should be regarded as a
1169 # code template only.
1170 # It will require modifications to work:
1171 # - It may require correct/in-range values for request initialization.
1172 # - It may require specifying regional endpoints when creating the service
1173 # client as shown in:
1174 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1175 from google import pubsub_v1
1176
1177 async def sample_delete_topic():
1178 # Create a client
1179 client = pubsub_v1.PublisherAsyncClient()
1180
1181 # Initialize request argument(s)
1182 request = pubsub_v1.DeleteTopicRequest(
1183 topic="topic_value",
1184 )
1185
1186 # Make the request
1187 await client.delete_topic(request=request)
1188
1189 Args:
1190 request (Optional[Union[google.pubsub_v1.types.DeleteTopicRequest, dict]]):
1191 The request object. Request for the ``DeleteTopic`` method.
1192 topic (:class:`str`):
1193 Required. Name of the topic to delete. Format is
1194 ``projects/{project}/topics/{topic}``.
1195
1196 This corresponds to the ``topic`` field
1197 on the ``request`` instance; if ``request`` is provided, this
1198 should not be set.
1199 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1200 should be retried.
1201 timeout (TimeoutType):
1202 The timeout for this request.
1203 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1204 sent along with the request as metadata. Normally, each value must be of type `str`,
1205 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1206 be of type `bytes`.
1207 """
1208 # Create or coerce a protobuf request object.
1209 # - Quick check: If we got a request object, we should *not* have
1210 # gotten any keyword arguments that map to the request.
1211 flattened_params = [topic]
1212 has_flattened_params = (
1213 len([param for param in flattened_params if param is not None]) > 0
1214 )
1215 if request is not None and has_flattened_params:
1216 raise ValueError(
1217 "If the `request` argument is set, then none of "
1218 "the individual field arguments should be set."
1219 )
1220
1221 # - Use the request object if provided (there's no risk of modifying the input as
1222 # there are no flattened fields), or create one.
1223 if not isinstance(request, pubsub.DeleteTopicRequest):
1224 request = pubsub.DeleteTopicRequest(request)
1225
1226 # If we have keyword arguments corresponding to fields on the
1227 # request, apply these.
1228 if topic is not None:
1229 request.topic = topic
1230
1231 # Wrap the RPC method; this adds retry and timeout information,
1232 # and friendly error handling.
1233 rpc = self._client._transport._wrapped_methods[
1234 self._client._transport.delete_topic
1235 ]
1236
1237 # Certain fields should be provided within the metadata header;
1238 # add these here.
1239 metadata = tuple(metadata) + (
1240 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)),
1241 )
1242
1243 # Validate the universe domain.
1244 self._client._validate_universe_domain()
1245
1246 # Send the request.
1247 await rpc(
1248 request,
1249 retry=retry,
1250 timeout=timeout,
1251 metadata=metadata,
1252 )
1253
1254 async def detach_subscription(
1255 self,
1256 request: Optional[Union[pubsub.DetachSubscriptionRequest, dict]] = None,
1257 *,
1258 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1259 timeout: TimeoutType = gapic_v1.method.DEFAULT,
1260 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1261 ) -> pubsub.DetachSubscriptionResponse:
1262 r"""Detaches a subscription from this topic. All messages retained
1263 in the subscription are dropped. Subsequent ``Pull`` and
1264 ``StreamingPull`` requests will return FAILED_PRECONDITION. If
1265 the subscription is a push subscription, pushes to the endpoint
1266 will stop.
1267
1268 .. code-block:: python
1269
1270 # This snippet has been automatically generated and should be regarded as a
1271 # code template only.
1272 # It will require modifications to work:
1273 # - It may require correct/in-range values for request initialization.
1274 # - It may require specifying regional endpoints when creating the service
1275 # client as shown in:
1276 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1277 from google import pubsub_v1
1278
1279 async def sample_detach_subscription():
1280 # Create a client
1281 client = pubsub_v1.PublisherAsyncClient()
1282
1283 # Initialize request argument(s)
1284 request = pubsub_v1.DetachSubscriptionRequest(
1285 subscription="subscription_value",
1286 )
1287
1288 # Make the request
1289 response = await client.detach_subscription(request=request)
1290
1291 # Handle the response
1292 print(response)
1293
1294 Args:
1295 request (Optional[Union[google.pubsub_v1.types.DetachSubscriptionRequest, dict]]):
1296 The request object. Request for the DetachSubscription
1297 method.
1298 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1299 should be retried.
1300 timeout (TimeoutType):
1301 The timeout for this request.
1302 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1303 sent along with the request as metadata. Normally, each value must be of type `str`,
1304 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1305 be of type `bytes`.
1306
1307 Returns:
1308 google.pubsub_v1.types.DetachSubscriptionResponse:
1309 Response for the DetachSubscription
1310 method. Reserved for future use.
1311
1312 """
1313 # Create or coerce a protobuf request object.
1314 # - Use the request object if provided (there's no risk of modifying the input as
1315 # there are no flattened fields), or create one.
1316 if not isinstance(request, pubsub.DetachSubscriptionRequest):
1317 request = pubsub.DetachSubscriptionRequest(request)
1318
1319 # Wrap the RPC method; this adds retry and timeout information,
1320 # and friendly error handling.
1321 rpc = self._client._transport._wrapped_methods[
1322 self._client._transport.detach_subscription
1323 ]
1324
1325 # Certain fields should be provided within the metadata header;
1326 # add these here.
1327 metadata = tuple(metadata) + (
1328 gapic_v1.routing_header.to_grpc_metadata(
1329 (("subscription", request.subscription),)
1330 ),
1331 )
1332
1333 # Validate the universe domain.
1334 self._client._validate_universe_domain()
1335
1336 # Send the request.
1337 response = await rpc(
1338 request,
1339 retry=retry,
1340 timeout=timeout,
1341 metadata=metadata,
1342 )
1343
1344 # Done; return the response.
1345 return response
1346
1347 async def set_iam_policy(
1348 self,
1349 request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None,
1350 *,
1351 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1352 timeout: TimeoutType = gapic_v1.method.DEFAULT,
1353 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1354 ) -> policy_pb2.Policy:
1355 r"""Sets the IAM access control policy on the specified function.
1356
1357 Replaces any existing policy.
1358
1359 Args:
1360 request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`):
1361 The request object. Request message for `SetIamPolicy`
1362 method.
1363 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if any,
1364 should be retried.
1365 timeout (TimeoutType):
1366 The timeout for this request.
1367 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1368 sent along with the request as metadata. Normally, each value must be of type `str`,
1369 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1370 be of type `bytes`.
1371 Returns:
1372 ~.policy_pb2.Policy:
1373 Defines an Identity and Access Management (IAM) policy.
1374 It is used to specify access control policies for Cloud
1375 Platform resources.
1376 A ``Policy`` is a collection of ``bindings``. A
1377 ``binding`` binds one or more ``members`` to a single
1378 ``role``. Members can be user accounts, service
1379 accounts, Google groups, and domains (such as G Suite).
1380 A ``role`` is a named list of permissions (defined by
1381 IAM or configured by users). A ``binding`` can
1382 optionally specify a ``condition``, which is a logic
1383 expression that further constrains the role binding
1384 based on attributes about the request and/or target
1385 resource.
1386
1387 **JSON Example**
1388
1389 ::
1390
1391 {
1392 "bindings": [
1393 {
1394 "role": "roles/resourcemanager.organizationAdmin",
1395 "members": [
1396 "user:mike@example.com",
1397 "group:admins@example.com",
1398 "domain:google.com",
1399 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
1400 ]
1401 },
1402 {
1403 "role": "roles/resourcemanager.organizationViewer",
1404 "members": ["user:eve@example.com"],
1405 "condition": {
1406 "title": "expirable access",
1407 "description": "Does not grant access after Sep 2020",
1408 "expression": "request.time <
1409 timestamp('2020-10-01T00:00:00.000Z')",
1410 }
1411 }
1412 ]
1413 }
1414
1415 **YAML Example**
1416
1417 ::
1418
1419 bindings:
1420 - members:
1421 - user:mike@example.com
1422 - group:admins@example.com
1423 - domain:google.com
1424 - serviceAccount:my-project-id@appspot.gserviceaccount.com
1425 role: roles/resourcemanager.organizationAdmin
1426 - members:
1427 - user:eve@example.com
1428 role: roles/resourcemanager.organizationViewer
1429 condition:
1430 title: expirable access
1431 description: Does not grant access after Sep 2020
1432 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
1433
1434 For a description of IAM and its features, see the `IAM
1435 developer's
1436 guide <https://cloud.google.com/iam/docs>`__.
1437 """
1438 # Create or coerce a protobuf request object.
1439
1440 # The request isn't a proto-plus wrapped type,
1441 # so it must be constructed via keyword expansion.
1442 if isinstance(request, dict):
1443 request = iam_policy_pb2.SetIamPolicyRequest(**request)
1444
1445 # Wrap the RPC method; this adds retry and timeout information,
1446 # and friendly error handling.
1447 rpc = self.transport._wrapped_methods[self._client._transport.set_iam_policy]
1448
1449 # Certain fields should be provided within the metadata header;
1450 # add these here.
1451 metadata = tuple(metadata) + (
1452 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1453 )
1454
1455 # Validate the universe domain.
1456 self._client._validate_universe_domain()
1457
1458 # Send the request.
1459 response = await rpc(
1460 request,
1461 retry=retry,
1462 timeout=timeout,
1463 metadata=metadata,
1464 )
1465
1466 # Done; return the response.
1467 return response
1468
1469 async def get_iam_policy(
1470 self,
1471 request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None,
1472 *,
1473 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1474 timeout: TimeoutType = gapic_v1.method.DEFAULT,
1475 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1476 ) -> policy_pb2.Policy:
1477 r"""Gets the IAM access control policy for a function.
1478
1479 Returns an empty policy if the function exists and does not have a
1480 policy set.
1481
1482 Args:
1483 request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`):
1484 The request object. Request message for `GetIamPolicy`
1485 method.
1486 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors, if
1487 any, should be retried.
1488 timeout (TimeoutType):
1489 The timeout for this request.
1490 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1491 sent along with the request as metadata. Normally, each value must be of type `str`,
1492 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1493 be of type `bytes`.
1494 Returns:
1495 ~.policy_pb2.Policy:
1496 Defines an Identity and Access Management (IAM) policy.
1497 It is used to specify access control policies for Cloud
1498 Platform resources.
1499 A ``Policy`` is a collection of ``bindings``. A
1500 ``binding`` binds one or more ``members`` to a single
1501 ``role``. Members can be user accounts, service
1502 accounts, Google groups, and domains (such as G Suite).
1503 A ``role`` is a named list of permissions (defined by
1504 IAM or configured by users). A ``binding`` can
1505 optionally specify a ``condition``, which is a logic
1506 expression that further constrains the role binding
1507 based on attributes about the request and/or target
1508 resource.
1509
1510 **JSON Example**
1511
1512 ::
1513
1514 {
1515 "bindings": [
1516 {
1517 "role": "roles/resourcemanager.organizationAdmin",
1518 "members": [
1519 "user:mike@example.com",
1520 "group:admins@example.com",
1521 "domain:google.com",
1522 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
1523 ]
1524 },
1525 {
1526 "role": "roles/resourcemanager.organizationViewer",
1527 "members": ["user:eve@example.com"],
1528 "condition": {
1529 "title": "expirable access",
1530 "description": "Does not grant access after Sep 2020",
1531 "expression": "request.time <
1532 timestamp('2020-10-01T00:00:00.000Z')",
1533 }
1534 }
1535 ]
1536 }
1537
1538 **YAML Example**
1539
1540 ::
1541
1542 bindings:
1543 - members:
1544 - user:mike@example.com
1545 - group:admins@example.com
1546 - domain:google.com
1547 - serviceAccount:my-project-id@appspot.gserviceaccount.com
1548 role: roles/resourcemanager.organizationAdmin
1549 - members:
1550 - user:eve@example.com
1551 role: roles/resourcemanager.organizationViewer
1552 condition:
1553 title: expirable access
1554 description: Does not grant access after Sep 2020
1555 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
1556
1557 For a description of IAM and its features, see the `IAM
1558 developer's
1559 guide <https://cloud.google.com/iam/docs>`__.
1560 """
1561 # Create or coerce a protobuf request object.
1562
1563 # The request isn't a proto-plus wrapped type,
1564 # so it must be constructed via keyword expansion.
1565 if isinstance(request, dict):
1566 request = iam_policy_pb2.GetIamPolicyRequest(**request)
1567
1568 # Wrap the RPC method; this adds retry and timeout information,
1569 # and friendly error handling.
1570 rpc = self.transport._wrapped_methods[self._client._transport.get_iam_policy]
1571
1572 # Certain fields should be provided within the metadata header;
1573 # add these here.
1574 metadata = tuple(metadata) + (
1575 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1576 )
1577
1578 # Validate the universe domain.
1579 self._client._validate_universe_domain()
1580
1581 # Send the request.
1582 response = await rpc(
1583 request,
1584 retry=retry,
1585 timeout=timeout,
1586 metadata=metadata,
1587 )
1588
1589 # Done; return the response.
1590 return response
1591
1592 async def test_iam_permissions(
1593 self,
1594 request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None,
1595 *,
1596 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1597 timeout: TimeoutType = gapic_v1.method.DEFAULT,
1598 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1599 ) -> iam_policy_pb2.TestIamPermissionsResponse:
1600 r"""Tests the specified IAM permissions against the IAM access control
1601 policy for a function.
1602
1603 If the function does not exist, this will return an empty set
1604 of permissions, not a NOT_FOUND error.
1605
1606 Args:
1607 request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`):
1608 The request object. Request message for
1609 `TestIamPermissions` method.
1610 retry (google.api_core.retry_async.AsyncRetry): Designation of what errors,
1611 if any, should be retried.
1612 timeout (TimeoutType):
1613 The timeout for this request.
1614 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1615 sent along with the request as metadata. Normally, each value must be of type `str`,
1616 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1617 be of type `bytes`.
1618 Returns:
1619 ~.iam_policy_pb2.TestIamPermissionsResponse:
1620 Response message for ``TestIamPermissions`` method.
1621 """
1622 # Create or coerce a protobuf request object.
1623
1624 # The request isn't a proto-plus wrapped type,
1625 # so it must be constructed via keyword expansion.
1626 if isinstance(request, dict):
1627 request = iam_policy_pb2.TestIamPermissionsRequest(**request)
1628
1629 # Wrap the RPC method; this adds retry and timeout information,
1630 # and friendly error handling.
1631 rpc = self.transport._wrapped_methods[
1632 self._client._transport.test_iam_permissions
1633 ]
1634
1635 # Certain fields should be provided within the metadata header;
1636 # add these here.
1637 metadata = tuple(metadata) + (
1638 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1639 )
1640
1641 # Validate the universe domain.
1642 self._client._validate_universe_domain()
1643
1644 # Send the request.
1645 response = await rpc(
1646 request,
1647 retry=retry,
1648 timeout=timeout,
1649 metadata=metadata,
1650 )
1651
1652 # Done; return the response.
1653 return response
1654
1655 async def __aenter__(self) -> "PublisherAsyncClient":
1656 return self
1657
1658 async def __aexit__(self, exc_type, exc, tb):
1659 await self.transport.close()
1660
1661
1662DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
1663 client_library_version=package_version.__version__
1664)
1665
1666if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER
1667 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
1668
1669
1670__all__ = ("PublisherAsyncClient",)