Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/pubsub_v1/services/subscriber/async_client.py: 28%
274 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:03 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-07 06:03 +0000
1# -*- coding: utf-8 -*-
2# Copyright 2022 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#
16from collections import OrderedDict
17import functools
18import re
19from typing import (
20 Dict,
21 Mapping,
22 MutableMapping,
23 MutableSequence,
24 Optional,
25 AsyncIterable,
26 Awaitable,
27 AsyncIterator,
28 Sequence,
29 Tuple,
30 Type,
31 Union,
32)
34import warnings
35from google.pubsub_v1 import gapic_version as package_version
37from google.api_core.client_options import ClientOptions
38from google.api_core import exceptions as core_exceptions
39from google.api_core import gapic_v1
40from google.api_core import retry as retries
41from google.auth import credentials as ga_credentials # type: ignore
42from google.oauth2 import service_account # type: ignore
44try:
45 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
46except AttributeError: # pragma: NO COVER
47 OptionalRetry = Union[retries.Retry, object] # type: ignore
49from google.iam.v1 import iam_policy_pb2 # type: ignore
50from google.iam.v1 import policy_pb2 # type: ignore
51from google.protobuf import duration_pb2 # type: ignore
52from google.protobuf import field_mask_pb2 # type: ignore
53from google.protobuf import timestamp_pb2 # type: ignore
54from google.pubsub_v1.services.subscriber import pagers
55from google.pubsub_v1.types import pubsub
56from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO
57from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport
58from .client import SubscriberClient
61class SubscriberAsyncClient:
62 """The service that an application uses to manipulate subscriptions and
63 to consume messages from a subscription via the ``Pull`` method or
64 by establishing a bi-directional stream using the ``StreamingPull``
65 method.
66 """
68 _client: SubscriberClient
70 DEFAULT_ENDPOINT = SubscriberClient.DEFAULT_ENDPOINT
71 DEFAULT_MTLS_ENDPOINT = SubscriberClient.DEFAULT_MTLS_ENDPOINT
73 snapshot_path = staticmethod(SubscriberClient.snapshot_path)
74 parse_snapshot_path = staticmethod(SubscriberClient.parse_snapshot_path)
75 subscription_path = staticmethod(SubscriberClient.subscription_path)
76 parse_subscription_path = staticmethod(SubscriberClient.parse_subscription_path)
77 topic_path = staticmethod(SubscriberClient.topic_path)
78 parse_topic_path = staticmethod(SubscriberClient.parse_topic_path)
79 common_billing_account_path = staticmethod(
80 SubscriberClient.common_billing_account_path
81 )
82 parse_common_billing_account_path = staticmethod(
83 SubscriberClient.parse_common_billing_account_path
84 )
85 common_folder_path = staticmethod(SubscriberClient.common_folder_path)
86 parse_common_folder_path = staticmethod(SubscriberClient.parse_common_folder_path)
87 common_organization_path = staticmethod(SubscriberClient.common_organization_path)
88 parse_common_organization_path = staticmethod(
89 SubscriberClient.parse_common_organization_path
90 )
91 common_project_path = staticmethod(SubscriberClient.common_project_path)
92 parse_common_project_path = staticmethod(SubscriberClient.parse_common_project_path)
93 common_location_path = staticmethod(SubscriberClient.common_location_path)
94 parse_common_location_path = staticmethod(
95 SubscriberClient.parse_common_location_path
96 )
98 @classmethod
99 def from_service_account_info(cls, info: dict, *args, **kwargs):
100 """Creates an instance of this client using the provided credentials
101 info.
103 Args:
104 info (dict): The service account private key info.
105 args: Additional arguments to pass to the constructor.
106 kwargs: Additional arguments to pass to the constructor.
108 Returns:
109 SubscriberAsyncClient: The constructed client.
110 """
111 return SubscriberClient.from_service_account_info.__func__(SubscriberAsyncClient, info, *args, **kwargs) # type: ignore
113 @classmethod
114 def from_service_account_file(cls, filename: str, *args, **kwargs):
115 """Creates an instance of this client using the provided credentials
116 file.
118 Args:
119 filename (str): The path to the service account private key json
120 file.
121 args: Additional arguments to pass to the constructor.
122 kwargs: Additional arguments to pass to the constructor.
124 Returns:
125 SubscriberAsyncClient: The constructed client.
126 """
127 return SubscriberClient.from_service_account_file.__func__(SubscriberAsyncClient, filename, *args, **kwargs) # type: ignore
129 from_service_account_json = from_service_account_file
131 @classmethod
132 def get_mtls_endpoint_and_cert_source(
133 cls, client_options: Optional[ClientOptions] = None
134 ):
135 """Return the API endpoint and client cert source for mutual TLS.
137 The client cert source is determined in the following order:
138 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
139 client cert source is None.
140 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
141 default client cert source exists, use the default one; otherwise the client cert
142 source is None.
144 The API endpoint is determined in the following order:
145 (1) if `client_options.api_endpoint` if provided, use the provided one.
146 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
147 default mTLS endpoint; if the environment variable is "never", use the default API
148 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
149 use the default API endpoint.
151 More details can be found at https://google.aip.dev/auth/4114.
153 Args:
154 client_options (google.api_core.client_options.ClientOptions): Custom options for the
155 client. Only the `api_endpoint` and `client_cert_source` properties may be used
156 in this method.
158 Returns:
159 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
160 client cert source to use.
162 Raises:
163 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
164 """
165 return SubscriberClient.get_mtls_endpoint_and_cert_source(client_options) # type: ignore
167 @property
168 def transport(self) -> SubscriberTransport:
169 """Returns the transport used by the client instance.
171 Returns:
172 SubscriberTransport: The transport used by the client instance.
173 """
174 return self._client.transport
176 get_transport_class = functools.partial(
177 type(SubscriberClient).get_transport_class, type(SubscriberClient)
178 )
180 def __init__(
181 self,
182 *,
183 credentials: Optional[ga_credentials.Credentials] = None,
184 transport: Union[str, SubscriberTransport] = "grpc_asyncio",
185 client_options: Optional[ClientOptions] = None,
186 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
187 ) -> None:
188 """Instantiates the subscriber client.
190 Args:
191 credentials (Optional[google.auth.credentials.Credentials]): The
192 authorization credentials to attach to requests. These
193 credentials identify the application to the service; if none
194 are specified, the client will attempt to ascertain the
195 credentials from the environment.
196 transport (Union[str, ~.SubscriberTransport]): The
197 transport to use. If set to None, a transport is chosen
198 automatically.
199 client_options (ClientOptions): Custom options for the client. It
200 won't take effect if a ``transport`` instance is provided.
201 (1) The ``api_endpoint`` property can be used to override the
202 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
203 environment variable can also be used to override the endpoint:
204 "always" (always use the default mTLS endpoint), "never" (always
205 use the default regular endpoint) and "auto" (auto switch to the
206 default mTLS endpoint if client certificate is present, this is
207 the default value). However, the ``api_endpoint`` property takes
208 precedence if provided.
209 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
210 is "true", then the ``client_cert_source`` property can be used
211 to provide client certificate for mutual TLS transport. If
212 not provided, the default SSL client certificate will be used if
213 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
214 set, no client certificate will be used.
216 Raises:
217 google.auth.exceptions.MutualTlsChannelError: If mutual TLS transport
218 creation failed for any reason.
219 """
220 self._client = SubscriberClient(
221 credentials=credentials,
222 transport=transport,
223 client_options=client_options,
224 client_info=client_info,
225 )
227 async def create_subscription(
228 self,
229 request: Optional[Union[pubsub.Subscription, dict]] = None,
230 *,
231 name: Optional[str] = None,
232 topic: Optional[str] = None,
233 push_config: Optional[pubsub.PushConfig] = None,
234 ack_deadline_seconds: Optional[int] = None,
235 retry: OptionalRetry = gapic_v1.method.DEFAULT,
236 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
237 metadata: Sequence[Tuple[str, str]] = (),
238 ) -> pubsub.Subscription:
239 r"""Creates a subscription to a given topic. See the [resource name
240 rules]
241 (https://cloud.google.com/pubsub/docs/admin#resource_names). If
242 the subscription already exists, returns ``ALREADY_EXISTS``. If
243 the corresponding topic doesn't exist, returns ``NOT_FOUND``.
245 If the name is not provided in the request, the server will
246 assign a random name for this subscription on the same project
247 as the topic, conforming to the [resource name format]
248 (https://cloud.google.com/pubsub/docs/admin#resource_names). The
249 generated name is populated in the returned Subscription object.
250 Note that for REST API requests, you must specify a name in the
251 request.
253 .. code-block:: python
255 # This snippet has been automatically generated and should be regarded as a
256 # code template only.
257 # It will require modifications to work:
258 # - It may require correct/in-range values for request initialization.
259 # - It may require specifying regional endpoints when creating the service
260 # client as shown in:
261 # https://googleapis.dev/python/google-api-core/latest/client_options.html
262 from google import pubsub_v1
264 async def sample_create_subscription():
265 # Create a client
266 client = pubsub_v1.SubscriberAsyncClient()
268 # Initialize request argument(s)
269 request = pubsub_v1.Subscription(
270 name="name_value",
271 topic="topic_value",
272 )
274 # Make the request
275 response = await client.create_subscription(request=request)
277 # Handle the response
278 print(response)
280 Args:
281 request (Optional[Union[google.pubsub_v1.types.Subscription, dict]]):
282 The request object. A subscription resource. If none of ``push_config``,
283 ``bigquery_config``, or ``cloud_storage_config`` is set,
284 then the subscriber will pull and ack messages using API
285 methods. At most one of these fields may be set.
286 name (:class:`str`):
287 Required. The name of the subscription. It must have the
288 format
289 ``"projects/{project}/subscriptions/{subscription}"``.
290 ``{subscription}`` must start with a letter, and contain
291 only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes
292 (``-``), underscores (``_``), periods (``.``), tildes
293 (``~``), plus (``+``) or percent signs (``%``). It must
294 be between 3 and 255 characters in length, and it must
295 not start with ``"goog"``.
297 This corresponds to the ``name`` field
298 on the ``request`` instance; if ``request`` is provided, this
299 should not be set.
300 topic (:class:`str`):
301 Required. The name of the topic from which this
302 subscription is receiving messages. Format is
303 ``projects/{project}/topics/{topic}``. The value of this
304 field will be ``_deleted-topic_`` if the topic has been
305 deleted.
307 This corresponds to the ``topic`` field
308 on the ``request`` instance; if ``request`` is provided, this
309 should not be set.
310 push_config (:class:`google.pubsub_v1.types.PushConfig`):
311 If push delivery is used with this
312 subscription, this field is used to
313 configure it.
315 This corresponds to the ``push_config`` field
316 on the ``request`` instance; if ``request`` is provided, this
317 should not be set.
318 ack_deadline_seconds (:class:`int`):
319 The approximate amount of time (on a best-effort basis)
320 Pub/Sub waits for the subscriber to acknowledge receipt
321 before resending the message. In the interval after the
322 message is delivered and before it is acknowledged, it
323 is considered to be *outstanding*. During that time
324 period, the message will not be redelivered (on a
325 best-effort basis).
327 For pull subscriptions, this value is used as the
328 initial value for the ack deadline. To override this
329 value for a given message, call ``ModifyAckDeadline``
330 with the corresponding ``ack_id`` if using non-streaming
331 pull or send the ``ack_id`` in a
332 ``StreamingModifyAckDeadlineRequest`` if using streaming
333 pull. The minimum custom deadline you can specify is 10
334 seconds. The maximum custom deadline you can specify is
335 600 seconds (10 minutes). If this parameter is 0, a
336 default value of 10 seconds is used.
338 For push delivery, this value is also used to set the
339 request timeout for the call to the push endpoint.
341 If the subscriber never acknowledges the message, the
342 Pub/Sub system will eventually redeliver the message.
344 This corresponds to the ``ack_deadline_seconds`` field
345 on the ``request`` instance; if ``request`` is provided, this
346 should not be set.
347 retry (google.api_core.retry.Retry): Designation of what errors, if any,
348 should be retried.
349 timeout (float): The timeout for this request.
350 metadata (Sequence[Tuple[str, str]]): Strings which should be
351 sent along with the request as metadata.
353 Returns:
354 google.pubsub_v1.types.Subscription:
355 A subscription resource. If none of push_config, bigquery_config, or
356 cloud_storage_config is set, then the subscriber will
357 pull and ack messages using API methods. At most one
358 of these fields may be set.
360 """
361 # Create or coerce a protobuf request object.
362 # Quick check: If we got a request object, we should *not* have
363 # gotten any keyword arguments that map to the request.
364 has_flattened_params = any([name, topic, push_config, ack_deadline_seconds])
365 if request is not None and has_flattened_params:
366 raise ValueError(
367 "If the `request` argument is set, then none of "
368 "the individual field arguments should be set."
369 )
371 request = pubsub.Subscription(request)
373 # If we have keyword arguments corresponding to fields on the
374 # request, apply these.
375 if name is not None:
376 request.name = name
377 if topic is not None:
378 request.topic = topic
379 if push_config is not None:
380 request.push_config = push_config
381 if ack_deadline_seconds is not None:
382 request.ack_deadline_seconds = ack_deadline_seconds
384 # Wrap the RPC method; this adds retry and timeout information,
385 # and friendly error handling.
386 rpc = gapic_v1.method_async.wrap_method(
387 self._client._transport.create_subscription,
388 default_retry=retries.Retry(
389 initial=0.1,
390 maximum=60.0,
391 multiplier=1.3,
392 predicate=retries.if_exception_type(
393 core_exceptions.Aborted,
394 core_exceptions.ServiceUnavailable,
395 core_exceptions.Unknown,
396 ),
397 deadline=60.0,
398 ),
399 default_timeout=60.0,
400 client_info=DEFAULT_CLIENT_INFO,
401 )
403 # Certain fields should be provided within the metadata header;
404 # add these here.
405 metadata = tuple(metadata) + (
406 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
407 )
409 # Send the request.
410 response = await rpc(
411 request,
412 retry=retry,
413 timeout=timeout,
414 metadata=metadata,
415 )
417 # Done; return the response.
418 return response
420 async def get_subscription(
421 self,
422 request: Optional[Union[pubsub.GetSubscriptionRequest, dict]] = None,
423 *,
424 subscription: Optional[str] = None,
425 retry: OptionalRetry = gapic_v1.method.DEFAULT,
426 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
427 metadata: Sequence[Tuple[str, str]] = (),
428 ) -> pubsub.Subscription:
429 r"""Gets the configuration details of a subscription.
431 .. code-block:: python
433 # This snippet has been automatically generated and should be regarded as a
434 # code template only.
435 # It will require modifications to work:
436 # - It may require correct/in-range values for request initialization.
437 # - It may require specifying regional endpoints when creating the service
438 # client as shown in:
439 # https://googleapis.dev/python/google-api-core/latest/client_options.html
440 from google import pubsub_v1
442 async def sample_get_subscription():
443 # Create a client
444 client = pubsub_v1.SubscriberAsyncClient()
446 # Initialize request argument(s)
447 request = pubsub_v1.GetSubscriptionRequest(
448 subscription="subscription_value",
449 )
451 # Make the request
452 response = await client.get_subscription(request=request)
454 # Handle the response
455 print(response)
457 Args:
458 request (Optional[Union[google.pubsub_v1.types.GetSubscriptionRequest, dict]]):
459 The request object. Request for the GetSubscription
460 method.
461 subscription (:class:`str`):
462 Required. The name of the subscription to get. Format is
463 ``projects/{project}/subscriptions/{sub}``.
465 This corresponds to the ``subscription`` field
466 on the ``request`` instance; if ``request`` is provided, this
467 should not be set.
468 retry (google.api_core.retry.Retry): Designation of what errors, if any,
469 should be retried.
470 timeout (float): The timeout for this request.
471 metadata (Sequence[Tuple[str, str]]): Strings which should be
472 sent along with the request as metadata.
474 Returns:
475 google.pubsub_v1.types.Subscription:
476 A subscription resource. If none of push_config, bigquery_config, or
477 cloud_storage_config is set, then the subscriber will
478 pull and ack messages using API methods. At most one
479 of these fields may be set.
481 """
482 # Create or coerce a protobuf request object.
483 # Quick check: If we got a request object, we should *not* have
484 # gotten any keyword arguments that map to the request.
485 has_flattened_params = any([subscription])
486 if request is not None and has_flattened_params:
487 raise ValueError(
488 "If the `request` argument is set, then none of "
489 "the individual field arguments should be set."
490 )
492 request = pubsub.GetSubscriptionRequest(request)
494 # If we have keyword arguments corresponding to fields on the
495 # request, apply these.
496 if subscription is not None:
497 request.subscription = subscription
499 # Wrap the RPC method; this adds retry and timeout information,
500 # and friendly error handling.
501 rpc = gapic_v1.method_async.wrap_method(
502 self._client._transport.get_subscription,
503 default_retry=retries.Retry(
504 initial=0.1,
505 maximum=60.0,
506 multiplier=1.3,
507 predicate=retries.if_exception_type(
508 core_exceptions.Aborted,
509 core_exceptions.ServiceUnavailable,
510 core_exceptions.Unknown,
511 ),
512 deadline=60.0,
513 ),
514 default_timeout=60.0,
515 client_info=DEFAULT_CLIENT_INFO,
516 )
518 # Certain fields should be provided within the metadata header;
519 # add these here.
520 metadata = tuple(metadata) + (
521 gapic_v1.routing_header.to_grpc_metadata(
522 (("subscription", request.subscription),)
523 ),
524 )
526 # Send the request.
527 response = await rpc(
528 request,
529 retry=retry,
530 timeout=timeout,
531 metadata=metadata,
532 )
534 # Done; return the response.
535 return response
537 async def update_subscription(
538 self,
539 request: Optional[Union[pubsub.UpdateSubscriptionRequest, dict]] = None,
540 *,
541 subscription: Optional[pubsub.Subscription] = None,
542 update_mask: Optional[field_mask_pb2.FieldMask] = None,
543 retry: OptionalRetry = gapic_v1.method.DEFAULT,
544 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
545 metadata: Sequence[Tuple[str, str]] = (),
546 ) -> pubsub.Subscription:
547 r"""Updates an existing subscription. Note that certain
548 properties of a subscription, such as its topic, are not
549 modifiable.
551 .. code-block:: python
553 # This snippet has been automatically generated and should be regarded as a
554 # code template only.
555 # It will require modifications to work:
556 # - It may require correct/in-range values for request initialization.
557 # - It may require specifying regional endpoints when creating the service
558 # client as shown in:
559 # https://googleapis.dev/python/google-api-core/latest/client_options.html
560 from google import pubsub_v1
562 async def sample_update_subscription():
563 # Create a client
564 client = pubsub_v1.SubscriberAsyncClient()
566 # Initialize request argument(s)
567 subscription = pubsub_v1.Subscription()
568 subscription.name = "name_value"
569 subscription.topic = "topic_value"
571 request = pubsub_v1.UpdateSubscriptionRequest(
572 subscription=subscription,
573 )
575 # Make the request
576 response = await client.update_subscription(request=request)
578 # Handle the response
579 print(response)
581 Args:
582 request (Optional[Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]]):
583 The request object. Request for the UpdateSubscription
584 method.
585 subscription (:class:`google.pubsub_v1.types.Subscription`):
586 Required. The updated subscription
587 object.
589 This corresponds to the ``subscription`` field
590 on the ``request`` instance; if ``request`` is provided, this
591 should not be set.
592 update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
593 Required. Indicates which fields in
594 the provided subscription to update.
595 Must be specified and non-empty.
597 This corresponds to the ``update_mask`` field
598 on the ``request`` instance; if ``request`` is provided, this
599 should not be set.
600 retry (google.api_core.retry.Retry): Designation of what errors, if any,
601 should be retried.
602 timeout (float): The timeout for this request.
603 metadata (Sequence[Tuple[str, str]]): Strings which should be
604 sent along with the request as metadata.
606 Returns:
607 google.pubsub_v1.types.Subscription:
608 A subscription resource. If none of push_config, bigquery_config, or
609 cloud_storage_config is set, then the subscriber will
610 pull and ack messages using API methods. At most one
611 of these fields may be set.
613 """
614 # Create or coerce a protobuf request object.
615 # Quick check: If we got a request object, we should *not* have
616 # gotten any keyword arguments that map to the request.
617 has_flattened_params = any([subscription, update_mask])
618 if request is not None and has_flattened_params:
619 raise ValueError(
620 "If the `request` argument is set, then none of "
621 "the individual field arguments should be set."
622 )
624 request = pubsub.UpdateSubscriptionRequest(request)
626 # If we have keyword arguments corresponding to fields on the
627 # request, apply these.
628 if subscription is not None:
629 request.subscription = subscription
630 if update_mask is not None:
631 request.update_mask = update_mask
633 # Wrap the RPC method; this adds retry and timeout information,
634 # and friendly error handling.
635 rpc = gapic_v1.method_async.wrap_method(
636 self._client._transport.update_subscription,
637 default_retry=retries.Retry(
638 initial=0.1,
639 maximum=60.0,
640 multiplier=1.3,
641 predicate=retries.if_exception_type(
642 core_exceptions.ServiceUnavailable,
643 ),
644 deadline=60.0,
645 ),
646 default_timeout=60.0,
647 client_info=DEFAULT_CLIENT_INFO,
648 )
650 # Certain fields should be provided within the metadata header;
651 # add these here.
652 metadata = tuple(metadata) + (
653 gapic_v1.routing_header.to_grpc_metadata(
654 (("subscription.name", request.subscription.name),)
655 ),
656 )
658 # Send the request.
659 response = await rpc(
660 request,
661 retry=retry,
662 timeout=timeout,
663 metadata=metadata,
664 )
666 # Done; return the response.
667 return response
669 async def list_subscriptions(
670 self,
671 request: Optional[Union[pubsub.ListSubscriptionsRequest, dict]] = None,
672 *,
673 project: Optional[str] = None,
674 retry: OptionalRetry = gapic_v1.method.DEFAULT,
675 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
676 metadata: Sequence[Tuple[str, str]] = (),
677 ) -> pagers.ListSubscriptionsAsyncPager:
678 r"""Lists matching subscriptions.
680 .. code-block:: python
682 # This snippet has been automatically generated and should be regarded as a
683 # code template only.
684 # It will require modifications to work:
685 # - It may require correct/in-range values for request initialization.
686 # - It may require specifying regional endpoints when creating the service
687 # client as shown in:
688 # https://googleapis.dev/python/google-api-core/latest/client_options.html
689 from google import pubsub_v1
691 async def sample_list_subscriptions():
692 # Create a client
693 client = pubsub_v1.SubscriberAsyncClient()
695 # Initialize request argument(s)
696 request = pubsub_v1.ListSubscriptionsRequest(
697 project="project_value",
698 )
700 # Make the request
701 page_result = client.list_subscriptions(request=request)
703 # Handle the response
704 async for response in page_result:
705 print(response)
707 Args:
708 request (Optional[Union[google.pubsub_v1.types.ListSubscriptionsRequest, dict]]):
709 The request object. Request for the ``ListSubscriptions`` method.
710 project (:class:`str`):
711 Required. The name of the project in which to list
712 subscriptions. Format is ``projects/{project-id}``.
714 This corresponds to the ``project`` field
715 on the ``request`` instance; if ``request`` is provided, this
716 should not be set.
717 retry (google.api_core.retry.Retry): Designation of what errors, if any,
718 should be retried.
719 timeout (float): The timeout for this request.
720 metadata (Sequence[Tuple[str, str]]): Strings which should be
721 sent along with the request as metadata.
723 Returns:
724 google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsAsyncPager:
725 Response for the ListSubscriptions method.
727 Iterating over this object will yield results and
728 resolve additional pages automatically.
730 """
731 # Create or coerce a protobuf request object.
732 # Quick check: If we got a request object, we should *not* have
733 # gotten any keyword arguments that map to the request.
734 has_flattened_params = any([project])
735 if request is not None and has_flattened_params:
736 raise ValueError(
737 "If the `request` argument is set, then none of "
738 "the individual field arguments should be set."
739 )
741 request = pubsub.ListSubscriptionsRequest(request)
743 # If we have keyword arguments corresponding to fields on the
744 # request, apply these.
745 if project is not None:
746 request.project = project
748 # Wrap the RPC method; this adds retry and timeout information,
749 # and friendly error handling.
750 rpc = gapic_v1.method_async.wrap_method(
751 self._client._transport.list_subscriptions,
752 default_retry=retries.Retry(
753 initial=0.1,
754 maximum=60.0,
755 multiplier=1.3,
756 predicate=retries.if_exception_type(
757 core_exceptions.Aborted,
758 core_exceptions.ServiceUnavailable,
759 core_exceptions.Unknown,
760 ),
761 deadline=60.0,
762 ),
763 default_timeout=60.0,
764 client_info=DEFAULT_CLIENT_INFO,
765 )
767 # Certain fields should be provided within the metadata header;
768 # add these here.
769 metadata = tuple(metadata) + (
770 gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)),
771 )
773 # Send the request.
774 response = await rpc(
775 request,
776 retry=retry,
777 timeout=timeout,
778 metadata=metadata,
779 )
781 # This method is paged; wrap the response in a pager, which provides
782 # an `__aiter__` convenience method.
783 response = pagers.ListSubscriptionsAsyncPager(
784 method=rpc,
785 request=request,
786 response=response,
787 metadata=metadata,
788 )
790 # Done; return the response.
791 return response
793 async def delete_subscription(
794 self,
795 request: Optional[Union[pubsub.DeleteSubscriptionRequest, dict]] = None,
796 *,
797 subscription: Optional[str] = None,
798 retry: OptionalRetry = gapic_v1.method.DEFAULT,
799 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
800 metadata: Sequence[Tuple[str, str]] = (),
801 ) -> None:
802 r"""Deletes an existing subscription. All messages retained in the
803 subscription are immediately dropped. Calls to ``Pull`` after
804 deletion will return ``NOT_FOUND``. After a subscription is
805 deleted, a new one may be created with the same name, but the
806 new one has no association with the old subscription or its
807 topic unless the same topic is specified.
809 .. code-block:: python
811 # This snippet has been automatically generated and should be regarded as a
812 # code template only.
813 # It will require modifications to work:
814 # - It may require correct/in-range values for request initialization.
815 # - It may require specifying regional endpoints when creating the service
816 # client as shown in:
817 # https://googleapis.dev/python/google-api-core/latest/client_options.html
818 from google import pubsub_v1
820 async def sample_delete_subscription():
821 # Create a client
822 client = pubsub_v1.SubscriberAsyncClient()
824 # Initialize request argument(s)
825 request = pubsub_v1.DeleteSubscriptionRequest(
826 subscription="subscription_value",
827 )
829 # Make the request
830 await client.delete_subscription(request=request)
832 Args:
833 request (Optional[Union[google.pubsub_v1.types.DeleteSubscriptionRequest, dict]]):
834 The request object. Request for the DeleteSubscription
835 method.
836 subscription (:class:`str`):
837 Required. The subscription to delete. Format is
838 ``projects/{project}/subscriptions/{sub}``.
840 This corresponds to the ``subscription`` field
841 on the ``request`` instance; if ``request`` is provided, this
842 should not be set.
843 retry (google.api_core.retry.Retry): Designation of what errors, if any,
844 should be retried.
845 timeout (float): The timeout for this request.
846 metadata (Sequence[Tuple[str, str]]): Strings which should be
847 sent along with the request as metadata.
848 """
849 # Create or coerce a protobuf request object.
850 # Quick check: If we got a request object, we should *not* have
851 # gotten any keyword arguments that map to the request.
852 has_flattened_params = any([subscription])
853 if request is not None and has_flattened_params:
854 raise ValueError(
855 "If the `request` argument is set, then none of "
856 "the individual field arguments should be set."
857 )
859 request = pubsub.DeleteSubscriptionRequest(request)
861 # If we have keyword arguments corresponding to fields on the
862 # request, apply these.
863 if subscription is not None:
864 request.subscription = subscription
866 # Wrap the RPC method; this adds retry and timeout information,
867 # and friendly error handling.
868 rpc = gapic_v1.method_async.wrap_method(
869 self._client._transport.delete_subscription,
870 default_retry=retries.Retry(
871 initial=0.1,
872 maximum=60.0,
873 multiplier=1.3,
874 predicate=retries.if_exception_type(
875 core_exceptions.ServiceUnavailable,
876 ),
877 deadline=60.0,
878 ),
879 default_timeout=60.0,
880 client_info=DEFAULT_CLIENT_INFO,
881 )
883 # Certain fields should be provided within the metadata header;
884 # add these here.
885 metadata = tuple(metadata) + (
886 gapic_v1.routing_header.to_grpc_metadata(
887 (("subscription", request.subscription),)
888 ),
889 )
891 # Send the request.
892 await rpc(
893 request,
894 retry=retry,
895 timeout=timeout,
896 metadata=metadata,
897 )
899 async def modify_ack_deadline(
900 self,
901 request: Optional[Union[pubsub.ModifyAckDeadlineRequest, dict]] = None,
902 *,
903 subscription: Optional[str] = None,
904 ack_ids: Optional[MutableSequence[str]] = None,
905 ack_deadline_seconds: Optional[int] = None,
906 retry: OptionalRetry = gapic_v1.method.DEFAULT,
907 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
908 metadata: Sequence[Tuple[str, str]] = (),
909 ) -> None:
910 r"""Modifies the ack deadline for a specific message. This method is
911 useful to indicate that more time is needed to process a message
912 by the subscriber, or to make the message available for
913 redelivery if the processing was interrupted. Note that this
914 does not modify the subscription-level ``ackDeadlineSeconds``
915 used for subsequent messages.
917 .. code-block:: python
919 # This snippet has been automatically generated and should be regarded as a
920 # code template only.
921 # It will require modifications to work:
922 # - It may require correct/in-range values for request initialization.
923 # - It may require specifying regional endpoints when creating the service
924 # client as shown in:
925 # https://googleapis.dev/python/google-api-core/latest/client_options.html
926 from google import pubsub_v1
928 async def sample_modify_ack_deadline():
929 # Create a client
930 client = pubsub_v1.SubscriberAsyncClient()
932 # Initialize request argument(s)
933 request = pubsub_v1.ModifyAckDeadlineRequest(
934 subscription="subscription_value",
935 ack_ids=['ack_ids_value1', 'ack_ids_value2'],
936 ack_deadline_seconds=2066,
937 )
939 # Make the request
940 await client.modify_ack_deadline(request=request)
942 Args:
943 request (Optional[Union[google.pubsub_v1.types.ModifyAckDeadlineRequest, dict]]):
944 The request object. Request for the ModifyAckDeadline
945 method.
946 subscription (:class:`str`):
947 Required. The name of the subscription. Format is
948 ``projects/{project}/subscriptions/{sub}``.
950 This corresponds to the ``subscription`` field
951 on the ``request`` instance; if ``request`` is provided, this
952 should not be set.
953 ack_ids (:class:`MutableSequence[str]`):
954 Required. List of acknowledgment IDs.
955 This corresponds to the ``ack_ids`` field
956 on the ``request`` instance; if ``request`` is provided, this
957 should not be set.
958 ack_deadline_seconds (:class:`int`):
959 Required. The new ack deadline with respect to the time
960 this request was sent to the Pub/Sub system. For
961 example, if the value is 10, the new ack deadline will
962 expire 10 seconds after the ``ModifyAckDeadline`` call
963 was made. Specifying zero might immediately make the
964 message available for delivery to another subscriber
965 client. This typically results in an increase in the
966 rate of message redeliveries (that is, duplicates). The
967 minimum deadline you can specify is 0 seconds. The
968 maximum deadline you can specify is 600 seconds (10
969 minutes).
971 This corresponds to the ``ack_deadline_seconds`` field
972 on the ``request`` instance; if ``request`` is provided, this
973 should not be set.
974 retry (google.api_core.retry.Retry): Designation of what errors, if any,
975 should be retried.
976 timeout (float): The timeout for this request.
977 metadata (Sequence[Tuple[str, str]]): Strings which should be
978 sent along with the request as metadata.
979 """
980 # Create or coerce a protobuf request object.
981 # Quick check: If we got a request object, we should *not* have
982 # gotten any keyword arguments that map to the request.
983 has_flattened_params = any([subscription, ack_ids, ack_deadline_seconds])
984 if request is not None and has_flattened_params:
985 raise ValueError(
986 "If the `request` argument is set, then none of "
987 "the individual field arguments should be set."
988 )
990 request = pubsub.ModifyAckDeadlineRequest(request)
992 # If we have keyword arguments corresponding to fields on the
993 # request, apply these.
994 if subscription is not None:
995 request.subscription = subscription
996 if ack_deadline_seconds is not None:
997 request.ack_deadline_seconds = ack_deadline_seconds
998 if ack_ids:
999 request.ack_ids.extend(ack_ids)
1001 # Wrap the RPC method; this adds retry and timeout information,
1002 # and friendly error handling.
1003 rpc = gapic_v1.method_async.wrap_method(
1004 self._client._transport.modify_ack_deadline,
1005 default_retry=retries.Retry(
1006 initial=0.1,
1007 maximum=60.0,
1008 multiplier=1.3,
1009 predicate=retries.if_exception_type(
1010 core_exceptions.ServiceUnavailable,
1011 ),
1012 deadline=60.0,
1013 ),
1014 default_timeout=60.0,
1015 client_info=DEFAULT_CLIENT_INFO,
1016 )
1018 # Certain fields should be provided within the metadata header;
1019 # add these here.
1020 metadata = tuple(metadata) + (
1021 gapic_v1.routing_header.to_grpc_metadata(
1022 (("subscription", request.subscription),)
1023 ),
1024 )
1026 # Send the request.
1027 await rpc(
1028 request,
1029 retry=retry,
1030 timeout=timeout,
1031 metadata=metadata,
1032 )
1034 async def acknowledge(
1035 self,
1036 request: Optional[Union[pubsub.AcknowledgeRequest, dict]] = None,
1037 *,
1038 subscription: Optional[str] = None,
1039 ack_ids: Optional[MutableSequence[str]] = None,
1040 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1041 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1042 metadata: Sequence[Tuple[str, str]] = (),
1043 ) -> None:
1044 r"""Acknowledges the messages associated with the ``ack_ids`` in the
1045 ``AcknowledgeRequest``. The Pub/Sub system can remove the
1046 relevant messages from the subscription.
1048 Acknowledging a message whose ack deadline has expired may
1049 succeed, but such a message may be redelivered later.
1050 Acknowledging a message more than once will not result in an
1051 error.
1053 .. code-block:: python
1055 # This snippet has been automatically generated and should be regarded as a
1056 # code template only.
1057 # It will require modifications to work:
1058 # - It may require correct/in-range values for request initialization.
1059 # - It may require specifying regional endpoints when creating the service
1060 # client as shown in:
1061 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1062 from google import pubsub_v1
1064 async def sample_acknowledge():
1065 # Create a client
1066 client = pubsub_v1.SubscriberAsyncClient()
1068 # Initialize request argument(s)
1069 request = pubsub_v1.AcknowledgeRequest(
1070 subscription="subscription_value",
1071 ack_ids=['ack_ids_value1', 'ack_ids_value2'],
1072 )
1074 # Make the request
1075 await client.acknowledge(request=request)
1077 Args:
1078 request (Optional[Union[google.pubsub_v1.types.AcknowledgeRequest, dict]]):
1079 The request object. Request for the Acknowledge method.
1080 subscription (:class:`str`):
1081 Required. The subscription whose message is being
1082 acknowledged. Format is
1083 ``projects/{project}/subscriptions/{sub}``.
1085 This corresponds to the ``subscription`` field
1086 on the ``request`` instance; if ``request`` is provided, this
1087 should not be set.
1088 ack_ids (:class:`MutableSequence[str]`):
1089 Required. The acknowledgment ID for the messages being
1090 acknowledged that was returned by the Pub/Sub system in
1091 the ``Pull`` response. Must not be empty.
1093 This corresponds to the ``ack_ids`` field
1094 on the ``request`` instance; if ``request`` is provided, this
1095 should not be set.
1096 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1097 should be retried.
1098 timeout (float): The timeout for this request.
1099 metadata (Sequence[Tuple[str, str]]): Strings which should be
1100 sent along with the request as metadata.
1101 """
1102 # Create or coerce a protobuf request object.
1103 # Quick check: If we got a request object, we should *not* have
1104 # gotten any keyword arguments that map to the request.
1105 has_flattened_params = any([subscription, ack_ids])
1106 if request is not None and has_flattened_params:
1107 raise ValueError(
1108 "If the `request` argument is set, then none of "
1109 "the individual field arguments should be set."
1110 )
1112 request = pubsub.AcknowledgeRequest(request)
1114 # If we have keyword arguments corresponding to fields on the
1115 # request, apply these.
1116 if subscription is not None:
1117 request.subscription = subscription
1118 if ack_ids:
1119 request.ack_ids.extend(ack_ids)
1121 # Wrap the RPC method; this adds retry and timeout information,
1122 # and friendly error handling.
1123 rpc = gapic_v1.method_async.wrap_method(
1124 self._client._transport.acknowledge,
1125 default_retry=retries.Retry(
1126 initial=0.1,
1127 maximum=60.0,
1128 multiplier=1.3,
1129 predicate=retries.if_exception_type(
1130 core_exceptions.ServiceUnavailable,
1131 ),
1132 deadline=60.0,
1133 ),
1134 default_timeout=60.0,
1135 client_info=DEFAULT_CLIENT_INFO,
1136 )
1138 # Certain fields should be provided within the metadata header;
1139 # add these here.
1140 metadata = tuple(metadata) + (
1141 gapic_v1.routing_header.to_grpc_metadata(
1142 (("subscription", request.subscription),)
1143 ),
1144 )
1146 # Send the request.
1147 await rpc(
1148 request,
1149 retry=retry,
1150 timeout=timeout,
1151 metadata=metadata,
1152 )
1154 async def pull(
1155 self,
1156 request: Optional[Union[pubsub.PullRequest, dict]] = None,
1157 *,
1158 subscription: Optional[str] = None,
1159 return_immediately: Optional[bool] = None,
1160 max_messages: Optional[int] = None,
1161 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1162 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1163 metadata: Sequence[Tuple[str, str]] = (),
1164 ) -> pubsub.PullResponse:
1165 r"""Pulls messages from the server.
1167 .. code-block:: python
1169 # This snippet has been automatically generated and should be regarded as a
1170 # code template only.
1171 # It will require modifications to work:
1172 # - It may require correct/in-range values for request initialization.
1173 # - It may require specifying regional endpoints when creating the service
1174 # client as shown in:
1175 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1176 from google import pubsub_v1
1178 async def sample_pull():
1179 # Create a client
1180 client = pubsub_v1.SubscriberAsyncClient()
1182 # Initialize request argument(s)
1183 request = pubsub_v1.PullRequest(
1184 subscription="subscription_value",
1185 max_messages=1277,
1186 )
1188 # Make the request
1189 response = await client.pull(request=request)
1191 # Handle the response
1192 print(response)
1194 Args:
1195 request (Optional[Union[google.pubsub_v1.types.PullRequest, dict]]):
1196 The request object. Request for the ``Pull`` method.
1197 subscription (:class:`str`):
1198 Required. The subscription from which messages should be
1199 pulled. Format is
1200 ``projects/{project}/subscriptions/{sub}``.
1202 This corresponds to the ``subscription`` field
1203 on the ``request`` instance; if ``request`` is provided, this
1204 should not be set.
1205 return_immediately (:class:`bool`):
1206 Optional. If this field set to true, the system will
1207 respond immediately even if it there are no messages
1208 available to return in the ``Pull`` response. Otherwise,
1209 the system may wait (for a bounded amount of time) until
1210 at least one message is available, rather than returning
1211 no messages. Warning: setting this field to ``true`` is
1212 discouraged because it adversely impacts the performance
1213 of ``Pull`` operations. We recommend that users do not
1214 set this field.
1216 This corresponds to the ``return_immediately`` field
1217 on the ``request`` instance; if ``request`` is provided, this
1218 should not be set.
1219 max_messages (:class:`int`):
1220 Required. The maximum number of
1221 messages to return for this request.
1222 Must be a positive integer. The Pub/Sub
1223 system may return fewer than the number
1224 specified.
1226 This corresponds to the ``max_messages`` field
1227 on the ``request`` instance; if ``request`` is provided, this
1228 should not be set.
1229 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1230 should be retried.
1231 timeout (float): The timeout for this request.
1232 metadata (Sequence[Tuple[str, str]]): Strings which should be
1233 sent along with the request as metadata.
1235 Returns:
1236 google.pubsub_v1.types.PullResponse:
1237 Response for the Pull method.
1238 """
1239 # Create or coerce a protobuf request object.
1240 # Quick check: If we got a request object, we should *not* have
1241 # gotten any keyword arguments that map to the request.
1242 has_flattened_params = any([subscription, return_immediately, max_messages])
1243 if request is not None and has_flattened_params:
1244 raise ValueError(
1245 "If the `request` argument is set, then none of "
1246 "the individual field arguments should be set."
1247 )
1249 request = pubsub.PullRequest(request)
1251 # If we have keyword arguments corresponding to fields on the
1252 # request, apply these.
1253 if subscription is not None:
1254 request.subscription = subscription
1255 if return_immediately is not None:
1256 request.return_immediately = return_immediately
1257 if max_messages is not None:
1258 request.max_messages = max_messages
1260 if request.return_immediately:
1261 warnings.warn(
1262 "The return_immediately flag is deprecated and should be set to False.",
1263 category=DeprecationWarning,
1264 )
1266 # Wrap the RPC method; this adds retry and timeout information,
1267 # and friendly error handling.
1268 rpc = gapic_v1.method_async.wrap_method(
1269 self._client._transport.pull,
1270 default_retry=retries.Retry(
1271 initial=0.1,
1272 maximum=60.0,
1273 multiplier=1.3,
1274 predicate=retries.if_exception_type(
1275 core_exceptions.Aborted,
1276 core_exceptions.InternalServerError,
1277 core_exceptions.ServiceUnavailable,
1278 core_exceptions.Unknown,
1279 ),
1280 deadline=60.0,
1281 ),
1282 default_timeout=60.0,
1283 client_info=DEFAULT_CLIENT_INFO,
1284 )
1286 # Certain fields should be provided within the metadata header;
1287 # add these here.
1288 metadata = tuple(metadata) + (
1289 gapic_v1.routing_header.to_grpc_metadata(
1290 (("subscription", request.subscription),)
1291 ),
1292 )
1294 # Send the request.
1295 response = await rpc(
1296 request,
1297 retry=retry,
1298 timeout=timeout,
1299 metadata=metadata,
1300 )
1302 # Done; return the response.
1303 return response
1305 def streaming_pull(
1306 self,
1307 requests: Optional[AsyncIterator[pubsub.StreamingPullRequest]] = None,
1308 *,
1309 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1310 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1311 metadata: Sequence[Tuple[str, str]] = (),
1312 ) -> Awaitable[AsyncIterable[pubsub.StreamingPullResponse]]:
1313 r"""Establishes a stream with the server, which sends messages down
1314 to the client. The client streams acknowledgements and ack
1315 deadline modifications back to the server. The server will close
1316 the stream and return the status on any error. The server may
1317 close the stream with status ``UNAVAILABLE`` to reassign
1318 server-side resources, in which case, the client should
1319 re-establish the stream. Flow control can be achieved by
1320 configuring the underlying RPC channel.
1322 .. code-block:: python
1324 # This snippet has been automatically generated and should be regarded as a
1325 # code template only.
1326 # It will require modifications to work:
1327 # - It may require correct/in-range values for request initialization.
1328 # - It may require specifying regional endpoints when creating the service
1329 # client as shown in:
1330 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1331 from google import pubsub_v1
1333 async def sample_streaming_pull():
1334 # Create a client
1335 client = pubsub_v1.SubscriberAsyncClient()
1337 # Initialize request argument(s)
1338 request = pubsub_v1.StreamingPullRequest(
1339 subscription="subscription_value",
1340 stream_ack_deadline_seconds=2813,
1341 )
1343 # This method expects an iterator which contains
1344 # 'pubsub_v1.StreamingPullRequest' objects
1345 # Here we create a generator that yields a single `request` for
1346 # demonstrative purposes.
1347 requests = [request]
1349 def request_generator():
1350 for request in requests:
1351 yield request
1353 # Make the request
1354 stream = await client.streaming_pull(requests=request_generator())
1356 # Handle the response
1357 async for response in stream:
1358 print(response)
1360 Args:
1361 requests (AsyncIterator[`google.pubsub_v1.types.StreamingPullRequest`]):
1362 The request object AsyncIterator. Request for the ``StreamingPull`` streaming RPC method.
1363 This request is used to establish the initial stream as
1364 well as to stream acknowledgements and ack deadline
1365 modifications from the client to the server.
1366 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1367 should be retried.
1368 timeout (float): The timeout for this request.
1369 metadata (Sequence[Tuple[str, str]]): Strings which should be
1370 sent along with the request as metadata.
1372 Returns:
1373 AsyncIterable[google.pubsub_v1.types.StreamingPullResponse]:
1374 Response for the StreamingPull method. This response is used to stream
1375 messages from the server to the client.
1377 """
1379 # Wrap the RPC method; this adds retry and timeout information,
1380 # and friendly error handling.
1381 rpc = gapic_v1.method_async.wrap_method(
1382 self._client._transport.streaming_pull,
1383 default_retry=retries.Retry(
1384 initial=0.1,
1385 maximum=60.0,
1386 multiplier=1.3,
1387 predicate=retries.if_exception_type(
1388 core_exceptions.Aborted,
1389 core_exceptions.DeadlineExceeded,
1390 core_exceptions.InternalServerError,
1391 core_exceptions.ResourceExhausted,
1392 core_exceptions.ServiceUnavailable,
1393 ),
1394 deadline=900.0,
1395 ),
1396 default_timeout=900.0,
1397 client_info=DEFAULT_CLIENT_INFO,
1398 )
1400 # Send the request.
1401 response = rpc(
1402 requests,
1403 retry=retry,
1404 timeout=timeout,
1405 metadata=metadata,
1406 )
1408 # Done; return the response.
1409 return response
1411 async def modify_push_config(
1412 self,
1413 request: Optional[Union[pubsub.ModifyPushConfigRequest, dict]] = None,
1414 *,
1415 subscription: Optional[str] = None,
1416 push_config: Optional[pubsub.PushConfig] = None,
1417 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1418 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1419 metadata: Sequence[Tuple[str, str]] = (),
1420 ) -> None:
1421 r"""Modifies the ``PushConfig`` for a specified subscription.
1423 This may be used to change a push subscription to a pull one
1424 (signified by an empty ``PushConfig``) or vice versa, or change
1425 the endpoint URL and other attributes of a push subscription.
1426 Messages will accumulate for delivery continuously through the
1427 call regardless of changes to the ``PushConfig``.
1429 .. code-block:: python
1431 # This snippet has been automatically generated and should be regarded as a
1432 # code template only.
1433 # It will require modifications to work:
1434 # - It may require correct/in-range values for request initialization.
1435 # - It may require specifying regional endpoints when creating the service
1436 # client as shown in:
1437 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1438 from google import pubsub_v1
1440 async def sample_modify_push_config():
1441 # Create a client
1442 client = pubsub_v1.SubscriberAsyncClient()
1444 # Initialize request argument(s)
1445 request = pubsub_v1.ModifyPushConfigRequest(
1446 subscription="subscription_value",
1447 )
1449 # Make the request
1450 await client.modify_push_config(request=request)
1452 Args:
1453 request (Optional[Union[google.pubsub_v1.types.ModifyPushConfigRequest, dict]]):
1454 The request object. Request for the ModifyPushConfig
1455 method.
1456 subscription (:class:`str`):
1457 Required. The name of the subscription. Format is
1458 ``projects/{project}/subscriptions/{sub}``.
1460 This corresponds to the ``subscription`` field
1461 on the ``request`` instance; if ``request`` is provided, this
1462 should not be set.
1463 push_config (:class:`google.pubsub_v1.types.PushConfig`):
1464 Required. The push configuration for future deliveries.
1466 An empty ``pushConfig`` indicates that the Pub/Sub
1467 system should stop pushing messages from the given
1468 subscription and allow messages to be pulled and
1469 acknowledged - effectively pausing the subscription if
1470 ``Pull`` or ``StreamingPull`` is not called.
1472 This corresponds to the ``push_config`` field
1473 on the ``request`` instance; if ``request`` is provided, this
1474 should not be set.
1475 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1476 should be retried.
1477 timeout (float): The timeout for this request.
1478 metadata (Sequence[Tuple[str, str]]): Strings which should be
1479 sent along with the request as metadata.
1480 """
1481 # Create or coerce a protobuf request object.
1482 # Quick check: If we got a request object, we should *not* have
1483 # gotten any keyword arguments that map to the request.
1484 has_flattened_params = any([subscription, push_config])
1485 if request is not None and has_flattened_params:
1486 raise ValueError(
1487 "If the `request` argument is set, then none of "
1488 "the individual field arguments should be set."
1489 )
1491 request = pubsub.ModifyPushConfigRequest(request)
1493 # If we have keyword arguments corresponding to fields on the
1494 # request, apply these.
1495 if subscription is not None:
1496 request.subscription = subscription
1497 if push_config is not None:
1498 request.push_config = push_config
1500 # Wrap the RPC method; this adds retry and timeout information,
1501 # and friendly error handling.
1502 rpc = gapic_v1.method_async.wrap_method(
1503 self._client._transport.modify_push_config,
1504 default_retry=retries.Retry(
1505 initial=0.1,
1506 maximum=60.0,
1507 multiplier=1.3,
1508 predicate=retries.if_exception_type(
1509 core_exceptions.ServiceUnavailable,
1510 ),
1511 deadline=60.0,
1512 ),
1513 default_timeout=60.0,
1514 client_info=DEFAULT_CLIENT_INFO,
1515 )
1517 # Certain fields should be provided within the metadata header;
1518 # add these here.
1519 metadata = tuple(metadata) + (
1520 gapic_v1.routing_header.to_grpc_metadata(
1521 (("subscription", request.subscription),)
1522 ),
1523 )
1525 # Send the request.
1526 await rpc(
1527 request,
1528 retry=retry,
1529 timeout=timeout,
1530 metadata=metadata,
1531 )
1533 async def get_snapshot(
1534 self,
1535 request: Optional[Union[pubsub.GetSnapshotRequest, dict]] = None,
1536 *,
1537 snapshot: Optional[str] = None,
1538 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1539 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1540 metadata: Sequence[Tuple[str, str]] = (),
1541 ) -> pubsub.Snapshot:
1542 r"""Gets the configuration details of a snapshot. Snapshots are used
1543 in
1544 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
1545 operations, which allow you to manage message acknowledgments in
1546 bulk. That is, you can set the acknowledgment state of messages
1547 in an existing subscription to the state captured by a snapshot.
1549 .. code-block:: python
1551 # This snippet has been automatically generated and should be regarded as a
1552 # code template only.
1553 # It will require modifications to work:
1554 # - It may require correct/in-range values for request initialization.
1555 # - It may require specifying regional endpoints when creating the service
1556 # client as shown in:
1557 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1558 from google import pubsub_v1
1560 async def sample_get_snapshot():
1561 # Create a client
1562 client = pubsub_v1.SubscriberAsyncClient()
1564 # Initialize request argument(s)
1565 request = pubsub_v1.GetSnapshotRequest(
1566 snapshot="snapshot_value",
1567 )
1569 # Make the request
1570 response = await client.get_snapshot(request=request)
1572 # Handle the response
1573 print(response)
1575 Args:
1576 request (Optional[Union[google.pubsub_v1.types.GetSnapshotRequest, dict]]):
1577 The request object. Request for the GetSnapshot method.
1578 snapshot (:class:`str`):
1579 Required. The name of the snapshot to get. Format is
1580 ``projects/{project}/snapshots/{snap}``.
1582 This corresponds to the ``snapshot`` field
1583 on the ``request`` instance; if ``request`` is provided, this
1584 should not be set.
1585 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1586 should be retried.
1587 timeout (float): The timeout for this request.
1588 metadata (Sequence[Tuple[str, str]]): Strings which should be
1589 sent along with the request as metadata.
1591 Returns:
1592 google.pubsub_v1.types.Snapshot:
1593 A snapshot resource. Snapshots are used in
1594 [Seek](https://cloud.google.com/pubsub/docs/replay-overview)
1595 operations, which allow you to manage message
1596 acknowledgments in bulk. That is, you can set the
1597 acknowledgment state of messages in an existing
1598 subscription to the state captured by a snapshot.
1600 """
1601 # Create or coerce a protobuf request object.
1602 # Quick check: If we got a request object, we should *not* have
1603 # gotten any keyword arguments that map to the request.
1604 has_flattened_params = any([snapshot])
1605 if request is not None and has_flattened_params:
1606 raise ValueError(
1607 "If the `request` argument is set, then none of "
1608 "the individual field arguments should be set."
1609 )
1611 request = pubsub.GetSnapshotRequest(request)
1613 # If we have keyword arguments corresponding to fields on the
1614 # request, apply these.
1615 if snapshot is not None:
1616 request.snapshot = snapshot
1618 # Wrap the RPC method; this adds retry and timeout information,
1619 # and friendly error handling.
1620 rpc = gapic_v1.method_async.wrap_method(
1621 self._client._transport.get_snapshot,
1622 default_retry=retries.Retry(
1623 initial=0.1,
1624 maximum=60.0,
1625 multiplier=1.3,
1626 predicate=retries.if_exception_type(
1627 core_exceptions.Aborted,
1628 core_exceptions.ServiceUnavailable,
1629 core_exceptions.Unknown,
1630 ),
1631 deadline=60.0,
1632 ),
1633 default_timeout=60.0,
1634 client_info=DEFAULT_CLIENT_INFO,
1635 )
1637 # Certain fields should be provided within the metadata header;
1638 # add these here.
1639 metadata = tuple(metadata) + (
1640 gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)),
1641 )
1643 # Send the request.
1644 response = await rpc(
1645 request,
1646 retry=retry,
1647 timeout=timeout,
1648 metadata=metadata,
1649 )
1651 # Done; return the response.
1652 return response
1654 async def list_snapshots(
1655 self,
1656 request: Optional[Union[pubsub.ListSnapshotsRequest, dict]] = None,
1657 *,
1658 project: Optional[str] = None,
1659 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1660 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1661 metadata: Sequence[Tuple[str, str]] = (),
1662 ) -> pagers.ListSnapshotsAsyncPager:
1663 r"""Lists the existing snapshots. Snapshots are used in
1664 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
1665 operations, which allow you to manage message acknowledgments in
1666 bulk. That is, you can set the acknowledgment state of messages
1667 in an existing subscription to the state captured by a snapshot.
1669 .. code-block:: python
1671 # This snippet has been automatically generated and should be regarded as a
1672 # code template only.
1673 # It will require modifications to work:
1674 # - It may require correct/in-range values for request initialization.
1675 # - It may require specifying regional endpoints when creating the service
1676 # client as shown in:
1677 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1678 from google import pubsub_v1
1680 async def sample_list_snapshots():
1681 # Create a client
1682 client = pubsub_v1.SubscriberAsyncClient()
1684 # Initialize request argument(s)
1685 request = pubsub_v1.ListSnapshotsRequest(
1686 project="project_value",
1687 )
1689 # Make the request
1690 page_result = client.list_snapshots(request=request)
1692 # Handle the response
1693 async for response in page_result:
1694 print(response)
1696 Args:
1697 request (Optional[Union[google.pubsub_v1.types.ListSnapshotsRequest, dict]]):
1698 The request object. Request for the ``ListSnapshots`` method.
1699 project (:class:`str`):
1700 Required. The name of the project in which to list
1701 snapshots. Format is ``projects/{project-id}``.
1703 This corresponds to the ``project`` field
1704 on the ``request`` instance; if ``request`` is provided, this
1705 should not be set.
1706 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1707 should be retried.
1708 timeout (float): The timeout for this request.
1709 metadata (Sequence[Tuple[str, str]]): Strings which should be
1710 sent along with the request as metadata.
1712 Returns:
1713 google.pubsub_v1.services.subscriber.pagers.ListSnapshotsAsyncPager:
1714 Response for the ListSnapshots method.
1716 Iterating over this object will yield results and
1717 resolve additional pages automatically.
1719 """
1720 # Create or coerce a protobuf request object.
1721 # Quick check: If we got a request object, we should *not* have
1722 # gotten any keyword arguments that map to the request.
1723 has_flattened_params = any([project])
1724 if request is not None and has_flattened_params:
1725 raise ValueError(
1726 "If the `request` argument is set, then none of "
1727 "the individual field arguments should be set."
1728 )
1730 request = pubsub.ListSnapshotsRequest(request)
1732 # If we have keyword arguments corresponding to fields on the
1733 # request, apply these.
1734 if project is not None:
1735 request.project = project
1737 # Wrap the RPC method; this adds retry and timeout information,
1738 # and friendly error handling.
1739 rpc = gapic_v1.method_async.wrap_method(
1740 self._client._transport.list_snapshots,
1741 default_retry=retries.Retry(
1742 initial=0.1,
1743 maximum=60.0,
1744 multiplier=1.3,
1745 predicate=retries.if_exception_type(
1746 core_exceptions.Aborted,
1747 core_exceptions.ServiceUnavailable,
1748 core_exceptions.Unknown,
1749 ),
1750 deadline=60.0,
1751 ),
1752 default_timeout=60.0,
1753 client_info=DEFAULT_CLIENT_INFO,
1754 )
1756 # Certain fields should be provided within the metadata header;
1757 # add these here.
1758 metadata = tuple(metadata) + (
1759 gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)),
1760 )
1762 # Send the request.
1763 response = await rpc(
1764 request,
1765 retry=retry,
1766 timeout=timeout,
1767 metadata=metadata,
1768 )
1770 # This method is paged; wrap the response in a pager, which provides
1771 # an `__aiter__` convenience method.
1772 response = pagers.ListSnapshotsAsyncPager(
1773 method=rpc,
1774 request=request,
1775 response=response,
1776 metadata=metadata,
1777 )
1779 # Done; return the response.
1780 return response
1782 async def create_snapshot(
1783 self,
1784 request: Optional[Union[pubsub.CreateSnapshotRequest, dict]] = None,
1785 *,
1786 name: Optional[str] = None,
1787 subscription: Optional[str] = None,
1788 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1789 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1790 metadata: Sequence[Tuple[str, str]] = (),
1791 ) -> pubsub.Snapshot:
1792 r"""Creates a snapshot from the requested subscription. Snapshots
1793 are used in
1794 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
1795 operations, which allow you to manage message acknowledgments in
1796 bulk. That is, you can set the acknowledgment state of messages
1797 in an existing subscription to the state captured by a snapshot.
1798 If the snapshot already exists, returns ``ALREADY_EXISTS``. If
1799 the requested subscription doesn't exist, returns ``NOT_FOUND``.
1800 If the backlog in the subscription is too old -- and the
1801 resulting snapshot would expire in less than 1 hour -- then
1802 ``FAILED_PRECONDITION`` is returned. See also the
1803 ``Snapshot.expire_time`` field. If the name is not provided in
1804 the request, the server will assign a random name for this
1805 snapshot on the same project as the subscription, conforming to
1806 the [resource name format]
1807 (https://cloud.google.com/pubsub/docs/admin#resource_names). The
1808 generated name is populated in the returned Snapshot object.
1809 Note that for REST API requests, you must specify a name in the
1810 request.
1812 .. code-block:: python
1814 # This snippet has been automatically generated and should be regarded as a
1815 # code template only.
1816 # It will require modifications to work:
1817 # - It may require correct/in-range values for request initialization.
1818 # - It may require specifying regional endpoints when creating the service
1819 # client as shown in:
1820 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1821 from google import pubsub_v1
1823 async def sample_create_snapshot():
1824 # Create a client
1825 client = pubsub_v1.SubscriberAsyncClient()
1827 # Initialize request argument(s)
1828 request = pubsub_v1.CreateSnapshotRequest(
1829 name="name_value",
1830 subscription="subscription_value",
1831 )
1833 # Make the request
1834 response = await client.create_snapshot(request=request)
1836 # Handle the response
1837 print(response)
1839 Args:
1840 request (Optional[Union[google.pubsub_v1.types.CreateSnapshotRequest, dict]]):
1841 The request object. Request for the ``CreateSnapshot`` method.
1842 name (:class:`str`):
1843 Required. User-provided name for this snapshot. If the
1844 name is not provided in the request, the server will
1845 assign a random name for this snapshot on the same
1846 project as the subscription. Note that for REST API
1847 requests, you must specify a name. See the `resource
1848 name
1849 rules <https://cloud.google.com/pubsub/docs/admin#resource_names>`__.
1850 Format is ``projects/{project}/snapshots/{snap}``.
1852 This corresponds to the ``name`` field
1853 on the ``request`` instance; if ``request`` is provided, this
1854 should not be set.
1855 subscription (:class:`str`):
1856 Required. The subscription whose backlog the snapshot
1857 retains. Specifically, the created snapshot is
1858 guaranteed to retain: (a) The existing backlog on the
1859 subscription. More precisely, this is defined as the
1860 messages in the subscription's backlog that are
1861 unacknowledged upon the successful completion of the
1862 ``CreateSnapshot`` request; as well as: (b) Any messages
1863 published to the subscription's topic following the
1864 successful completion of the CreateSnapshot request.
1865 Format is ``projects/{project}/subscriptions/{sub}``.
1867 This corresponds to the ``subscription`` field
1868 on the ``request`` instance; if ``request`` is provided, this
1869 should not be set.
1870 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1871 should be retried.
1872 timeout (float): The timeout for this request.
1873 metadata (Sequence[Tuple[str, str]]): Strings which should be
1874 sent along with the request as metadata.
1876 Returns:
1877 google.pubsub_v1.types.Snapshot:
1878 A snapshot resource. Snapshots are used in
1879 [Seek](https://cloud.google.com/pubsub/docs/replay-overview)
1880 operations, which allow you to manage message
1881 acknowledgments in bulk. That is, you can set the
1882 acknowledgment state of messages in an existing
1883 subscription to the state captured by a snapshot.
1885 """
1886 # Create or coerce a protobuf request object.
1887 # Quick check: If we got a request object, we should *not* have
1888 # gotten any keyword arguments that map to the request.
1889 has_flattened_params = any([name, subscription])
1890 if request is not None and has_flattened_params:
1891 raise ValueError(
1892 "If the `request` argument is set, then none of "
1893 "the individual field arguments should be set."
1894 )
1896 request = pubsub.CreateSnapshotRequest(request)
1898 # If we have keyword arguments corresponding to fields on the
1899 # request, apply these.
1900 if name is not None:
1901 request.name = name
1902 if subscription is not None:
1903 request.subscription = subscription
1905 # Wrap the RPC method; this adds retry and timeout information,
1906 # and friendly error handling.
1907 rpc = gapic_v1.method_async.wrap_method(
1908 self._client._transport.create_snapshot,
1909 default_retry=retries.Retry(
1910 initial=0.1,
1911 maximum=60.0,
1912 multiplier=1.3,
1913 predicate=retries.if_exception_type(
1914 core_exceptions.ServiceUnavailable,
1915 ),
1916 deadline=60.0,
1917 ),
1918 default_timeout=60.0,
1919 client_info=DEFAULT_CLIENT_INFO,
1920 )
1922 # Certain fields should be provided within the metadata header;
1923 # add these here.
1924 metadata = tuple(metadata) + (
1925 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1926 )
1928 # Send the request.
1929 response = await rpc(
1930 request,
1931 retry=retry,
1932 timeout=timeout,
1933 metadata=metadata,
1934 )
1936 # Done; return the response.
1937 return response
1939 async def update_snapshot(
1940 self,
1941 request: Optional[Union[pubsub.UpdateSnapshotRequest, dict]] = None,
1942 *,
1943 snapshot: Optional[pubsub.Snapshot] = None,
1944 update_mask: Optional[field_mask_pb2.FieldMask] = None,
1945 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1946 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1947 metadata: Sequence[Tuple[str, str]] = (),
1948 ) -> pubsub.Snapshot:
1949 r"""Updates an existing snapshot. Snapshots are used in
1950 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
1951 operations, which allow you to manage message acknowledgments in
1952 bulk. That is, you can set the acknowledgment state of messages
1953 in an existing subscription to the state captured by a snapshot.
1955 .. code-block:: python
1957 # This snippet has been automatically generated and should be regarded as a
1958 # code template only.
1959 # It will require modifications to work:
1960 # - It may require correct/in-range values for request initialization.
1961 # - It may require specifying regional endpoints when creating the service
1962 # client as shown in:
1963 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1964 from google import pubsub_v1
1966 async def sample_update_snapshot():
1967 # Create a client
1968 client = pubsub_v1.SubscriberAsyncClient()
1970 # Initialize request argument(s)
1971 request = pubsub_v1.UpdateSnapshotRequest(
1972 )
1974 # Make the request
1975 response = await client.update_snapshot(request=request)
1977 # Handle the response
1978 print(response)
1980 Args:
1981 request (Optional[Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]]):
1982 The request object. Request for the UpdateSnapshot
1983 method.
1984 snapshot (:class:`google.pubsub_v1.types.Snapshot`):
1985 Required. The updated snapshot
1986 object.
1988 This corresponds to the ``snapshot`` field
1989 on the ``request`` instance; if ``request`` is provided, this
1990 should not be set.
1991 update_mask (:class:`google.protobuf.field_mask_pb2.FieldMask`):
1992 Required. Indicates which fields in
1993 the provided snapshot to update. Must be
1994 specified and non-empty.
1996 This corresponds to the ``update_mask`` field
1997 on the ``request`` instance; if ``request`` is provided, this
1998 should not be set.
1999 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2000 should be retried.
2001 timeout (float): The timeout for this request.
2002 metadata (Sequence[Tuple[str, str]]): Strings which should be
2003 sent along with the request as metadata.
2005 Returns:
2006 google.pubsub_v1.types.Snapshot:
2007 A snapshot resource. Snapshots are used in
2008 [Seek](https://cloud.google.com/pubsub/docs/replay-overview)
2009 operations, which allow you to manage message
2010 acknowledgments in bulk. That is, you can set the
2011 acknowledgment state of messages in an existing
2012 subscription to the state captured by a snapshot.
2014 """
2015 # Create or coerce a protobuf request object.
2016 # Quick check: If we got a request object, we should *not* have
2017 # gotten any keyword arguments that map to the request.
2018 has_flattened_params = any([snapshot, update_mask])
2019 if request is not None and has_flattened_params:
2020 raise ValueError(
2021 "If the `request` argument is set, then none of "
2022 "the individual field arguments should be set."
2023 )
2025 request = pubsub.UpdateSnapshotRequest(request)
2027 # If we have keyword arguments corresponding to fields on the
2028 # request, apply these.
2029 if snapshot is not None:
2030 request.snapshot = snapshot
2031 if update_mask is not None:
2032 request.update_mask = update_mask
2034 # Wrap the RPC method; this adds retry and timeout information,
2035 # and friendly error handling.
2036 rpc = gapic_v1.method_async.wrap_method(
2037 self._client._transport.update_snapshot,
2038 default_retry=retries.Retry(
2039 initial=0.1,
2040 maximum=60.0,
2041 multiplier=1.3,
2042 predicate=retries.if_exception_type(
2043 core_exceptions.ServiceUnavailable,
2044 ),
2045 deadline=60.0,
2046 ),
2047 default_timeout=60.0,
2048 client_info=DEFAULT_CLIENT_INFO,
2049 )
2051 # Certain fields should be provided within the metadata header;
2052 # add these here.
2053 metadata = tuple(metadata) + (
2054 gapic_v1.routing_header.to_grpc_metadata(
2055 (("snapshot.name", request.snapshot.name),)
2056 ),
2057 )
2059 # Send the request.
2060 response = await rpc(
2061 request,
2062 retry=retry,
2063 timeout=timeout,
2064 metadata=metadata,
2065 )
2067 # Done; return the response.
2068 return response
2070 async def delete_snapshot(
2071 self,
2072 request: Optional[Union[pubsub.DeleteSnapshotRequest, dict]] = None,
2073 *,
2074 snapshot: Optional[str] = None,
2075 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2076 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2077 metadata: Sequence[Tuple[str, str]] = (),
2078 ) -> None:
2079 r"""Removes an existing snapshot. Snapshots are used in [Seek]
2080 (https://cloud.google.com/pubsub/docs/replay-overview)
2081 operations, which allow you to manage message acknowledgments in
2082 bulk. That is, you can set the acknowledgment state of messages
2083 in an existing subscription to the state captured by a snapshot.
2084 When the snapshot is deleted, all messages retained in the
2085 snapshot are immediately dropped. After a snapshot is deleted, a
2086 new one may be created with the same name, but the new one has
2087 no association with the old snapshot or its subscription, unless
2088 the same subscription is specified.
2090 .. code-block:: python
2092 # This snippet has been automatically generated and should be regarded as a
2093 # code template only.
2094 # It will require modifications to work:
2095 # - It may require correct/in-range values for request initialization.
2096 # - It may require specifying regional endpoints when creating the service
2097 # client as shown in:
2098 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2099 from google import pubsub_v1
2101 async def sample_delete_snapshot():
2102 # Create a client
2103 client = pubsub_v1.SubscriberAsyncClient()
2105 # Initialize request argument(s)
2106 request = pubsub_v1.DeleteSnapshotRequest(
2107 snapshot="snapshot_value",
2108 )
2110 # Make the request
2111 await client.delete_snapshot(request=request)
2113 Args:
2114 request (Optional[Union[google.pubsub_v1.types.DeleteSnapshotRequest, dict]]):
2115 The request object. Request for the ``DeleteSnapshot`` method.
2116 snapshot (:class:`str`):
2117 Required. The name of the snapshot to delete. Format is
2118 ``projects/{project}/snapshots/{snap}``.
2120 This corresponds to the ``snapshot`` field
2121 on the ``request`` instance; if ``request`` is provided, this
2122 should not be set.
2123 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2124 should be retried.
2125 timeout (float): The timeout for this request.
2126 metadata (Sequence[Tuple[str, str]]): Strings which should be
2127 sent along with the request as metadata.
2128 """
2129 # Create or coerce a protobuf request object.
2130 # Quick check: If we got a request object, we should *not* have
2131 # gotten any keyword arguments that map to the request.
2132 has_flattened_params = any([snapshot])
2133 if request is not None and has_flattened_params:
2134 raise ValueError(
2135 "If the `request` argument is set, then none of "
2136 "the individual field arguments should be set."
2137 )
2139 request = pubsub.DeleteSnapshotRequest(request)
2141 # If we have keyword arguments corresponding to fields on the
2142 # request, apply these.
2143 if snapshot is not None:
2144 request.snapshot = snapshot
2146 # Wrap the RPC method; this adds retry and timeout information,
2147 # and friendly error handling.
2148 rpc = gapic_v1.method_async.wrap_method(
2149 self._client._transport.delete_snapshot,
2150 default_retry=retries.Retry(
2151 initial=0.1,
2152 maximum=60.0,
2153 multiplier=1.3,
2154 predicate=retries.if_exception_type(
2155 core_exceptions.ServiceUnavailable,
2156 ),
2157 deadline=60.0,
2158 ),
2159 default_timeout=60.0,
2160 client_info=DEFAULT_CLIENT_INFO,
2161 )
2163 # Certain fields should be provided within the metadata header;
2164 # add these here.
2165 metadata = tuple(metadata) + (
2166 gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)),
2167 )
2169 # Send the request.
2170 await rpc(
2171 request,
2172 retry=retry,
2173 timeout=timeout,
2174 metadata=metadata,
2175 )
2177 async def seek(
2178 self,
2179 request: Optional[Union[pubsub.SeekRequest, dict]] = None,
2180 *,
2181 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2182 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2183 metadata: Sequence[Tuple[str, str]] = (),
2184 ) -> pubsub.SeekResponse:
2185 r"""Seeks an existing subscription to a point in time or to a given
2186 snapshot, whichever is provided in the request. Snapshots are
2187 used in [Seek]
2188 (https://cloud.google.com/pubsub/docs/replay-overview)
2189 operations, which allow you to manage message acknowledgments in
2190 bulk. That is, you can set the acknowledgment state of messages
2191 in an existing subscription to the state captured by a snapshot.
2192 Note that both the subscription and the snapshot must be on the
2193 same topic.
2195 .. code-block:: python
2197 # This snippet has been automatically generated and should be regarded as a
2198 # code template only.
2199 # It will require modifications to work:
2200 # - It may require correct/in-range values for request initialization.
2201 # - It may require specifying regional endpoints when creating the service
2202 # client as shown in:
2203 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2204 from google import pubsub_v1
2206 async def sample_seek():
2207 # Create a client
2208 client = pubsub_v1.SubscriberAsyncClient()
2210 # Initialize request argument(s)
2211 request = pubsub_v1.SeekRequest(
2212 subscription="subscription_value",
2213 )
2215 # Make the request
2216 response = await client.seek(request=request)
2218 # Handle the response
2219 print(response)
2221 Args:
2222 request (Optional[Union[google.pubsub_v1.types.SeekRequest, dict]]):
2223 The request object. Request for the ``Seek`` method.
2224 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2225 should be retried.
2226 timeout (float): The timeout for this request.
2227 metadata (Sequence[Tuple[str, str]]): Strings which should be
2228 sent along with the request as metadata.
2230 Returns:
2231 google.pubsub_v1.types.SeekResponse:
2232 Response for the Seek method (this response is empty).
2233 """
2234 # Create or coerce a protobuf request object.
2235 request = pubsub.SeekRequest(request)
2237 # Wrap the RPC method; this adds retry and timeout information,
2238 # and friendly error handling.
2239 rpc = gapic_v1.method_async.wrap_method(
2240 self._client._transport.seek,
2241 default_retry=retries.Retry(
2242 initial=0.1,
2243 maximum=60.0,
2244 multiplier=1.3,
2245 predicate=retries.if_exception_type(
2246 core_exceptions.Aborted,
2247 core_exceptions.ServiceUnavailable,
2248 core_exceptions.Unknown,
2249 ),
2250 deadline=60.0,
2251 ),
2252 default_timeout=60.0,
2253 client_info=DEFAULT_CLIENT_INFO,
2254 )
2256 # Certain fields should be provided within the metadata header;
2257 # add these here.
2258 metadata = tuple(metadata) + (
2259 gapic_v1.routing_header.to_grpc_metadata(
2260 (("subscription", request.subscription),)
2261 ),
2262 )
2264 # Send the request.
2265 response = await rpc(
2266 request,
2267 retry=retry,
2268 timeout=timeout,
2269 metadata=metadata,
2270 )
2272 # Done; return the response.
2273 return response
2275 async def set_iam_policy(
2276 self,
2277 request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None,
2278 *,
2279 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2280 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2281 metadata: Sequence[Tuple[str, str]] = (),
2282 ) -> policy_pb2.Policy:
2283 r"""Sets the IAM access control policy on the specified function.
2285 Replaces any existing policy.
2287 Args:
2288 request (:class:`~.policy_pb2.SetIamPolicyRequest`):
2289 The request object. Request message for `SetIamPolicy`
2290 method.
2291 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2292 should be retried.
2293 timeout (float): The timeout for this request.
2294 metadata (Sequence[Tuple[str, str]]): Strings which should be
2295 sent along with the request as metadata.
2296 Returns:
2297 ~.policy_pb2.Policy:
2298 Defines an Identity and Access Management (IAM) policy.
2299 It is used to specify access control policies for Cloud
2300 Platform resources.
2301 A ``Policy`` is a collection of ``bindings``. A
2302 ``binding`` binds one or more ``members`` to a single
2303 ``role``. Members can be user accounts, service
2304 accounts, Google groups, and domains (such as G Suite).
2305 A ``role`` is a named list of permissions (defined by
2306 IAM or configured by users). A ``binding`` can
2307 optionally specify a ``condition``, which is a logic
2308 expression that further constrains the role binding
2309 based on attributes about the request and/or target
2310 resource.
2312 **JSON Example**
2314 ::
2315 {
2316 "bindings": [
2317 {
2318 "role": "roles/resourcemanager.organizationAdmin",
2319 "members": [
2320 "user:mike@example.com",
2321 "group:admins@example.com",
2322 "domain:google.com",
2323 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
2324 ]
2325 },
2326 {
2327 "role": "roles/resourcemanager.organizationViewer",
2328 "members": ["user:eve@example.com"],
2329 "condition": {
2330 "title": "expirable access",
2331 "description": "Does not grant access after Sep 2020",
2332 "expression": "request.time <
2333 timestamp('2020-10-01T00:00:00.000Z')",
2334 }
2335 }
2336 ]
2337 }
2339 **YAML Example**
2341 ::
2343 bindings:
2344 - members:
2345 - user:mike@example.com
2346 - group:admins@example.com
2347 - domain:google.com
2348 - serviceAccount:my-project-id@appspot.gserviceaccount.com
2349 role: roles/resourcemanager.organizationAdmin
2350 - members:
2351 - user:eve@example.com
2352 role: roles/resourcemanager.organizationViewer
2353 condition:
2354 title: expirable access
2355 description: Does not grant access after Sep 2020
2356 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
2358 For a description of IAM and its features, see the `IAM
2359 developer's
2360 guide <https://cloud.google.com/iam/docs>`__.
2361 """
2362 # Create or coerce a protobuf request object.
2364 # The request isn't a proto-plus wrapped type,
2365 # so it must be constructed via keyword expansion.
2366 if isinstance(request, dict):
2367 request = iam_policy_pb2.SetIamPolicyRequest(**request)
2369 # Wrap the RPC method; this adds retry and timeout information,
2370 # and friendly error handling.
2371 rpc = gapic_v1.method_async.wrap_method(
2372 self._client._transport.set_iam_policy,
2373 default_timeout=None,
2374 client_info=DEFAULT_CLIENT_INFO,
2375 )
2377 # Certain fields should be provided within the metadata header;
2378 # add these here.
2379 metadata = tuple(metadata) + (
2380 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2381 )
2383 # Send the request.
2384 response = await rpc(
2385 request,
2386 retry=retry,
2387 timeout=timeout,
2388 metadata=metadata,
2389 )
2391 # Done; return the response.
2392 return response
2394 async def get_iam_policy(
2395 self,
2396 request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None,
2397 *,
2398 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2399 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2400 metadata: Sequence[Tuple[str, str]] = (),
2401 ) -> policy_pb2.Policy:
2402 r"""Gets the IAM access control policy for a function.
2404 Returns an empty policy if the function exists and does
2405 not have a policy set.
2407 Args:
2408 request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`):
2409 The request object. Request message for `GetIamPolicy`
2410 method.
2411 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2412 should be retried.
2413 timeout (float): The timeout for this request.
2414 metadata (Sequence[Tuple[str, str]]): Strings which should be
2415 sent along with the request as metadata.
2416 Returns:
2417 ~.policy_pb2.Policy:
2418 Defines an Identity and Access Management (IAM) policy.
2419 It is used to specify access control policies for Cloud
2420 Platform resources.
2421 A ``Policy`` is a collection of ``bindings``. A
2422 ``binding`` binds one or more ``members`` to a single
2423 ``role``. Members can be user accounts, service
2424 accounts, Google groups, and domains (such as G Suite).
2425 A ``role`` is a named list of permissions (defined by
2426 IAM or configured by users). A ``binding`` can
2427 optionally specify a ``condition``, which is a logic
2428 expression that further constrains the role binding
2429 based on attributes about the request and/or target
2430 resource.
2432 **JSON Example**
2434 ::
2436 {
2437 "bindings": [
2438 {
2439 "role": "roles/resourcemanager.organizationAdmin",
2440 "members": [
2441 "user:mike@example.com",
2442 "group:admins@example.com",
2443 "domain:google.com",
2444 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
2445 ]
2446 },
2447 {
2448 "role": "roles/resourcemanager.organizationViewer",
2449 "members": ["user:eve@example.com"],
2450 "condition": {
2451 "title": "expirable access",
2452 "description": "Does not grant access after Sep 2020",
2453 "expression": "request.time <
2454 timestamp('2020-10-01T00:00:00.000Z')",
2455 }
2456 }
2457 ]
2458 }
2460 **YAML Example**
2462 ::
2464 bindings:
2465 - members:
2466 - user:mike@example.com
2467 - group:admins@example.com
2468 - domain:google.com
2469 - serviceAccount:my-project-id@appspot.gserviceaccount.com
2470 role: roles/resourcemanager.organizationAdmin
2471 - members:
2472 - user:eve@example.com
2473 role: roles/resourcemanager.organizationViewer
2474 condition:
2475 title: expirable access
2476 description: Does not grant access after Sep 2020
2477 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
2479 For a description of IAM and its features, see the `IAM
2480 developer's
2481 guide <https://cloud.google.com/iam/docs>`__.
2482 """
2483 # Create or coerce a protobuf request object.
2485 # The request isn't a proto-plus wrapped type,
2486 # so it must be constructed via keyword expansion.
2487 if isinstance(request, dict):
2488 request = iam_policy_pb2.GetIamPolicyRequest(**request)
2490 # Wrap the RPC method; this adds retry and timeout information,
2491 # and friendly error handling.
2492 rpc = gapic_v1.method_async.wrap_method(
2493 self._client._transport.get_iam_policy,
2494 default_timeout=None,
2495 client_info=DEFAULT_CLIENT_INFO,
2496 )
2498 # Certain fields should be provided within the metadata header;
2499 # add these here.
2500 metadata = tuple(metadata) + (
2501 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2502 )
2504 # Send the request.
2505 response = await rpc(
2506 request,
2507 retry=retry,
2508 timeout=timeout,
2509 metadata=metadata,
2510 )
2512 # Done; return the response.
2513 return response
2515 async def test_iam_permissions(
2516 self,
2517 request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None,
2518 *,
2519 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2520 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2521 metadata: Sequence[Tuple[str, str]] = (),
2522 ) -> iam_policy_pb2.TestIamPermissionsResponse:
2523 r"""Tests the specified permissions against the IAM access control
2524 policy for a function.
2526 If the function does not exist, this will
2527 return an empty set of permissions, not a NOT_FOUND error.
2529 Args:
2530 request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`):
2531 The request object. Request message for
2532 `TestIamPermissions` method.
2533 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2534 should be retried.
2535 timeout (float): The timeout for this request.
2536 metadata (Sequence[Tuple[str, str]]): Strings which should be
2537 sent along with the request as metadata.
2538 Returns:
2539 ~iam_policy_pb2.PolicyTestIamPermissionsResponse:
2540 Response message for ``TestIamPermissions`` method.
2541 """
2542 # Create or coerce a protobuf request object.
2544 # The request isn't a proto-plus wrapped type,
2545 # so it must be constructed via keyword expansion.
2546 if isinstance(request, dict):
2547 request = iam_policy_pb2.TestIamPermissionsRequest(**request)
2549 # Wrap the RPC method; this adds retry and timeout information,
2550 # and friendly error handling.
2551 rpc = gapic_v1.method_async.wrap_method(
2552 self._client._transport.test_iam_permissions,
2553 default_timeout=None,
2554 client_info=DEFAULT_CLIENT_INFO,
2555 )
2557 # Certain fields should be provided within the metadata header;
2558 # add these here.
2559 metadata = tuple(metadata) + (
2560 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2561 )
2563 # Send the request.
2564 response = await rpc(
2565 request,
2566 retry=retry,
2567 timeout=timeout,
2568 metadata=metadata,
2569 )
2571 # Done; return the response.
2572 return response
2574 async def __aenter__(self):
2575 return self
2577 async def __aexit__(self, exc_type, exc, tb):
2578 await self.transport.close()
2581DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
2582 client_library_version=package_version.__version__
2583)
2586__all__ = ("SubscriberAsyncClient",)