Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/google/pubsub_v1/services/subscriber/client.py: 28%
403 statements
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:25 +0000
« prev ^ index » next coverage.py v7.2.2, created at 2023-03-26 06:25 +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 os
19import re
20from typing import (
21 Dict,
22 Mapping,
23 MutableMapping,
24 MutableSequence,
25 Optional,
26 Iterable,
27 Iterator,
28 Sequence,
29 Tuple,
30 Type,
31 Union,
32 cast,
33)
35import warnings
36from google.pubsub_v1 import gapic_version as package_version
38from google.api_core import client_options as client_options_lib
39from google.api_core import exceptions as core_exceptions
40from google.api_core import gapic_v1
41from google.api_core import retry as retries
42from google.auth import credentials as ga_credentials # type: ignore
43from google.auth.transport import mtls # type: ignore
44from google.auth.transport.grpc import SslCredentials # type: ignore
45from google.auth.exceptions import MutualTLSChannelError # type: ignore
46from google.oauth2 import service_account # type: ignore
48try:
49 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault]
50except AttributeError: # pragma: NO COVER
51 OptionalRetry = Union[retries.Retry, object] # type: ignore
53from google.iam.v1 import iam_policy_pb2 # type: ignore
54from google.iam.v1 import policy_pb2 # type: ignore
55from google.protobuf import duration_pb2 # type: ignore
56from google.protobuf import field_mask_pb2 # type: ignore
57from google.protobuf import timestamp_pb2 # type: ignore
58from google.pubsub_v1.services.subscriber import pagers
59from google.pubsub_v1.types import pubsub
61import grpc
62from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO
63from .transports.grpc import SubscriberGrpcTransport
64from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport
67class SubscriberClientMeta(type):
68 """Metaclass for the Subscriber client.
70 This provides class-level methods for building and retrieving
71 support objects (e.g. transport) without polluting the client instance
72 objects.
73 """
75 _transport_registry = OrderedDict() # type: Dict[str, Type[SubscriberTransport]]
76 _transport_registry["grpc"] = SubscriberGrpcTransport
77 _transport_registry["grpc_asyncio"] = SubscriberGrpcAsyncIOTransport
79 def get_transport_class(
80 cls,
81 label: Optional[str] = None,
82 ) -> Type[SubscriberTransport]:
83 """Returns an appropriate transport class.
85 Args:
86 label: The name of the desired transport. If none is
87 provided, then the first transport in the registry is used.
89 Returns:
90 The transport class to use.
91 """
92 # If a specific transport is requested, return that one.
93 if label:
94 return cls._transport_registry[label]
96 # No transport is requested; return the default (that is, the first one
97 # in the dictionary).
98 return next(iter(cls._transport_registry.values()))
101class SubscriberClient(metaclass=SubscriberClientMeta):
102 """The service that an application uses to manipulate subscriptions and
103 to consume messages from a subscription via the ``Pull`` method or
104 by establishing a bi-directional stream using the ``StreamingPull``
105 method.
106 """
108 @staticmethod
109 def _get_default_mtls_endpoint(api_endpoint):
110 """Converts api endpoint to mTLS endpoint.
112 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
113 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
114 Args:
115 api_endpoint (Optional[str]): the api endpoint to convert.
116 Returns:
117 str: converted mTLS api endpoint.
118 """
119 if not api_endpoint:
120 return api_endpoint
122 mtls_endpoint_re = re.compile(
123 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
124 )
126 m = mtls_endpoint_re.match(api_endpoint)
127 name, mtls, sandbox, googledomain = m.groups()
128 if mtls or not googledomain:
129 return api_endpoint
131 if sandbox:
132 return api_endpoint.replace(
133 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
134 )
136 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
138 # The scopes needed to make gRPC calls to all of the methods defined in
139 # this service
140 _DEFAULT_SCOPES = (
141 "https://www.googleapis.com/auth/cloud-platform",
142 "https://www.googleapis.com/auth/pubsub",
143 )
145 SERVICE_ADDRESS = "pubsub.googleapis.com:443"
146 """The default address of the service."""
148 DEFAULT_ENDPOINT = "pubsub.googleapis.com"
149 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
150 DEFAULT_ENDPOINT
151 )
153 @classmethod
154 def from_service_account_info(cls, info: dict, *args, **kwargs):
155 """Creates an instance of this client using the provided credentials
156 info.
158 Args:
159 info (dict): The service account private key info.
160 args: Additional arguments to pass to the constructor.
161 kwargs: Additional arguments to pass to the constructor.
163 Returns:
164 SubscriberClient: The constructed client.
165 """
166 credentials = service_account.Credentials.from_service_account_info(info)
167 kwargs["credentials"] = credentials
168 return cls(*args, **kwargs)
170 @classmethod
171 def from_service_account_file(cls, filename: str, *args, **kwargs):
172 """Creates an instance of this client using the provided credentials
173 file.
175 Args:
176 filename (str): The path to the service account private key json
177 file.
178 args: Additional arguments to pass to the constructor.
179 kwargs: Additional arguments to pass to the constructor.
181 Returns:
182 SubscriberClient: The constructed client.
183 """
184 credentials = service_account.Credentials.from_service_account_file(filename)
185 kwargs["credentials"] = credentials
186 return cls(*args, **kwargs)
188 from_service_account_json = from_service_account_file
190 @property
191 def transport(self) -> SubscriberTransport:
192 """Returns the transport used by the client instance.
194 Returns:
195 SubscriberTransport: The transport used by the client
196 instance.
197 """
198 return self._transport
200 @staticmethod
201 def snapshot_path(
202 project: str,
203 snapshot: str,
204 ) -> str:
205 """Returns a fully-qualified snapshot string."""
206 return "projects/{project}/snapshots/{snapshot}".format(
207 project=project,
208 snapshot=snapshot,
209 )
211 @staticmethod
212 def parse_snapshot_path(path: str) -> Dict[str, str]:
213 """Parses a snapshot path into its component segments."""
214 m = re.match(r"^projects/(?P<project>.+?)/snapshots/(?P<snapshot>.+?)$", path)
215 return m.groupdict() if m else {}
217 @staticmethod
218 def subscription_path(
219 project: str,
220 subscription: str,
221 ) -> str:
222 """Returns a fully-qualified subscription string."""
223 return "projects/{project}/subscriptions/{subscription}".format(
224 project=project,
225 subscription=subscription,
226 )
228 @staticmethod
229 def parse_subscription_path(path: str) -> Dict[str, str]:
230 """Parses a subscription path into its component segments."""
231 m = re.match(
232 r"^projects/(?P<project>.+?)/subscriptions/(?P<subscription>.+?)$", path
233 )
234 return m.groupdict() if m else {}
236 @staticmethod
237 def topic_path(
238 project: str,
239 topic: str,
240 ) -> str:
241 """Returns a fully-qualified topic string."""
242 return "projects/{project}/topics/{topic}".format(
243 project=project,
244 topic=topic,
245 )
247 @staticmethod
248 def parse_topic_path(path: str) -> Dict[str, str]:
249 """Parses a topic path into its component segments."""
250 m = re.match(r"^projects/(?P<project>.+?)/topics/(?P<topic>.+?)$", path)
251 return m.groupdict() if m else {}
253 @staticmethod
254 def common_billing_account_path(
255 billing_account: str,
256 ) -> str:
257 """Returns a fully-qualified billing_account string."""
258 return "billingAccounts/{billing_account}".format(
259 billing_account=billing_account,
260 )
262 @staticmethod
263 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
264 """Parse a billing_account path into its component segments."""
265 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
266 return m.groupdict() if m else {}
268 @staticmethod
269 def common_folder_path(
270 folder: str,
271 ) -> str:
272 """Returns a fully-qualified folder string."""
273 return "folders/{folder}".format(
274 folder=folder,
275 )
277 @staticmethod
278 def parse_common_folder_path(path: str) -> Dict[str, str]:
279 """Parse a folder path into its component segments."""
280 m = re.match(r"^folders/(?P<folder>.+?)$", path)
281 return m.groupdict() if m else {}
283 @staticmethod
284 def common_organization_path(
285 organization: str,
286 ) -> str:
287 """Returns a fully-qualified organization string."""
288 return "organizations/{organization}".format(
289 organization=organization,
290 )
292 @staticmethod
293 def parse_common_organization_path(path: str) -> Dict[str, str]:
294 """Parse a organization path into its component segments."""
295 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
296 return m.groupdict() if m else {}
298 @staticmethod
299 def common_project_path(
300 project: str,
301 ) -> str:
302 """Returns a fully-qualified project string."""
303 return "projects/{project}".format(
304 project=project,
305 )
307 @staticmethod
308 def parse_common_project_path(path: str) -> Dict[str, str]:
309 """Parse a project path into its component segments."""
310 m = re.match(r"^projects/(?P<project>.+?)$", path)
311 return m.groupdict() if m else {}
313 @staticmethod
314 def common_location_path(
315 project: str,
316 location: str,
317 ) -> str:
318 """Returns a fully-qualified location string."""
319 return "projects/{project}/locations/{location}".format(
320 project=project,
321 location=location,
322 )
324 @staticmethod
325 def parse_common_location_path(path: str) -> Dict[str, str]:
326 """Parse a location path into its component segments."""
327 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
328 return m.groupdict() if m else {}
330 @classmethod
331 def get_mtls_endpoint_and_cert_source(
332 cls, client_options: Optional[client_options_lib.ClientOptions] = None
333 ):
334 """Return the API endpoint and client cert source for mutual TLS.
336 The client cert source is determined in the following order:
337 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
338 client cert source is None.
339 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
340 default client cert source exists, use the default one; otherwise the client cert
341 source is None.
343 The API endpoint is determined in the following order:
344 (1) if `client_options.api_endpoint` if provided, use the provided one.
345 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
346 default mTLS endpoint; if the environment variable is "never", use the default API
347 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
348 use the default API endpoint.
350 More details can be found at https://google.aip.dev/auth/4114.
352 Args:
353 client_options (google.api_core.client_options.ClientOptions): Custom options for the
354 client. Only the `api_endpoint` and `client_cert_source` properties may be used
355 in this method.
357 Returns:
358 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
359 client cert source to use.
361 Raises:
362 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
363 """
364 if client_options is None:
365 client_options = client_options_lib.ClientOptions()
366 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
367 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
368 if use_client_cert not in ("true", "false"):
369 raise ValueError(
370 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
371 )
372 if use_mtls_endpoint not in ("auto", "never", "always"):
373 raise MutualTLSChannelError(
374 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
375 )
377 # Figure out the client cert source to use.
378 client_cert_source = None
379 if use_client_cert == "true":
380 if client_options.client_cert_source:
381 client_cert_source = client_options.client_cert_source
382 elif mtls.has_default_client_cert_source():
383 client_cert_source = mtls.default_client_cert_source()
385 # Figure out which api endpoint to use.
386 if client_options.api_endpoint is not None:
387 api_endpoint = client_options.api_endpoint
388 elif use_mtls_endpoint == "always" or (
389 use_mtls_endpoint == "auto" and client_cert_source
390 ):
391 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
392 else:
393 api_endpoint = cls.DEFAULT_ENDPOINT
395 return api_endpoint, client_cert_source
397 def __init__(
398 self,
399 *,
400 credentials: Optional[ga_credentials.Credentials] = None,
401 transport: Optional[Union[str, SubscriberTransport]] = None,
402 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
403 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
404 ) -> None:
405 """Instantiates the subscriber client.
407 Args:
408 credentials (Optional[google.auth.credentials.Credentials]): The
409 authorization credentials to attach to requests. These
410 credentials identify the application to the service; if none
411 are specified, the client will attempt to ascertain the
412 credentials from the environment.
413 transport (Union[str, SubscriberTransport]): The
414 transport to use. If set to None, a transport is chosen
415 automatically.
416 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the
417 client. It won't take effect if a ``transport`` instance is provided.
418 (1) The ``api_endpoint`` property can be used to override the
419 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT
420 environment variable can also be used to override the endpoint:
421 "always" (always use the default mTLS endpoint), "never" (always
422 use the default regular endpoint) and "auto" (auto switch to the
423 default mTLS endpoint if client certificate is present, this is
424 the default value). However, the ``api_endpoint`` property takes
425 precedence if provided.
426 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
427 is "true", then the ``client_cert_source`` property can be used
428 to provide client certificate for mutual TLS transport. If
429 not provided, the default SSL client certificate will be used if
430 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
431 set, no client certificate will be used.
432 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
433 The client info used to send a user-agent string along with
434 API requests. If ``None``, then default info will be used.
435 Generally, you only need to set this if you're developing
436 your own client library.
438 Raises:
439 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
440 creation failed for any reason.
441 """
442 if isinstance(client_options, dict):
443 client_options = client_options_lib.from_dict(client_options)
444 if client_options is None:
445 client_options = client_options_lib.ClientOptions()
446 client_options = cast(client_options_lib.ClientOptions, client_options)
448 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source(
449 client_options
450 )
452 api_key_value = getattr(client_options, "api_key", None)
453 if api_key_value and credentials:
454 raise ValueError(
455 "client_options.api_key and credentials are mutually exclusive"
456 )
458 # Save or instantiate the transport.
459 # Ordinarily, we provide the transport, but allowing a custom transport
460 # instance provides an extensibility point for unusual situations.
461 if isinstance(transport, SubscriberTransport):
462 # transport is a SubscriberTransport instance.
463 if credentials or client_options.credentials_file or api_key_value:
464 raise ValueError(
465 "When providing a transport instance, "
466 "provide its credentials directly."
467 )
468 if client_options.scopes:
469 raise ValueError(
470 "When providing a transport instance, provide its scopes "
471 "directly."
472 )
473 self._transport = transport
474 else:
475 import google.auth._default # type: ignore
477 if api_key_value and hasattr(
478 google.auth._default, "get_api_key_credentials"
479 ):
480 credentials = google.auth._default.get_api_key_credentials(
481 api_key_value
482 )
484 Transport = type(self).get_transport_class(transport)
486 emulator_host = os.environ.get("PUBSUB_EMULATOR_HOST")
487 if emulator_host:
488 if issubclass(Transport, type(self)._transport_registry["grpc"]):
489 channel = grpc.insecure_channel(target=emulator_host)
490 else:
491 channel = grpc.aio.insecure_channel(target=emulator_host)
492 Transport = functools.partial(Transport, channel=channel)
494 self._transport = Transport(
495 credentials=credentials,
496 credentials_file=client_options.credentials_file,
497 host=api_endpoint,
498 scopes=client_options.scopes,
499 client_cert_source_for_mtls=client_cert_source_func,
500 quota_project_id=client_options.quota_project_id,
501 client_info=client_info,
502 always_use_jwt_access=True,
503 api_audience=client_options.api_audience,
504 )
506 def create_subscription(
507 self,
508 request: Optional[Union[pubsub.Subscription, dict]] = None,
509 *,
510 name: Optional[str] = None,
511 topic: Optional[str] = None,
512 push_config: Optional[pubsub.PushConfig] = None,
513 ack_deadline_seconds: Optional[int] = None,
514 retry: OptionalRetry = gapic_v1.method.DEFAULT,
515 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
516 metadata: Sequence[Tuple[str, str]] = (),
517 ) -> pubsub.Subscription:
518 r"""Creates a subscription to a given topic. See the [resource name
519 rules]
520 (https://cloud.google.com/pubsub/docs/admin#resource_names). If
521 the subscription already exists, returns ``ALREADY_EXISTS``. If
522 the corresponding topic doesn't exist, returns ``NOT_FOUND``.
524 If the name is not provided in the request, the server will
525 assign a random name for this subscription on the same project
526 as the topic, conforming to the [resource name format]
527 (https://cloud.google.com/pubsub/docs/admin#resource_names). The
528 generated name is populated in the returned Subscription object.
529 Note that for REST API requests, you must specify a name in the
530 request.
532 .. code-block:: python
534 # This snippet has been automatically generated and should be regarded as a
535 # code template only.
536 # It will require modifications to work:
537 # - It may require correct/in-range values for request initialization.
538 # - It may require specifying regional endpoints when creating the service
539 # client as shown in:
540 # https://googleapis.dev/python/google-api-core/latest/client_options.html
541 from google import pubsub_v1
543 def sample_create_subscription():
544 # Create a client
545 client = pubsub_v1.SubscriberClient()
547 # Initialize request argument(s)
548 request = pubsub_v1.Subscription(
549 name="name_value",
550 topic="topic_value",
551 )
553 # Make the request
554 response = client.create_subscription(request=request)
556 # Handle the response
557 print(response)
559 Args:
560 request (Union[google.pubsub_v1.types.Subscription, dict]):
561 The request object. A subscription resource. If none of
562 `push_config` or `bigquery_config` is set, then the
563 subscriber will pull and ack messages using API methods.
564 At most one of these fields may be set.
565 name (str):
566 Required. The name of the subscription. It must have the
567 format
568 ``"projects/{project}/subscriptions/{subscription}"``.
569 ``{subscription}`` must start with a letter, and contain
570 only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes
571 (``-``), underscores (``_``), periods (``.``), tildes
572 (``~``), plus (``+``) or percent signs (``%``). It must
573 be between 3 and 255 characters in length, and it must
574 not start with ``"goog"``.
576 This corresponds to the ``name`` field
577 on the ``request`` instance; if ``request`` is provided, this
578 should not be set.
579 topic (str):
580 Required. The name of the topic from which this
581 subscription is receiving messages. Format is
582 ``projects/{project}/topics/{topic}``. The value of this
583 field will be ``_deleted-topic_`` if the topic has been
584 deleted.
586 This corresponds to the ``topic`` field
587 on the ``request`` instance; if ``request`` is provided, this
588 should not be set.
589 push_config (google.pubsub_v1.types.PushConfig):
590 If push delivery is used with this
591 subscription, this field is used to
592 configure it.
594 This corresponds to the ``push_config`` field
595 on the ``request`` instance; if ``request`` is provided, this
596 should not be set.
597 ack_deadline_seconds (int):
598 The approximate amount of time (on a best-effort basis)
599 Pub/Sub waits for the subscriber to acknowledge receipt
600 before resending the message. In the interval after the
601 message is delivered and before it is acknowledged, it
602 is considered to be *outstanding*. During that time
603 period, the message will not be redelivered (on a
604 best-effort basis).
606 For pull subscriptions, this value is used as the
607 initial value for the ack deadline. To override this
608 value for a given message, call ``ModifyAckDeadline``
609 with the corresponding ``ack_id`` if using non-streaming
610 pull or send the ``ack_id`` in a
611 ``StreamingModifyAckDeadlineRequest`` if using streaming
612 pull. The minimum custom deadline you can specify is 10
613 seconds. The maximum custom deadline you can specify is
614 600 seconds (10 minutes). If this parameter is 0, a
615 default value of 10 seconds is used.
617 For push delivery, this value is also used to set the
618 request timeout for the call to the push endpoint.
620 If the subscriber never acknowledges the message, the
621 Pub/Sub system will eventually redeliver the message.
623 This corresponds to the ``ack_deadline_seconds`` field
624 on the ``request`` instance; if ``request`` is provided, this
625 should not be set.
626 retry (google.api_core.retry.Retry): Designation of what errors, if any,
627 should be retried.
628 timeout (float): The timeout for this request.
629 metadata (Sequence[Tuple[str, str]]): Strings which should be
630 sent along with the request as metadata.
632 Returns:
633 google.pubsub_v1.types.Subscription:
634 A subscription resource. If none of push_config or bigquery_config is
635 set, then the subscriber will pull and ack messages
636 using API methods. At most one of these fields may be
637 set.
639 """
640 # Create or coerce a protobuf request object.
641 # Quick check: If we got a request object, we should *not* have
642 # gotten any keyword arguments that map to the request.
643 has_flattened_params = any([name, topic, push_config, ack_deadline_seconds])
644 if request is not None and has_flattened_params:
645 raise ValueError(
646 "If the `request` argument is set, then none of "
647 "the individual field arguments should be set."
648 )
650 # Minor optimization to avoid making a copy if the user passes
651 # in a pubsub.Subscription.
652 # There's no risk of modifying the input as we've already verified
653 # there are no flattened fields.
654 if not isinstance(request, pubsub.Subscription):
655 request = pubsub.Subscription(request)
656 # If we have keyword arguments corresponding to fields on the
657 # request, apply these.
658 if name is not None:
659 request.name = name
660 if topic is not None:
661 request.topic = topic
662 if push_config is not None:
663 request.push_config = push_config
664 if ack_deadline_seconds is not None:
665 request.ack_deadline_seconds = ack_deadline_seconds
667 # Wrap the RPC method; this adds retry and timeout information,
668 # and friendly error handling.
669 rpc = self._transport._wrapped_methods[self._transport.create_subscription]
671 # Certain fields should be provided within the metadata header;
672 # add these here.
673 metadata = tuple(metadata) + (
674 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
675 )
677 # Send the request.
678 response = rpc(
679 request,
680 retry=retry,
681 timeout=timeout,
682 metadata=metadata,
683 )
685 # Done; return the response.
686 return response
688 def get_subscription(
689 self,
690 request: Optional[Union[pubsub.GetSubscriptionRequest, dict]] = None,
691 *,
692 subscription: Optional[str] = None,
693 retry: OptionalRetry = gapic_v1.method.DEFAULT,
694 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
695 metadata: Sequence[Tuple[str, str]] = (),
696 ) -> pubsub.Subscription:
697 r"""Gets the configuration details of a subscription.
699 .. code-block:: python
701 # This snippet has been automatically generated and should be regarded as a
702 # code template only.
703 # It will require modifications to work:
704 # - It may require correct/in-range values for request initialization.
705 # - It may require specifying regional endpoints when creating the service
706 # client as shown in:
707 # https://googleapis.dev/python/google-api-core/latest/client_options.html
708 from google import pubsub_v1
710 def sample_get_subscription():
711 # Create a client
712 client = pubsub_v1.SubscriberClient()
714 # Initialize request argument(s)
715 request = pubsub_v1.GetSubscriptionRequest(
716 subscription="subscription_value",
717 )
719 # Make the request
720 response = client.get_subscription(request=request)
722 # Handle the response
723 print(response)
725 Args:
726 request (Union[google.pubsub_v1.types.GetSubscriptionRequest, dict]):
727 The request object. Request for the GetSubscription
728 method.
729 subscription (str):
730 Required. The name of the subscription to get. Format is
731 ``projects/{project}/subscriptions/{sub}``.
733 This corresponds to the ``subscription`` field
734 on the ``request`` instance; if ``request`` is provided, this
735 should not be set.
736 retry (google.api_core.retry.Retry): Designation of what errors, if any,
737 should be retried.
738 timeout (float): The timeout for this request.
739 metadata (Sequence[Tuple[str, str]]): Strings which should be
740 sent along with the request as metadata.
742 Returns:
743 google.pubsub_v1.types.Subscription:
744 A subscription resource. If none of push_config or bigquery_config is
745 set, then the subscriber will pull and ack messages
746 using API methods. At most one of these fields may be
747 set.
749 """
750 # Create or coerce a protobuf request object.
751 # Quick check: If we got a request object, we should *not* have
752 # gotten any keyword arguments that map to the request.
753 has_flattened_params = any([subscription])
754 if request is not None and has_flattened_params:
755 raise ValueError(
756 "If the `request` argument is set, then none of "
757 "the individual field arguments should be set."
758 )
760 # Minor optimization to avoid making a copy if the user passes
761 # in a pubsub.GetSubscriptionRequest.
762 # There's no risk of modifying the input as we've already verified
763 # there are no flattened fields.
764 if not isinstance(request, pubsub.GetSubscriptionRequest):
765 request = pubsub.GetSubscriptionRequest(request)
766 # If we have keyword arguments corresponding to fields on the
767 # request, apply these.
768 if subscription is not None:
769 request.subscription = subscription
771 # Wrap the RPC method; this adds retry and timeout information,
772 # and friendly error handling.
773 rpc = self._transport._wrapped_methods[self._transport.get_subscription]
775 # Certain fields should be provided within the metadata header;
776 # add these here.
777 metadata = tuple(metadata) + (
778 gapic_v1.routing_header.to_grpc_metadata(
779 (("subscription", request.subscription),)
780 ),
781 )
783 # Send the request.
784 response = rpc(
785 request,
786 retry=retry,
787 timeout=timeout,
788 metadata=metadata,
789 )
791 # Done; return the response.
792 return response
794 def update_subscription(
795 self,
796 request: Optional[Union[pubsub.UpdateSubscriptionRequest, dict]] = None,
797 *,
798 subscription: Optional[pubsub.Subscription] = None,
799 update_mask: Optional[field_mask_pb2.FieldMask] = None,
800 retry: OptionalRetry = gapic_v1.method.DEFAULT,
801 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
802 metadata: Sequence[Tuple[str, str]] = (),
803 ) -> pubsub.Subscription:
804 r"""Updates an existing subscription. Note that certain
805 properties of a subscription, such as its topic, are not
806 modifiable.
808 .. code-block:: python
810 # This snippet has been automatically generated and should be regarded as a
811 # code template only.
812 # It will require modifications to work:
813 # - It may require correct/in-range values for request initialization.
814 # - It may require specifying regional endpoints when creating the service
815 # client as shown in:
816 # https://googleapis.dev/python/google-api-core/latest/client_options.html
817 from google import pubsub_v1
819 def sample_update_subscription():
820 # Create a client
821 client = pubsub_v1.SubscriberClient()
823 # Initialize request argument(s)
824 subscription = pubsub_v1.Subscription()
825 subscription.name = "name_value"
826 subscription.topic = "topic_value"
828 request = pubsub_v1.UpdateSubscriptionRequest(
829 subscription=subscription,
830 )
832 # Make the request
833 response = client.update_subscription(request=request)
835 # Handle the response
836 print(response)
838 Args:
839 request (Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]):
840 The request object. Request for the UpdateSubscription
841 method.
842 subscription (google.pubsub_v1.types.Subscription):
843 Required. The updated subscription
844 object.
846 This corresponds to the ``subscription`` field
847 on the ``request`` instance; if ``request`` is provided, this
848 should not be set.
849 update_mask (google.protobuf.field_mask_pb2.FieldMask):
850 Required. Indicates which fields in
851 the provided subscription to update.
852 Must be specified and non-empty.
854 This corresponds to the ``update_mask`` field
855 on the ``request`` instance; if ``request`` is provided, this
856 should not be set.
857 retry (google.api_core.retry.Retry): Designation of what errors, if any,
858 should be retried.
859 timeout (float): The timeout for this request.
860 metadata (Sequence[Tuple[str, str]]): Strings which should be
861 sent along with the request as metadata.
863 Returns:
864 google.pubsub_v1.types.Subscription:
865 A subscription resource. If none of push_config or bigquery_config is
866 set, then the subscriber will pull and ack messages
867 using API methods. At most one of these fields may be
868 set.
870 """
871 # Create or coerce a protobuf request object.
872 # Quick check: If we got a request object, we should *not* have
873 # gotten any keyword arguments that map to the request.
874 has_flattened_params = any([subscription, update_mask])
875 if request is not None and has_flattened_params:
876 raise ValueError(
877 "If the `request` argument is set, then none of "
878 "the individual field arguments should be set."
879 )
881 # Minor optimization to avoid making a copy if the user passes
882 # in a pubsub.UpdateSubscriptionRequest.
883 # There's no risk of modifying the input as we've already verified
884 # there are no flattened fields.
885 if not isinstance(request, pubsub.UpdateSubscriptionRequest):
886 request = pubsub.UpdateSubscriptionRequest(request)
887 # If we have keyword arguments corresponding to fields on the
888 # request, apply these.
889 if subscription is not None:
890 request.subscription = subscription
891 if update_mask is not None:
892 request.update_mask = update_mask
894 # Wrap the RPC method; this adds retry and timeout information,
895 # and friendly error handling.
896 rpc = self._transport._wrapped_methods[self._transport.update_subscription]
898 # Certain fields should be provided within the metadata header;
899 # add these here.
900 metadata = tuple(metadata) + (
901 gapic_v1.routing_header.to_grpc_metadata(
902 (("subscription.name", request.subscription.name),)
903 ),
904 )
906 # Send the request.
907 response = rpc(
908 request,
909 retry=retry,
910 timeout=timeout,
911 metadata=metadata,
912 )
914 # Done; return the response.
915 return response
917 def list_subscriptions(
918 self,
919 request: Optional[Union[pubsub.ListSubscriptionsRequest, dict]] = None,
920 *,
921 project: Optional[str] = None,
922 retry: OptionalRetry = gapic_v1.method.DEFAULT,
923 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
924 metadata: Sequence[Tuple[str, str]] = (),
925 ) -> pagers.ListSubscriptionsPager:
926 r"""Lists matching subscriptions.
928 .. code-block:: python
930 # This snippet has been automatically generated and should be regarded as a
931 # code template only.
932 # It will require modifications to work:
933 # - It may require correct/in-range values for request initialization.
934 # - It may require specifying regional endpoints when creating the service
935 # client as shown in:
936 # https://googleapis.dev/python/google-api-core/latest/client_options.html
937 from google import pubsub_v1
939 def sample_list_subscriptions():
940 # Create a client
941 client = pubsub_v1.SubscriberClient()
943 # Initialize request argument(s)
944 request = pubsub_v1.ListSubscriptionsRequest(
945 project="project_value",
946 )
948 # Make the request
949 page_result = client.list_subscriptions(request=request)
951 # Handle the response
952 for response in page_result:
953 print(response)
955 Args:
956 request (Union[google.pubsub_v1.types.ListSubscriptionsRequest, dict]):
957 The request object. Request for the `ListSubscriptions`
958 method.
959 project (str):
960 Required. The name of the project in which to list
961 subscriptions. Format is ``projects/{project-id}``.
963 This corresponds to the ``project`` field
964 on the ``request`` instance; if ``request`` is provided, this
965 should not be set.
966 retry (google.api_core.retry.Retry): Designation of what errors, if any,
967 should be retried.
968 timeout (float): The timeout for this request.
969 metadata (Sequence[Tuple[str, str]]): Strings which should be
970 sent along with the request as metadata.
972 Returns:
973 google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsPager:
974 Response for the ListSubscriptions method.
976 Iterating over this object will yield results and
977 resolve additional pages automatically.
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([project])
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 # Minor optimization to avoid making a copy if the user passes
991 # in a pubsub.ListSubscriptionsRequest.
992 # There's no risk of modifying the input as we've already verified
993 # there are no flattened fields.
994 if not isinstance(request, pubsub.ListSubscriptionsRequest):
995 request = pubsub.ListSubscriptionsRequest(request)
996 # If we have keyword arguments corresponding to fields on the
997 # request, apply these.
998 if project is not None:
999 request.project = project
1001 # Wrap the RPC method; this adds retry and timeout information,
1002 # and friendly error handling.
1003 rpc = self._transport._wrapped_methods[self._transport.list_subscriptions]
1005 # Certain fields should be provided within the metadata header;
1006 # add these here.
1007 metadata = tuple(metadata) + (
1008 gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)),
1009 )
1011 # Send the request.
1012 response = rpc(
1013 request,
1014 retry=retry,
1015 timeout=timeout,
1016 metadata=metadata,
1017 )
1019 # This method is paged; wrap the response in a pager, which provides
1020 # an `__iter__` convenience method.
1021 response = pagers.ListSubscriptionsPager(
1022 method=rpc,
1023 request=request,
1024 response=response,
1025 metadata=metadata,
1026 )
1028 # Done; return the response.
1029 return response
1031 def delete_subscription(
1032 self,
1033 request: Optional[Union[pubsub.DeleteSubscriptionRequest, dict]] = None,
1034 *,
1035 subscription: Optional[str] = None,
1036 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1037 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1038 metadata: Sequence[Tuple[str, str]] = (),
1039 ) -> None:
1040 r"""Deletes an existing subscription. All messages retained in the
1041 subscription are immediately dropped. Calls to ``Pull`` after
1042 deletion will return ``NOT_FOUND``. After a subscription is
1043 deleted, a new one may be created with the same name, but the
1044 new one has no association with the old subscription or its
1045 topic unless the same topic is specified.
1047 .. code-block:: python
1049 # This snippet has been automatically generated and should be regarded as a
1050 # code template only.
1051 # It will require modifications to work:
1052 # - It may require correct/in-range values for request initialization.
1053 # - It may require specifying regional endpoints when creating the service
1054 # client as shown in:
1055 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1056 from google import pubsub_v1
1058 def sample_delete_subscription():
1059 # Create a client
1060 client = pubsub_v1.SubscriberClient()
1062 # Initialize request argument(s)
1063 request = pubsub_v1.DeleteSubscriptionRequest(
1064 subscription="subscription_value",
1065 )
1067 # Make the request
1068 client.delete_subscription(request=request)
1070 Args:
1071 request (Union[google.pubsub_v1.types.DeleteSubscriptionRequest, dict]):
1072 The request object. Request for the DeleteSubscription
1073 method.
1074 subscription (str):
1075 Required. The subscription to delete. Format is
1076 ``projects/{project}/subscriptions/{sub}``.
1078 This corresponds to the ``subscription`` field
1079 on the ``request`` instance; if ``request`` is provided, this
1080 should not be set.
1081 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1082 should be retried.
1083 timeout (float): The timeout for this request.
1084 metadata (Sequence[Tuple[str, str]]): Strings which should be
1085 sent along with the request as metadata.
1086 """
1087 # Create or coerce a protobuf request object.
1088 # Quick check: If we got a request object, we should *not* have
1089 # gotten any keyword arguments that map to the request.
1090 has_flattened_params = any([subscription])
1091 if request is not None and has_flattened_params:
1092 raise ValueError(
1093 "If the `request` argument is set, then none of "
1094 "the individual field arguments should be set."
1095 )
1097 # Minor optimization to avoid making a copy if the user passes
1098 # in a pubsub.DeleteSubscriptionRequest.
1099 # There's no risk of modifying the input as we've already verified
1100 # there are no flattened fields.
1101 if not isinstance(request, pubsub.DeleteSubscriptionRequest):
1102 request = pubsub.DeleteSubscriptionRequest(request)
1103 # If we have keyword arguments corresponding to fields on the
1104 # request, apply these.
1105 if subscription is not None:
1106 request.subscription = subscription
1108 # Wrap the RPC method; this adds retry and timeout information,
1109 # and friendly error handling.
1110 rpc = self._transport._wrapped_methods[self._transport.delete_subscription]
1112 # Certain fields should be provided within the metadata header;
1113 # add these here.
1114 metadata = tuple(metadata) + (
1115 gapic_v1.routing_header.to_grpc_metadata(
1116 (("subscription", request.subscription),)
1117 ),
1118 )
1120 # Send the request.
1121 rpc(
1122 request,
1123 retry=retry,
1124 timeout=timeout,
1125 metadata=metadata,
1126 )
1128 def modify_ack_deadline(
1129 self,
1130 request: Optional[Union[pubsub.ModifyAckDeadlineRequest, dict]] = None,
1131 *,
1132 subscription: Optional[str] = None,
1133 ack_ids: Optional[MutableSequence[str]] = None,
1134 ack_deadline_seconds: Optional[int] = None,
1135 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1136 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1137 metadata: Sequence[Tuple[str, str]] = (),
1138 ) -> None:
1139 r"""Modifies the ack deadline for a specific message. This method is
1140 useful to indicate that more time is needed to process a message
1141 by the subscriber, or to make the message available for
1142 redelivery if the processing was interrupted. Note that this
1143 does not modify the subscription-level ``ackDeadlineSeconds``
1144 used for subsequent messages.
1146 .. code-block:: python
1148 # This snippet has been automatically generated and should be regarded as a
1149 # code template only.
1150 # It will require modifications to work:
1151 # - It may require correct/in-range values for request initialization.
1152 # - It may require specifying regional endpoints when creating the service
1153 # client as shown in:
1154 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1155 from google import pubsub_v1
1157 def sample_modify_ack_deadline():
1158 # Create a client
1159 client = pubsub_v1.SubscriberClient()
1161 # Initialize request argument(s)
1162 request = pubsub_v1.ModifyAckDeadlineRequest(
1163 subscription="subscription_value",
1164 ack_ids=['ack_ids_value1', 'ack_ids_value2'],
1165 ack_deadline_seconds=2066,
1166 )
1168 # Make the request
1169 client.modify_ack_deadline(request=request)
1171 Args:
1172 request (Union[google.pubsub_v1.types.ModifyAckDeadlineRequest, dict]):
1173 The request object. Request for the ModifyAckDeadline
1174 method.
1175 subscription (str):
1176 Required. The name of the subscription. Format is
1177 ``projects/{project}/subscriptions/{sub}``.
1179 This corresponds to the ``subscription`` field
1180 on the ``request`` instance; if ``request`` is provided, this
1181 should not be set.
1182 ack_ids (MutableSequence[str]):
1183 Required. List of acknowledgment IDs.
1184 This corresponds to the ``ack_ids`` field
1185 on the ``request`` instance; if ``request`` is provided, this
1186 should not be set.
1187 ack_deadline_seconds (int):
1188 Required. The new ack deadline with respect to the time
1189 this request was sent to the Pub/Sub system. For
1190 example, if the value is 10, the new ack deadline will
1191 expire 10 seconds after the ``ModifyAckDeadline`` call
1192 was made. Specifying zero might immediately make the
1193 message available for delivery to another subscriber
1194 client. This typically results in an increase in the
1195 rate of message redeliveries (that is, duplicates). The
1196 minimum deadline you can specify is 0 seconds. The
1197 maximum deadline you can specify is 600 seconds (10
1198 minutes).
1200 This corresponds to the ``ack_deadline_seconds`` field
1201 on the ``request`` instance; if ``request`` is provided, this
1202 should not be set.
1203 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1204 should be retried.
1205 timeout (float): The timeout for this request.
1206 metadata (Sequence[Tuple[str, str]]): Strings which should be
1207 sent along with the request as metadata.
1208 """
1209 # Create or coerce a protobuf request object.
1210 # Quick check: If we got a request object, we should *not* have
1211 # gotten any keyword arguments that map to the request.
1212 has_flattened_params = any([subscription, ack_ids, ack_deadline_seconds])
1213 if request is not None and has_flattened_params:
1214 raise ValueError(
1215 "If the `request` argument is set, then none of "
1216 "the individual field arguments should be set."
1217 )
1219 # Minor optimization to avoid making a copy if the user passes
1220 # in a pubsub.ModifyAckDeadlineRequest.
1221 # There's no risk of modifying the input as we've already verified
1222 # there are no flattened fields.
1223 if not isinstance(request, pubsub.ModifyAckDeadlineRequest):
1224 request = pubsub.ModifyAckDeadlineRequest(request)
1225 # If we have keyword arguments corresponding to fields on the
1226 # request, apply these.
1227 if subscription is not None:
1228 request.subscription = subscription
1229 if ack_ids is not None:
1230 request.ack_ids = ack_ids
1231 if ack_deadline_seconds is not None:
1232 request.ack_deadline_seconds = ack_deadline_seconds
1234 # Wrap the RPC method; this adds retry and timeout information,
1235 # and friendly error handling.
1236 rpc = self._transport._wrapped_methods[self._transport.modify_ack_deadline]
1238 # Certain fields should be provided within the metadata header;
1239 # add these here.
1240 metadata = tuple(metadata) + (
1241 gapic_v1.routing_header.to_grpc_metadata(
1242 (("subscription", request.subscription),)
1243 ),
1244 )
1246 # Send the request.
1247 rpc(
1248 request,
1249 retry=retry,
1250 timeout=timeout,
1251 metadata=metadata,
1252 )
1254 def acknowledge(
1255 self,
1256 request: Optional[Union[pubsub.AcknowledgeRequest, dict]] = None,
1257 *,
1258 subscription: Optional[str] = None,
1259 ack_ids: Optional[MutableSequence[str]] = None,
1260 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1261 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1262 metadata: Sequence[Tuple[str, str]] = (),
1263 ) -> None:
1264 r"""Acknowledges the messages associated with the ``ack_ids`` in the
1265 ``AcknowledgeRequest``. The Pub/Sub system can remove the
1266 relevant messages from the subscription.
1268 Acknowledging a message whose ack deadline has expired may
1269 succeed, but such a message may be redelivered later.
1270 Acknowledging a message more than once will not result in an
1271 error.
1273 .. code-block:: python
1275 # This snippet has been automatically generated and should be regarded as a
1276 # code template only.
1277 # It will require modifications to work:
1278 # - It may require correct/in-range values for request initialization.
1279 # - It may require specifying regional endpoints when creating the service
1280 # client as shown in:
1281 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1282 from google import pubsub_v1
1284 def sample_acknowledge():
1285 # Create a client
1286 client = pubsub_v1.SubscriberClient()
1288 # Initialize request argument(s)
1289 request = pubsub_v1.AcknowledgeRequest(
1290 subscription="subscription_value",
1291 ack_ids=['ack_ids_value1', 'ack_ids_value2'],
1292 )
1294 # Make the request
1295 client.acknowledge(request=request)
1297 Args:
1298 request (Union[google.pubsub_v1.types.AcknowledgeRequest, dict]):
1299 The request object. Request for the Acknowledge method.
1300 subscription (str):
1301 Required. The subscription whose message is being
1302 acknowledged. Format is
1303 ``projects/{project}/subscriptions/{sub}``.
1305 This corresponds to the ``subscription`` field
1306 on the ``request`` instance; if ``request`` is provided, this
1307 should not be set.
1308 ack_ids (MutableSequence[str]):
1309 Required. The acknowledgment ID for the messages being
1310 acknowledged that was returned by the Pub/Sub system in
1311 the ``Pull`` response. Must not be empty.
1313 This corresponds to the ``ack_ids`` field
1314 on the ``request`` instance; if ``request`` is provided, this
1315 should not be set.
1316 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1317 should be retried.
1318 timeout (float): The timeout for this request.
1319 metadata (Sequence[Tuple[str, str]]): Strings which should be
1320 sent along with the request as metadata.
1321 """
1322 # Create or coerce a protobuf request object.
1323 # Quick check: If we got a request object, we should *not* have
1324 # gotten any keyword arguments that map to the request.
1325 has_flattened_params = any([subscription, ack_ids])
1326 if request is not None and has_flattened_params:
1327 raise ValueError(
1328 "If the `request` argument is set, then none of "
1329 "the individual field arguments should be set."
1330 )
1332 # Minor optimization to avoid making a copy if the user passes
1333 # in a pubsub.AcknowledgeRequest.
1334 # There's no risk of modifying the input as we've already verified
1335 # there are no flattened fields.
1336 if not isinstance(request, pubsub.AcknowledgeRequest):
1337 request = pubsub.AcknowledgeRequest(request)
1338 # If we have keyword arguments corresponding to fields on the
1339 # request, apply these.
1340 if subscription is not None:
1341 request.subscription = subscription
1342 if ack_ids is not None:
1343 request.ack_ids = ack_ids
1345 # Wrap the RPC method; this adds retry and timeout information,
1346 # and friendly error handling.
1347 rpc = self._transport._wrapped_methods[self._transport.acknowledge]
1349 # Certain fields should be provided within the metadata header;
1350 # add these here.
1351 metadata = tuple(metadata) + (
1352 gapic_v1.routing_header.to_grpc_metadata(
1353 (("subscription", request.subscription),)
1354 ),
1355 )
1357 # Send the request.
1358 rpc(
1359 request,
1360 retry=retry,
1361 timeout=timeout,
1362 metadata=metadata,
1363 )
1365 def pull(
1366 self,
1367 request: Optional[Union[pubsub.PullRequest, dict]] = None,
1368 *,
1369 subscription: Optional[str] = None,
1370 return_immediately: Optional[bool] = None,
1371 max_messages: Optional[int] = None,
1372 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1373 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1374 metadata: Sequence[Tuple[str, str]] = (),
1375 ) -> pubsub.PullResponse:
1376 r"""Pulls messages from the server.
1378 .. code-block:: python
1380 # This snippet has been automatically generated and should be regarded as a
1381 # code template only.
1382 # It will require modifications to work:
1383 # - It may require correct/in-range values for request initialization.
1384 # - It may require specifying regional endpoints when creating the service
1385 # client as shown in:
1386 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1387 from google import pubsub_v1
1389 def sample_pull():
1390 # Create a client
1391 client = pubsub_v1.SubscriberClient()
1393 # Initialize request argument(s)
1394 request = pubsub_v1.PullRequest(
1395 subscription="subscription_value",
1396 max_messages=1277,
1397 )
1399 # Make the request
1400 response = client.pull(request=request)
1402 # Handle the response
1403 print(response)
1405 Args:
1406 request (Union[google.pubsub_v1.types.PullRequest, dict]):
1407 The request object. Request for the `Pull` method.
1408 subscription (str):
1409 Required. The subscription from which messages should be
1410 pulled. Format is
1411 ``projects/{project}/subscriptions/{sub}``.
1413 This corresponds to the ``subscription`` field
1414 on the ``request`` instance; if ``request`` is provided, this
1415 should not be set.
1416 return_immediately (bool):
1417 Optional. If this field set to true, the system will
1418 respond immediately even if it there are no messages
1419 available to return in the ``Pull`` response. Otherwise,
1420 the system may wait (for a bounded amount of time) until
1421 at least one message is available, rather than returning
1422 no messages. Warning: setting this field to ``true`` is
1423 discouraged because it adversely impacts the performance
1424 of ``Pull`` operations. We recommend that users do not
1425 set this field.
1427 This corresponds to the ``return_immediately`` field
1428 on the ``request`` instance; if ``request`` is provided, this
1429 should not be set.
1430 max_messages (int):
1431 Required. The maximum number of
1432 messages to return for this request.
1433 Must be a positive integer. The Pub/Sub
1434 system may return fewer than the number
1435 specified.
1437 This corresponds to the ``max_messages`` field
1438 on the ``request`` instance; if ``request`` is provided, this
1439 should not be set.
1440 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1441 should be retried.
1442 timeout (float): The timeout for this request.
1443 metadata (Sequence[Tuple[str, str]]): Strings which should be
1444 sent along with the request as metadata.
1446 Returns:
1447 google.pubsub_v1.types.PullResponse:
1448 Response for the Pull method.
1449 """
1450 # Create or coerce a protobuf request object.
1451 # Quick check: If we got a request object, we should *not* have
1452 # gotten any keyword arguments that map to the request.
1453 has_flattened_params = any([subscription, return_immediately, max_messages])
1454 if request is not None and has_flattened_params:
1455 raise ValueError(
1456 "If the `request` argument is set, then none of "
1457 "the individual field arguments should be set."
1458 )
1460 # Minor optimization to avoid making a copy if the user passes
1461 # in a pubsub.PullRequest.
1462 # There's no risk of modifying the input as we've already verified
1463 # there are no flattened fields.
1464 if not isinstance(request, pubsub.PullRequest):
1465 request = pubsub.PullRequest(request)
1466 # If we have keyword arguments corresponding to fields on the
1467 # request, apply these.
1468 if subscription is not None:
1469 request.subscription = subscription
1470 if return_immediately is not None:
1471 request.return_immediately = return_immediately
1472 if max_messages is not None:
1473 request.max_messages = max_messages
1475 if request.return_immediately:
1476 warnings.warn(
1477 "The return_immediately flag is deprecated and should be set to False.",
1478 category=DeprecationWarning,
1479 )
1481 # Wrap the RPC method; this adds retry and timeout information,
1482 # and friendly error handling.
1483 rpc = self._transport._wrapped_methods[self._transport.pull]
1485 # Certain fields should be provided within the metadata header;
1486 # add these here.
1487 metadata = tuple(metadata) + (
1488 gapic_v1.routing_header.to_grpc_metadata(
1489 (("subscription", request.subscription),)
1490 ),
1491 )
1493 # Send the request.
1494 response = rpc(
1495 request,
1496 retry=retry,
1497 timeout=timeout,
1498 metadata=metadata,
1499 )
1501 # Done; return the response.
1502 return response
1504 def streaming_pull(
1505 self,
1506 requests: Optional[Iterator[pubsub.StreamingPullRequest]] = None,
1507 *,
1508 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1509 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1510 metadata: Sequence[Tuple[str, str]] = (),
1511 ) -> Iterable[pubsub.StreamingPullResponse]:
1512 r"""Establishes a stream with the server, which sends messages down
1513 to the client. The client streams acknowledgements and ack
1514 deadline modifications back to the server. The server will close
1515 the stream and return the status on any error. The server may
1516 close the stream with status ``UNAVAILABLE`` to reassign
1517 server-side resources, in which case, the client should
1518 re-establish the stream. Flow control can be achieved by
1519 configuring the underlying RPC channel.
1521 .. code-block:: python
1523 # This snippet has been automatically generated and should be regarded as a
1524 # code template only.
1525 # It will require modifications to work:
1526 # - It may require correct/in-range values for request initialization.
1527 # - It may require specifying regional endpoints when creating the service
1528 # client as shown in:
1529 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1530 from google import pubsub_v1
1532 def sample_streaming_pull():
1533 # Create a client
1534 client = pubsub_v1.SubscriberClient()
1536 # Initialize request argument(s)
1537 request = pubsub_v1.StreamingPullRequest(
1538 subscription="subscription_value",
1539 stream_ack_deadline_seconds=2813,
1540 )
1542 # This method expects an iterator which contains
1543 # 'pubsub_v1.StreamingPullRequest' objects
1544 # Here we create a generator that yields a single `request` for
1545 # demonstrative purposes.
1546 requests = [request]
1548 def request_generator():
1549 for request in requests:
1550 yield request
1552 # Make the request
1553 stream = client.streaming_pull(requests=request_generator())
1555 # Handle the response
1556 for response in stream:
1557 print(response)
1559 Args:
1560 requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]):
1561 The request object iterator. Request for the `StreamingPull`
1562 streaming RPC method. This request is used to establish
1563 the initial stream as well as to stream acknowledgements
1564 and ack deadline modifications from the client to the
1565 server.
1566 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1567 should be retried.
1568 timeout (float): The timeout for this request.
1569 metadata (Sequence[Tuple[str, str]]): Strings which should be
1570 sent along with the request as metadata.
1572 Returns:
1573 Iterable[google.pubsub_v1.types.StreamingPullResponse]:
1574 Response for the StreamingPull method. This response is used to stream
1575 messages from the server to the client.
1577 """
1579 # Wrappers in api-core should not automatically pre-fetch the first
1580 # stream result, as this breaks the stream when re-opening it.
1581 # https://github.com/googleapis/python-pubsub/issues/93#issuecomment-630762257
1582 self._transport.streaming_pull._prefetch_first_result_ = False
1584 # Wrap the RPC method; this adds retry and timeout information,
1585 # and friendly error handling.
1586 rpc = self._transport._wrapped_methods[self._transport.streaming_pull]
1588 # Send the request.
1589 response = rpc(
1590 requests,
1591 retry=retry,
1592 timeout=timeout,
1593 metadata=metadata,
1594 )
1596 # Done; return the response.
1597 return response
1599 def modify_push_config(
1600 self,
1601 request: Optional[Union[pubsub.ModifyPushConfigRequest, dict]] = None,
1602 *,
1603 subscription: Optional[str] = None,
1604 push_config: Optional[pubsub.PushConfig] = None,
1605 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1606 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1607 metadata: Sequence[Tuple[str, str]] = (),
1608 ) -> None:
1609 r"""Modifies the ``PushConfig`` for a specified subscription.
1611 This may be used to change a push subscription to a pull one
1612 (signified by an empty ``PushConfig``) or vice versa, or change
1613 the endpoint URL and other attributes of a push subscription.
1614 Messages will accumulate for delivery continuously through the
1615 call regardless of changes to the ``PushConfig``.
1617 .. code-block:: python
1619 # This snippet has been automatically generated and should be regarded as a
1620 # code template only.
1621 # It will require modifications to work:
1622 # - It may require correct/in-range values for request initialization.
1623 # - It may require specifying regional endpoints when creating the service
1624 # client as shown in:
1625 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1626 from google import pubsub_v1
1628 def sample_modify_push_config():
1629 # Create a client
1630 client = pubsub_v1.SubscriberClient()
1632 # Initialize request argument(s)
1633 request = pubsub_v1.ModifyPushConfigRequest(
1634 subscription="subscription_value",
1635 )
1637 # Make the request
1638 client.modify_push_config(request=request)
1640 Args:
1641 request (Union[google.pubsub_v1.types.ModifyPushConfigRequest, dict]):
1642 The request object. Request for the ModifyPushConfig
1643 method.
1644 subscription (str):
1645 Required. The name of the subscription. Format is
1646 ``projects/{project}/subscriptions/{sub}``.
1648 This corresponds to the ``subscription`` field
1649 on the ``request`` instance; if ``request`` is provided, this
1650 should not be set.
1651 push_config (google.pubsub_v1.types.PushConfig):
1652 Required. The push configuration for future deliveries.
1654 An empty ``pushConfig`` indicates that the Pub/Sub
1655 system should stop pushing messages from the given
1656 subscription and allow messages to be pulled and
1657 acknowledged - effectively pausing the subscription if
1658 ``Pull`` or ``StreamingPull`` is not called.
1660 This corresponds to the ``push_config`` field
1661 on the ``request`` instance; if ``request`` is provided, this
1662 should not be set.
1663 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1664 should be retried.
1665 timeout (float): The timeout for this request.
1666 metadata (Sequence[Tuple[str, str]]): Strings which should be
1667 sent along with the request as metadata.
1668 """
1669 # Create or coerce a protobuf request object.
1670 # Quick check: If we got a request object, we should *not* have
1671 # gotten any keyword arguments that map to the request.
1672 has_flattened_params = any([subscription, push_config])
1673 if request is not None and has_flattened_params:
1674 raise ValueError(
1675 "If the `request` argument is set, then none of "
1676 "the individual field arguments should be set."
1677 )
1679 # Minor optimization to avoid making a copy if the user passes
1680 # in a pubsub.ModifyPushConfigRequest.
1681 # There's no risk of modifying the input as we've already verified
1682 # there are no flattened fields.
1683 if not isinstance(request, pubsub.ModifyPushConfigRequest):
1684 request = pubsub.ModifyPushConfigRequest(request)
1685 # If we have keyword arguments corresponding to fields on the
1686 # request, apply these.
1687 if subscription is not None:
1688 request.subscription = subscription
1689 if push_config is not None:
1690 request.push_config = push_config
1692 # Wrap the RPC method; this adds retry and timeout information,
1693 # and friendly error handling.
1694 rpc = self._transport._wrapped_methods[self._transport.modify_push_config]
1696 # Certain fields should be provided within the metadata header;
1697 # add these here.
1698 metadata = tuple(metadata) + (
1699 gapic_v1.routing_header.to_grpc_metadata(
1700 (("subscription", request.subscription),)
1701 ),
1702 )
1704 # Send the request.
1705 rpc(
1706 request,
1707 retry=retry,
1708 timeout=timeout,
1709 metadata=metadata,
1710 )
1712 def get_snapshot(
1713 self,
1714 request: Optional[Union[pubsub.GetSnapshotRequest, dict]] = None,
1715 *,
1716 snapshot: Optional[str] = None,
1717 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1718 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1719 metadata: Sequence[Tuple[str, str]] = (),
1720 ) -> pubsub.Snapshot:
1721 r"""Gets the configuration details of a snapshot. Snapshots are used
1722 in
1723 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
1724 operations, which allow you to manage message acknowledgments in
1725 bulk. That is, you can set the acknowledgment state of messages
1726 in an existing subscription to the state captured by a snapshot.
1728 .. code-block:: python
1730 # This snippet has been automatically generated and should be regarded as a
1731 # code template only.
1732 # It will require modifications to work:
1733 # - It may require correct/in-range values for request initialization.
1734 # - It may require specifying regional endpoints when creating the service
1735 # client as shown in:
1736 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1737 from google import pubsub_v1
1739 def sample_get_snapshot():
1740 # Create a client
1741 client = pubsub_v1.SubscriberClient()
1743 # Initialize request argument(s)
1744 request = pubsub_v1.GetSnapshotRequest(
1745 snapshot="snapshot_value",
1746 )
1748 # Make the request
1749 response = client.get_snapshot(request=request)
1751 # Handle the response
1752 print(response)
1754 Args:
1755 request (Union[google.pubsub_v1.types.GetSnapshotRequest, dict]):
1756 The request object. Request for the GetSnapshot method.
1757 snapshot (str):
1758 Required. The name of the snapshot to get. Format is
1759 ``projects/{project}/snapshots/{snap}``.
1761 This corresponds to the ``snapshot`` field
1762 on the ``request`` instance; if ``request`` is provided, this
1763 should not be set.
1764 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1765 should be retried.
1766 timeout (float): The timeout for this request.
1767 metadata (Sequence[Tuple[str, str]]): Strings which should be
1768 sent along with the request as metadata.
1770 Returns:
1771 google.pubsub_v1.types.Snapshot:
1772 A snapshot resource. Snapshots are used in
1773 [Seek](https://cloud.google.com/pubsub/docs/replay-overview)
1774 operations, which allow you to manage message
1775 acknowledgments in bulk. That is, you can set the
1776 acknowledgment state of messages in an existing
1777 subscription to the state captured by a snapshot.
1779 """
1780 # Create or coerce a protobuf request object.
1781 # Quick check: If we got a request object, we should *not* have
1782 # gotten any keyword arguments that map to the request.
1783 has_flattened_params = any([snapshot])
1784 if request is not None and has_flattened_params:
1785 raise ValueError(
1786 "If the `request` argument is set, then none of "
1787 "the individual field arguments should be set."
1788 )
1790 # Minor optimization to avoid making a copy if the user passes
1791 # in a pubsub.GetSnapshotRequest.
1792 # There's no risk of modifying the input as we've already verified
1793 # there are no flattened fields.
1794 if not isinstance(request, pubsub.GetSnapshotRequest):
1795 request = pubsub.GetSnapshotRequest(request)
1796 # If we have keyword arguments corresponding to fields on the
1797 # request, apply these.
1798 if snapshot is not None:
1799 request.snapshot = snapshot
1801 # Wrap the RPC method; this adds retry and timeout information,
1802 # and friendly error handling.
1803 rpc = self._transport._wrapped_methods[self._transport.get_snapshot]
1805 # Certain fields should be provided within the metadata header;
1806 # add these here.
1807 metadata = tuple(metadata) + (
1808 gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)),
1809 )
1811 # Send the request.
1812 response = rpc(
1813 request,
1814 retry=retry,
1815 timeout=timeout,
1816 metadata=metadata,
1817 )
1819 # Done; return the response.
1820 return response
1822 def list_snapshots(
1823 self,
1824 request: Optional[Union[pubsub.ListSnapshotsRequest, dict]] = None,
1825 *,
1826 project: Optional[str] = None,
1827 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1828 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1829 metadata: Sequence[Tuple[str, str]] = (),
1830 ) -> pagers.ListSnapshotsPager:
1831 r"""Lists the existing snapshots. Snapshots are used in
1832 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
1833 operations, which allow you to manage message acknowledgments in
1834 bulk. That is, you can set the acknowledgment state of messages
1835 in an existing subscription to the state captured by a snapshot.
1837 .. code-block:: python
1839 # This snippet has been automatically generated and should be regarded as a
1840 # code template only.
1841 # It will require modifications to work:
1842 # - It may require correct/in-range values for request initialization.
1843 # - It may require specifying regional endpoints when creating the service
1844 # client as shown in:
1845 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1846 from google import pubsub_v1
1848 def sample_list_snapshots():
1849 # Create a client
1850 client = pubsub_v1.SubscriberClient()
1852 # Initialize request argument(s)
1853 request = pubsub_v1.ListSnapshotsRequest(
1854 project="project_value",
1855 )
1857 # Make the request
1858 page_result = client.list_snapshots(request=request)
1860 # Handle the response
1861 for response in page_result:
1862 print(response)
1864 Args:
1865 request (Union[google.pubsub_v1.types.ListSnapshotsRequest, dict]):
1866 The request object. Request for the `ListSnapshots`
1867 method.
1868 project (str):
1869 Required. The name of the project in which to list
1870 snapshots. Format is ``projects/{project-id}``.
1872 This corresponds to the ``project`` field
1873 on the ``request`` instance; if ``request`` is provided, this
1874 should not be set.
1875 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1876 should be retried.
1877 timeout (float): The timeout for this request.
1878 metadata (Sequence[Tuple[str, str]]): Strings which should be
1879 sent along with the request as metadata.
1881 Returns:
1882 google.pubsub_v1.services.subscriber.pagers.ListSnapshotsPager:
1883 Response for the ListSnapshots method.
1885 Iterating over this object will yield results and
1886 resolve additional pages automatically.
1888 """
1889 # Create or coerce a protobuf request object.
1890 # Quick check: If we got a request object, we should *not* have
1891 # gotten any keyword arguments that map to the request.
1892 has_flattened_params = any([project])
1893 if request is not None and has_flattened_params:
1894 raise ValueError(
1895 "If the `request` argument is set, then none of "
1896 "the individual field arguments should be set."
1897 )
1899 # Minor optimization to avoid making a copy if the user passes
1900 # in a pubsub.ListSnapshotsRequest.
1901 # There's no risk of modifying the input as we've already verified
1902 # there are no flattened fields.
1903 if not isinstance(request, pubsub.ListSnapshotsRequest):
1904 request = pubsub.ListSnapshotsRequest(request)
1905 # If we have keyword arguments corresponding to fields on the
1906 # request, apply these.
1907 if project is not None:
1908 request.project = project
1910 # Wrap the RPC method; this adds retry and timeout information,
1911 # and friendly error handling.
1912 rpc = self._transport._wrapped_methods[self._transport.list_snapshots]
1914 # Certain fields should be provided within the metadata header;
1915 # add these here.
1916 metadata = tuple(metadata) + (
1917 gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)),
1918 )
1920 # Send the request.
1921 response = rpc(
1922 request,
1923 retry=retry,
1924 timeout=timeout,
1925 metadata=metadata,
1926 )
1928 # This method is paged; wrap the response in a pager, which provides
1929 # an `__iter__` convenience method.
1930 response = pagers.ListSnapshotsPager(
1931 method=rpc,
1932 request=request,
1933 response=response,
1934 metadata=metadata,
1935 )
1937 # Done; return the response.
1938 return response
1940 def create_snapshot(
1941 self,
1942 request: Optional[Union[pubsub.CreateSnapshotRequest, dict]] = None,
1943 *,
1944 name: Optional[str] = None,
1945 subscription: Optional[str] = None,
1946 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1947 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1948 metadata: Sequence[Tuple[str, str]] = (),
1949 ) -> pubsub.Snapshot:
1950 r"""Creates a snapshot from the requested subscription. Snapshots
1951 are used in
1952 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
1953 operations, which allow you to manage message acknowledgments in
1954 bulk. That is, you can set the acknowledgment state of messages
1955 in an existing subscription to the state captured by a snapshot.
1956 If the snapshot already exists, returns ``ALREADY_EXISTS``. If
1957 the requested subscription doesn't exist, returns ``NOT_FOUND``.
1958 If the backlog in the subscription is too old -- and the
1959 resulting snapshot would expire in less than 1 hour -- then
1960 ``FAILED_PRECONDITION`` is returned. See also the
1961 ``Snapshot.expire_time`` field. If the name is not provided in
1962 the request, the server will assign a random name for this
1963 snapshot on the same project as the subscription, conforming to
1964 the [resource name format]
1965 (https://cloud.google.com/pubsub/docs/admin#resource_names). The
1966 generated name is populated in the returned Snapshot object.
1967 Note that for REST API requests, you must specify a name in the
1968 request.
1970 .. code-block:: python
1972 # This snippet has been automatically generated and should be regarded as a
1973 # code template only.
1974 # It will require modifications to work:
1975 # - It may require correct/in-range values for request initialization.
1976 # - It may require specifying regional endpoints when creating the service
1977 # client as shown in:
1978 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1979 from google import pubsub_v1
1981 def sample_create_snapshot():
1982 # Create a client
1983 client = pubsub_v1.SubscriberClient()
1985 # Initialize request argument(s)
1986 request = pubsub_v1.CreateSnapshotRequest(
1987 name="name_value",
1988 subscription="subscription_value",
1989 )
1991 # Make the request
1992 response = client.create_snapshot(request=request)
1994 # Handle the response
1995 print(response)
1997 Args:
1998 request (Union[google.pubsub_v1.types.CreateSnapshotRequest, dict]):
1999 The request object. Request for the `CreateSnapshot`
2000 method.
2001 name (str):
2002 Required. User-provided name for this snapshot. If the
2003 name is not provided in the request, the server will
2004 assign a random name for this snapshot on the same
2005 project as the subscription. Note that for REST API
2006 requests, you must specify a name. See the `resource
2007 name
2008 rules <https://cloud.google.com/pubsub/docs/admin#resource_names>`__.
2009 Format is ``projects/{project}/snapshots/{snap}``.
2011 This corresponds to the ``name`` field
2012 on the ``request`` instance; if ``request`` is provided, this
2013 should not be set.
2014 subscription (str):
2015 Required. The subscription whose backlog the snapshot
2016 retains. Specifically, the created snapshot is
2017 guaranteed to retain: (a) The existing backlog on the
2018 subscription. More precisely, this is defined as the
2019 messages in the subscription's backlog that are
2020 unacknowledged upon the successful completion of the
2021 ``CreateSnapshot`` request; as well as: (b) Any messages
2022 published to the subscription's topic following the
2023 successful completion of the CreateSnapshot request.
2024 Format is ``projects/{project}/subscriptions/{sub}``.
2026 This corresponds to the ``subscription`` field
2027 on the ``request`` instance; if ``request`` is provided, this
2028 should not be set.
2029 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2030 should be retried.
2031 timeout (float): The timeout for this request.
2032 metadata (Sequence[Tuple[str, str]]): Strings which should be
2033 sent along with the request as metadata.
2035 Returns:
2036 google.pubsub_v1.types.Snapshot:
2037 A snapshot resource. Snapshots are used in
2038 [Seek](https://cloud.google.com/pubsub/docs/replay-overview)
2039 operations, which allow you to manage message
2040 acknowledgments in bulk. That is, you can set the
2041 acknowledgment state of messages in an existing
2042 subscription to the state captured by a snapshot.
2044 """
2045 # Create or coerce a protobuf request object.
2046 # Quick check: If we got a request object, we should *not* have
2047 # gotten any keyword arguments that map to the request.
2048 has_flattened_params = any([name, subscription])
2049 if request is not None and has_flattened_params:
2050 raise ValueError(
2051 "If the `request` argument is set, then none of "
2052 "the individual field arguments should be set."
2053 )
2055 # Minor optimization to avoid making a copy if the user passes
2056 # in a pubsub.CreateSnapshotRequest.
2057 # There's no risk of modifying the input as we've already verified
2058 # there are no flattened fields.
2059 if not isinstance(request, pubsub.CreateSnapshotRequest):
2060 request = pubsub.CreateSnapshotRequest(request)
2061 # If we have keyword arguments corresponding to fields on the
2062 # request, apply these.
2063 if name is not None:
2064 request.name = name
2065 if subscription is not None:
2066 request.subscription = subscription
2068 # Wrap the RPC method; this adds retry and timeout information,
2069 # and friendly error handling.
2070 rpc = self._transport._wrapped_methods[self._transport.create_snapshot]
2072 # Certain fields should be provided within the metadata header;
2073 # add these here.
2074 metadata = tuple(metadata) + (
2075 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
2076 )
2078 # Send the request.
2079 response = rpc(
2080 request,
2081 retry=retry,
2082 timeout=timeout,
2083 metadata=metadata,
2084 )
2086 # Done; return the response.
2087 return response
2089 def update_snapshot(
2090 self,
2091 request: Optional[Union[pubsub.UpdateSnapshotRequest, dict]] = None,
2092 *,
2093 snapshot: Optional[pubsub.Snapshot] = None,
2094 update_mask: Optional[field_mask_pb2.FieldMask] = None,
2095 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2096 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2097 metadata: Sequence[Tuple[str, str]] = (),
2098 ) -> pubsub.Snapshot:
2099 r"""Updates an existing snapshot. Snapshots are used in
2100 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
2101 operations, which allow you to manage message acknowledgments in
2102 bulk. That is, you can set the acknowledgment state of messages
2103 in an existing subscription to the state captured by a snapshot.
2105 .. code-block:: python
2107 # This snippet has been automatically generated and should be regarded as a
2108 # code template only.
2109 # It will require modifications to work:
2110 # - It may require correct/in-range values for request initialization.
2111 # - It may require specifying regional endpoints when creating the service
2112 # client as shown in:
2113 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2114 from google import pubsub_v1
2116 def sample_update_snapshot():
2117 # Create a client
2118 client = pubsub_v1.SubscriberClient()
2120 # Initialize request argument(s)
2121 request = pubsub_v1.UpdateSnapshotRequest(
2122 )
2124 # Make the request
2125 response = client.update_snapshot(request=request)
2127 # Handle the response
2128 print(response)
2130 Args:
2131 request (Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]):
2132 The request object. Request for the UpdateSnapshot
2133 method.
2134 snapshot (google.pubsub_v1.types.Snapshot):
2135 Required. The updated snapshot
2136 object.
2138 This corresponds to the ``snapshot`` field
2139 on the ``request`` instance; if ``request`` is provided, this
2140 should not be set.
2141 update_mask (google.protobuf.field_mask_pb2.FieldMask):
2142 Required. Indicates which fields in
2143 the provided snapshot to update. Must be
2144 specified and non-empty.
2146 This corresponds to the ``update_mask`` field
2147 on the ``request`` instance; if ``request`` is provided, this
2148 should not be set.
2149 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2150 should be retried.
2151 timeout (float): The timeout for this request.
2152 metadata (Sequence[Tuple[str, str]]): Strings which should be
2153 sent along with the request as metadata.
2155 Returns:
2156 google.pubsub_v1.types.Snapshot:
2157 A snapshot resource. Snapshots are used in
2158 [Seek](https://cloud.google.com/pubsub/docs/replay-overview)
2159 operations, which allow you to manage message
2160 acknowledgments in bulk. That is, you can set the
2161 acknowledgment state of messages in an existing
2162 subscription to the state captured by a snapshot.
2164 """
2165 # Create or coerce a protobuf request object.
2166 # Quick check: If we got a request object, we should *not* have
2167 # gotten any keyword arguments that map to the request.
2168 has_flattened_params = any([snapshot, update_mask])
2169 if request is not None and has_flattened_params:
2170 raise ValueError(
2171 "If the `request` argument is set, then none of "
2172 "the individual field arguments should be set."
2173 )
2175 # Minor optimization to avoid making a copy if the user passes
2176 # in a pubsub.UpdateSnapshotRequest.
2177 # There's no risk of modifying the input as we've already verified
2178 # there are no flattened fields.
2179 if not isinstance(request, pubsub.UpdateSnapshotRequest):
2180 request = pubsub.UpdateSnapshotRequest(request)
2181 # If we have keyword arguments corresponding to fields on the
2182 # request, apply these.
2183 if snapshot is not None:
2184 request.snapshot = snapshot
2185 if update_mask is not None:
2186 request.update_mask = update_mask
2188 # Wrap the RPC method; this adds retry and timeout information,
2189 # and friendly error handling.
2190 rpc = self._transport._wrapped_methods[self._transport.update_snapshot]
2192 # Certain fields should be provided within the metadata header;
2193 # add these here.
2194 metadata = tuple(metadata) + (
2195 gapic_v1.routing_header.to_grpc_metadata(
2196 (("snapshot.name", request.snapshot.name),)
2197 ),
2198 )
2200 # Send the request.
2201 response = rpc(
2202 request,
2203 retry=retry,
2204 timeout=timeout,
2205 metadata=metadata,
2206 )
2208 # Done; return the response.
2209 return response
2211 def delete_snapshot(
2212 self,
2213 request: Optional[Union[pubsub.DeleteSnapshotRequest, dict]] = None,
2214 *,
2215 snapshot: Optional[str] = None,
2216 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2217 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2218 metadata: Sequence[Tuple[str, str]] = (),
2219 ) -> None:
2220 r"""Removes an existing snapshot. Snapshots are used in [Seek]
2221 (https://cloud.google.com/pubsub/docs/replay-overview)
2222 operations, which allow you to manage message acknowledgments in
2223 bulk. That is, you can set the acknowledgment state of messages
2224 in an existing subscription to the state captured by a snapshot.
2225 When the snapshot is deleted, all messages retained in the
2226 snapshot are immediately dropped. After a snapshot is deleted, a
2227 new one may be created with the same name, but the new one has
2228 no association with the old snapshot or its subscription, unless
2229 the same subscription is specified.
2231 .. code-block:: python
2233 # This snippet has been automatically generated and should be regarded as a
2234 # code template only.
2235 # It will require modifications to work:
2236 # - It may require correct/in-range values for request initialization.
2237 # - It may require specifying regional endpoints when creating the service
2238 # client as shown in:
2239 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2240 from google import pubsub_v1
2242 def sample_delete_snapshot():
2243 # Create a client
2244 client = pubsub_v1.SubscriberClient()
2246 # Initialize request argument(s)
2247 request = pubsub_v1.DeleteSnapshotRequest(
2248 snapshot="snapshot_value",
2249 )
2251 # Make the request
2252 client.delete_snapshot(request=request)
2254 Args:
2255 request (Union[google.pubsub_v1.types.DeleteSnapshotRequest, dict]):
2256 The request object. Request for the `DeleteSnapshot`
2257 method.
2258 snapshot (str):
2259 Required. The name of the snapshot to delete. Format is
2260 ``projects/{project}/snapshots/{snap}``.
2262 This corresponds to the ``snapshot`` field
2263 on the ``request`` instance; if ``request`` is provided, this
2264 should not be set.
2265 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2266 should be retried.
2267 timeout (float): The timeout for this request.
2268 metadata (Sequence[Tuple[str, str]]): Strings which should be
2269 sent along with the request as metadata.
2270 """
2271 # Create or coerce a protobuf request object.
2272 # Quick check: If we got a request object, we should *not* have
2273 # gotten any keyword arguments that map to the request.
2274 has_flattened_params = any([snapshot])
2275 if request is not None and has_flattened_params:
2276 raise ValueError(
2277 "If the `request` argument is set, then none of "
2278 "the individual field arguments should be set."
2279 )
2281 # Minor optimization to avoid making a copy if the user passes
2282 # in a pubsub.DeleteSnapshotRequest.
2283 # There's no risk of modifying the input as we've already verified
2284 # there are no flattened fields.
2285 if not isinstance(request, pubsub.DeleteSnapshotRequest):
2286 request = pubsub.DeleteSnapshotRequest(request)
2287 # If we have keyword arguments corresponding to fields on the
2288 # request, apply these.
2289 if snapshot is not None:
2290 request.snapshot = snapshot
2292 # Wrap the RPC method; this adds retry and timeout information,
2293 # and friendly error handling.
2294 rpc = self._transport._wrapped_methods[self._transport.delete_snapshot]
2296 # Certain fields should be provided within the metadata header;
2297 # add these here.
2298 metadata = tuple(metadata) + (
2299 gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)),
2300 )
2302 # Send the request.
2303 rpc(
2304 request,
2305 retry=retry,
2306 timeout=timeout,
2307 metadata=metadata,
2308 )
2310 def seek(
2311 self,
2312 request: Optional[Union[pubsub.SeekRequest, dict]] = None,
2313 *,
2314 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2315 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2316 metadata: Sequence[Tuple[str, str]] = (),
2317 ) -> pubsub.SeekResponse:
2318 r"""Seeks an existing subscription to a point in time or to a given
2319 snapshot, whichever is provided in the request. Snapshots are
2320 used in [Seek]
2321 (https://cloud.google.com/pubsub/docs/replay-overview)
2322 operations, which allow you to manage message acknowledgments in
2323 bulk. That is, you can set the acknowledgment state of messages
2324 in an existing subscription to the state captured by a snapshot.
2325 Note that both the subscription and the snapshot must be on the
2326 same topic.
2328 .. code-block:: python
2330 # This snippet has been automatically generated and should be regarded as a
2331 # code template only.
2332 # It will require modifications to work:
2333 # - It may require correct/in-range values for request initialization.
2334 # - It may require specifying regional endpoints when creating the service
2335 # client as shown in:
2336 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2337 from google import pubsub_v1
2339 def sample_seek():
2340 # Create a client
2341 client = pubsub_v1.SubscriberClient()
2343 # Initialize request argument(s)
2344 request = pubsub_v1.SeekRequest(
2345 subscription="subscription_value",
2346 )
2348 # Make the request
2349 response = client.seek(request=request)
2351 # Handle the response
2352 print(response)
2354 Args:
2355 request (Union[google.pubsub_v1.types.SeekRequest, dict]):
2356 The request object. Request for the `Seek` method.
2357 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2358 should be retried.
2359 timeout (float): The timeout for this request.
2360 metadata (Sequence[Tuple[str, str]]): Strings which should be
2361 sent along with the request as metadata.
2363 Returns:
2364 google.pubsub_v1.types.SeekResponse:
2365 Response for the Seek method (this response is empty).
2366 """
2367 # Create or coerce a protobuf request object.
2368 # Minor optimization to avoid making a copy if the user passes
2369 # in a pubsub.SeekRequest.
2370 # There's no risk of modifying the input as we've already verified
2371 # there are no flattened fields.
2372 if not isinstance(request, pubsub.SeekRequest):
2373 request = pubsub.SeekRequest(request)
2375 # Wrap the RPC method; this adds retry and timeout information,
2376 # and friendly error handling.
2377 rpc = self._transport._wrapped_methods[self._transport.seek]
2379 # Certain fields should be provided within the metadata header;
2380 # add these here.
2381 metadata = tuple(metadata) + (
2382 gapic_v1.routing_header.to_grpc_metadata(
2383 (("subscription", request.subscription),)
2384 ),
2385 )
2387 # Send the request.
2388 response = rpc(
2389 request,
2390 retry=retry,
2391 timeout=timeout,
2392 metadata=metadata,
2393 )
2395 # Done; return the response.
2396 return response
2398 def __enter__(self) -> "SubscriberClient":
2399 return self
2401 def __exit__(self, type, value, traceback):
2402 """Releases underlying transport's resources.
2404 .. warning::
2405 ONLY use as a context manager if the transport is NOT shared
2406 with other clients! Exiting the with block will CLOSE the transport
2407 and may cause errors in other clients!
2408 """
2409 self.transport.close()
2411 def set_iam_policy(
2412 self,
2413 request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None,
2414 *,
2415 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2416 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2417 metadata: Sequence[Tuple[str, str]] = (),
2418 ) -> policy_pb2.Policy:
2419 r"""Sets the IAM access control policy on the specified function.
2421 Replaces any existing policy.
2423 Args:
2424 request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`):
2425 The request object. Request message for `SetIamPolicy`
2426 method.
2427 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2428 should be retried.
2429 timeout (float): The timeout for this request.
2430 metadata (Sequence[Tuple[str, str]]): Strings which should be
2431 sent along with the request as metadata.
2432 Returns:
2433 ~.policy_pb2.Policy:
2434 Defines an Identity and Access Management (IAM) policy.
2435 It is used to specify access control policies for Cloud
2436 Platform resources.
2437 A ``Policy`` is a collection of ``bindings``. A
2438 ``binding`` binds one or more ``members`` to a single
2439 ``role``. Members can be user accounts, service
2440 accounts, Google groups, and domains (such as G Suite).
2441 A ``role`` is a named list of permissions (defined by
2442 IAM or configured by users). A ``binding`` can
2443 optionally specify a ``condition``, which is a logic
2444 expression that further constrains the role binding
2445 based on attributes about the request and/or target
2446 resource.
2448 **JSON Example**
2450 ::
2452 {
2453 "bindings": [
2454 {
2455 "role": "roles/resourcemanager.organizationAdmin",
2456 "members": [
2457 "user:mike@example.com",
2458 "group:admins@example.com",
2459 "domain:google.com",
2460 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
2461 ]
2462 },
2463 {
2464 "role": "roles/resourcemanager.organizationViewer",
2465 "members": ["user:eve@example.com"],
2466 "condition": {
2467 "title": "expirable access",
2468 "description": "Does not grant access after Sep 2020",
2469 "expression": "request.time <
2470 timestamp('2020-10-01T00:00:00.000Z')",
2471 }
2472 }
2473 ]
2474 }
2476 **YAML Example**
2478 ::
2480 bindings:
2481 - members:
2482 - user:mike@example.com
2483 - group:admins@example.com
2484 - domain:google.com
2485 - serviceAccount:my-project-id@appspot.gserviceaccount.com
2486 role: roles/resourcemanager.organizationAdmin
2487 - members:
2488 - user:eve@example.com
2489 role: roles/resourcemanager.organizationViewer
2490 condition:
2491 title: expirable access
2492 description: Does not grant access after Sep 2020
2493 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
2495 For a description of IAM and its features, see the `IAM
2496 developer's
2497 guide <https://cloud.google.com/iam/docs>`__.
2498 """
2499 # Create or coerce a protobuf request object.
2501 # The request isn't a proto-plus wrapped type,
2502 # so it must be constructed via keyword expansion.
2503 if isinstance(request, dict):
2504 request = iam_policy_pb2.SetIamPolicyRequest(**request)
2506 # Wrap the RPC method; this adds retry and timeout information,
2507 # and friendly error handling.
2508 rpc = gapic_v1.method.wrap_method(
2509 self._transport.set_iam_policy,
2510 default_timeout=None,
2511 client_info=DEFAULT_CLIENT_INFO,
2512 )
2514 # Certain fields should be provided within the metadata header;
2515 # add these here.
2516 metadata = tuple(metadata) + (
2517 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2518 )
2520 # Send the request.
2521 response = rpc(
2522 request,
2523 retry=retry,
2524 timeout=timeout,
2525 metadata=metadata,
2526 )
2528 # Done; return the response.
2529 return response
2531 def get_iam_policy(
2532 self,
2533 request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None,
2534 *,
2535 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2536 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2537 metadata: Sequence[Tuple[str, str]] = (),
2538 ) -> policy_pb2.Policy:
2539 r"""Gets the IAM access control policy for a function.
2541 Returns an empty policy if the function exists and does not have a
2542 policy set.
2544 Args:
2545 request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`):
2546 The request object. Request message for `GetIamPolicy`
2547 method.
2548 retry (google.api_core.retry.Retry): Designation of what errors, if
2549 any, should be retried.
2550 timeout (float): The timeout for this request.
2551 metadata (Sequence[Tuple[str, str]]): Strings which should be
2552 sent along with the request as metadata.
2553 Returns:
2554 ~.policy_pb2.Policy:
2555 Defines an Identity and Access Management (IAM) policy.
2556 It is used to specify access control policies for Cloud
2557 Platform resources.
2558 A ``Policy`` is a collection of ``bindings``. A
2559 ``binding`` binds one or more ``members`` to a single
2560 ``role``. Members can be user accounts, service
2561 accounts, Google groups, and domains (such as G Suite).
2562 A ``role`` is a named list of permissions (defined by
2563 IAM or configured by users). A ``binding`` can
2564 optionally specify a ``condition``, which is a logic
2565 expression that further constrains the role binding
2566 based on attributes about the request and/or target
2567 resource.
2569 **JSON Example**
2571 ::
2573 {
2574 "bindings": [
2575 {
2576 "role": "roles/resourcemanager.organizationAdmin",
2577 "members": [
2578 "user:mike@example.com",
2579 "group:admins@example.com",
2580 "domain:google.com",
2581 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
2582 ]
2583 },
2584 {
2585 "role": "roles/resourcemanager.organizationViewer",
2586 "members": ["user:eve@example.com"],
2587 "condition": {
2588 "title": "expirable access",
2589 "description": "Does not grant access after Sep 2020",
2590 "expression": "request.time <
2591 timestamp('2020-10-01T00:00:00.000Z')",
2592 }
2593 }
2594 ]
2595 }
2597 **YAML Example**
2599 ::
2601 bindings:
2602 - members:
2603 - user:mike@example.com
2604 - group:admins@example.com
2605 - domain:google.com
2606 - serviceAccount:my-project-id@appspot.gserviceaccount.com
2607 role: roles/resourcemanager.organizationAdmin
2608 - members:
2609 - user:eve@example.com
2610 role: roles/resourcemanager.organizationViewer
2611 condition:
2612 title: expirable access
2613 description: Does not grant access after Sep 2020
2614 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
2616 For a description of IAM and its features, see the `IAM
2617 developer's
2618 guide <https://cloud.google.com/iam/docs>`__.
2619 """
2620 # Create or coerce a protobuf request object.
2622 # The request isn't a proto-plus wrapped type,
2623 # so it must be constructed via keyword expansion.
2624 if isinstance(request, dict):
2625 request = iam_policy_pb2.GetIamPolicyRequest(**request)
2627 # Wrap the RPC method; this adds retry and timeout information,
2628 # and friendly error handling.
2629 rpc = gapic_v1.method.wrap_method(
2630 self._transport.get_iam_policy,
2631 default_timeout=None,
2632 client_info=DEFAULT_CLIENT_INFO,
2633 )
2635 # Certain fields should be provided within the metadata header;
2636 # add these here.
2637 metadata = tuple(metadata) + (
2638 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2639 )
2641 # Send the request.
2642 response = rpc(
2643 request,
2644 retry=retry,
2645 timeout=timeout,
2646 metadata=metadata,
2647 )
2649 # Done; return the response.
2650 return response
2652 def test_iam_permissions(
2653 self,
2654 request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None,
2655 *,
2656 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2657 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2658 metadata: Sequence[Tuple[str, str]] = (),
2659 ) -> iam_policy_pb2.TestIamPermissionsResponse:
2660 r"""Tests the specified IAM permissions against the IAM access control
2661 policy for a function.
2663 If the function does not exist, this will return an empty set
2664 of permissions, not a NOT_FOUND error.
2666 Args:
2667 request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`):
2668 The request object. Request message for
2669 `TestIamPermissions` method.
2670 retry (google.api_core.retry.Retry): Designation of what errors,
2671 if any, should be retried.
2672 timeout (float): The timeout for this request.
2673 metadata (Sequence[Tuple[str, str]]): Strings which should be
2674 sent along with the request as metadata.
2675 Returns:
2676 ~.iam_policy_pb2.TestIamPermissionsResponse:
2677 Response message for ``TestIamPermissions`` method.
2678 """
2679 # Create or coerce a protobuf request object.
2681 # The request isn't a proto-plus wrapped type,
2682 # so it must be constructed via keyword expansion.
2683 if isinstance(request, dict):
2684 request = iam_policy_pb2.TestIamPermissionsRequest(**request)
2686 # Wrap the RPC method; this adds retry and timeout information,
2687 # and friendly error handling.
2688 rpc = gapic_v1.method.wrap_method(
2689 self._transport.test_iam_permissions,
2690 default_timeout=None,
2691 client_info=DEFAULT_CLIENT_INFO,
2692 )
2694 # Certain fields should be provided within the metadata header;
2695 # add these here.
2696 metadata = tuple(metadata) + (
2697 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2698 )
2700 # Send the request.
2701 response = rpc(
2702 request,
2703 retry=retry,
2704 timeout=timeout,
2705 metadata=metadata,
2706 )
2708 # Done; return the response.
2709 return response
2712DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
2713 client_library_version=package_version.__version__
2714)
2717__all__ = ("SubscriberClient",)