1# -*- coding: utf-8 -*-
2# Copyright 2025 Google LLC
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16from collections import OrderedDict
17from http import HTTPStatus
18import json
19import logging as std_logging
20import functools
21import os
22import re
23from typing import (
24 Dict,
25 Callable,
26 Mapping,
27 MutableMapping,
28 MutableSequence,
29 Optional,
30 Iterable,
31 Iterator,
32 Sequence,
33 Tuple,
34 Type,
35 Union,
36 cast,
37)
38import warnings
39
40import warnings
41from google.pubsub_v1 import gapic_version as package_version
42
43from google.api_core import client_options as client_options_lib
44from google.api_core import exceptions as core_exceptions
45from google.api_core import gapic_v1
46from google.api_core import retry as retries
47from google.auth import credentials as ga_credentials # type: ignore
48from google.auth.transport import mtls # type: ignore
49from google.auth.transport.grpc import SslCredentials # type: ignore
50from google.auth.exceptions import MutualTLSChannelError # type: ignore
51from google.oauth2 import service_account # type: ignore
52import google.protobuf
53
54try:
55 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
56except AttributeError: # pragma: NO COVER
57 OptionalRetry = Union[retries.Retry, object, None] # type: ignore
58
59try:
60 from google.api_core import client_logging # type: ignore
61
62 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
63except ImportError: # pragma: NO COVER
64 CLIENT_LOGGING_SUPPORTED = False
65
66_LOGGER = std_logging.getLogger(__name__)
67
68from google.iam.v1 import iam_policy_pb2 # type: ignore
69from google.iam.v1 import policy_pb2 # type: ignore
70from google.protobuf import duration_pb2 # type: ignore
71from google.protobuf import field_mask_pb2 # type: ignore
72from google.protobuf import timestamp_pb2 # type: ignore
73from google.pubsub_v1.services.subscriber import pagers
74from google.pubsub_v1.types import pubsub
75
76import grpc
77from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO
78from .transports.grpc import SubscriberGrpcTransport
79from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport
80from .transports.rest import SubscriberRestTransport
81
82
83class SubscriberClientMeta(type):
84 """Metaclass for the Subscriber client.
85
86 This provides class-level methods for building and retrieving
87 support objects (e.g. transport) without polluting the client instance
88 objects.
89 """
90
91 _transport_registry = OrderedDict() # type: Dict[str, Type[SubscriberTransport]]
92 _transport_registry["grpc"] = SubscriberGrpcTransport
93 _transport_registry["grpc_asyncio"] = SubscriberGrpcAsyncIOTransport
94 _transport_registry["rest"] = SubscriberRestTransport
95
96 def get_transport_class(
97 cls,
98 label: Optional[str] = None,
99 ) -> Type[SubscriberTransport]:
100 """Returns an appropriate transport class.
101
102 Args:
103 label: The name of the desired transport. If none is
104 provided, then the first transport in the registry is used.
105
106 Returns:
107 The transport class to use.
108 """
109 # If a specific transport is requested, return that one.
110 if label:
111 return cls._transport_registry[label]
112
113 # No transport is requested; return the default (that is, the first one
114 # in the dictionary).
115 return next(iter(cls._transport_registry.values()))
116
117
118class SubscriberClient(metaclass=SubscriberClientMeta):
119 """The service that an application uses to manipulate subscriptions and
120 to consume messages from a subscription via the ``Pull`` method or
121 by establishing a bi-directional stream using the ``StreamingPull``
122 method.
123 """
124
125 @staticmethod
126 def _get_default_mtls_endpoint(api_endpoint):
127 """Converts api endpoint to mTLS endpoint.
128
129 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
130 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
131 Args:
132 api_endpoint (Optional[str]): the api endpoint to convert.
133 Returns:
134 str: converted mTLS api endpoint.
135 """
136 if not api_endpoint:
137 return api_endpoint
138
139 mtls_endpoint_re = re.compile(
140 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
141 )
142
143 m = mtls_endpoint_re.match(api_endpoint)
144 name, mtls, sandbox, googledomain = m.groups()
145 if mtls or not googledomain:
146 return api_endpoint
147
148 if sandbox:
149 return api_endpoint.replace(
150 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
151 )
152
153 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
154
155 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
156
157 # The scopes needed to make gRPC calls to all of the methods defined in
158 # this service
159 _DEFAULT_SCOPES = (
160 "https://www.googleapis.com/auth/cloud-platform",
161 "https://www.googleapis.com/auth/pubsub",
162 )
163
164 SERVICE_ADDRESS = "pubsub.googleapis.com:443"
165 """The default address of the service."""
166
167 DEFAULT_ENDPOINT = "pubsub.googleapis.com"
168 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
169 DEFAULT_ENDPOINT
170 )
171
172 _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}"
173 _DEFAULT_UNIVERSE = "googleapis.com"
174
175 @staticmethod
176 def _use_client_cert_effective():
177 """Returns whether client certificate should be used for mTLS if the
178 google-auth version supports should_use_client_cert automatic mTLS enablement.
179
180 Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var.
181
182 Returns:
183 bool: whether client certificate should be used for mTLS
184 Raises:
185 ValueError: (If using a version of google-auth without should_use_client_cert and
186 GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.)
187 """
188 # check if google-auth version supports should_use_client_cert for automatic mTLS enablement
189 if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER
190 return mtls.should_use_client_cert()
191 else: # pragma: NO COVER
192 # if unsupported, fallback to reading from env var
193 use_client_cert_str = os.getenv(
194 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
195 ).lower()
196 if use_client_cert_str not in ("true", "false"):
197 raise ValueError(
198 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be"
199 " either `true` or `false`"
200 )
201 return use_client_cert_str == "true"
202
203 @classmethod
204 def from_service_account_info(cls, info: dict, *args, **kwargs):
205 """Creates an instance of this client using the provided credentials
206 info.
207
208 Args:
209 info (dict): The service account private key info.
210 args: Additional arguments to pass to the constructor.
211 kwargs: Additional arguments to pass to the constructor.
212
213 Returns:
214 SubscriberClient: The constructed client.
215 """
216 credentials = service_account.Credentials.from_service_account_info(info)
217 kwargs["credentials"] = credentials
218 return cls(*args, **kwargs)
219
220 @classmethod
221 def from_service_account_file(cls, filename: str, *args, **kwargs):
222 """Creates an instance of this client using the provided credentials
223 file.
224
225 Args:
226 filename (str): The path to the service account private key json
227 file.
228 args: Additional arguments to pass to the constructor.
229 kwargs: Additional arguments to pass to the constructor.
230
231 Returns:
232 SubscriberClient: The constructed client.
233 """
234 credentials = service_account.Credentials.from_service_account_file(filename)
235 kwargs["credentials"] = credentials
236 return cls(*args, **kwargs)
237
238 from_service_account_json = from_service_account_file
239
240 @property
241 def transport(self) -> SubscriberTransport:
242 """Returns the transport used by the client instance.
243
244 Returns:
245 SubscriberTransport: The transport used by the client
246 instance.
247 """
248 return self._transport
249
250 @staticmethod
251 def listing_path(
252 project: str,
253 location: str,
254 data_exchange: str,
255 listing: str,
256 ) -> str:
257 """Returns a fully-qualified listing string."""
258 return "projects/{project}/locations/{location}/dataExchanges/{data_exchange}/listings/{listing}".format(
259 project=project,
260 location=location,
261 data_exchange=data_exchange,
262 listing=listing,
263 )
264
265 @staticmethod
266 def parse_listing_path(path: str) -> Dict[str, str]:
267 """Parses a listing path into its component segments."""
268 m = re.match(
269 r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)/dataExchanges/(?P<data_exchange>.+?)/listings/(?P<listing>.+?)$",
270 path,
271 )
272 return m.groupdict() if m else {}
273
274 @staticmethod
275 def snapshot_path(
276 project: str,
277 snapshot: str,
278 ) -> str:
279 """Returns a fully-qualified snapshot string."""
280 return "projects/{project}/snapshots/{snapshot}".format(
281 project=project,
282 snapshot=snapshot,
283 )
284
285 @staticmethod
286 def parse_snapshot_path(path: str) -> Dict[str, str]:
287 """Parses a snapshot path into its component segments."""
288 m = re.match(r"^projects/(?P<project>.+?)/snapshots/(?P<snapshot>.+?)$", path)
289 return m.groupdict() if m else {}
290
291 @staticmethod
292 def subscription_path(
293 project: str,
294 subscription: str,
295 ) -> str:
296 """Returns a fully-qualified subscription string."""
297 return "projects/{project}/subscriptions/{subscription}".format(
298 project=project,
299 subscription=subscription,
300 )
301
302 @staticmethod
303 def parse_subscription_path(path: str) -> Dict[str, str]:
304 """Parses a subscription path into its component segments."""
305 m = re.match(
306 r"^projects/(?P<project>.+?)/subscriptions/(?P<subscription>.+?)$", path
307 )
308 return m.groupdict() if m else {}
309
310 @staticmethod
311 def topic_path(
312 project: str,
313 topic: str,
314 ) -> str:
315 """Returns a fully-qualified topic string."""
316 return "projects/{project}/topics/{topic}".format(
317 project=project,
318 topic=topic,
319 )
320
321 @staticmethod
322 def parse_topic_path(path: str) -> Dict[str, str]:
323 """Parses a topic path into its component segments."""
324 m = re.match(r"^projects/(?P<project>.+?)/topics/(?P<topic>.+?)$", path)
325 return m.groupdict() if m else {}
326
327 @staticmethod
328 def common_billing_account_path(
329 billing_account: str,
330 ) -> str:
331 """Returns a fully-qualified billing_account string."""
332 return "billingAccounts/{billing_account}".format(
333 billing_account=billing_account,
334 )
335
336 @staticmethod
337 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
338 """Parse a billing_account path into its component segments."""
339 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
340 return m.groupdict() if m else {}
341
342 @staticmethod
343 def common_folder_path(
344 folder: str,
345 ) -> str:
346 """Returns a fully-qualified folder string."""
347 return "folders/{folder}".format(
348 folder=folder,
349 )
350
351 @staticmethod
352 def parse_common_folder_path(path: str) -> Dict[str, str]:
353 """Parse a folder path into its component segments."""
354 m = re.match(r"^folders/(?P<folder>.+?)$", path)
355 return m.groupdict() if m else {}
356
357 @staticmethod
358 def common_organization_path(
359 organization: str,
360 ) -> str:
361 """Returns a fully-qualified organization string."""
362 return "organizations/{organization}".format(
363 organization=organization,
364 )
365
366 @staticmethod
367 def parse_common_organization_path(path: str) -> Dict[str, str]:
368 """Parse a organization path into its component segments."""
369 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
370 return m.groupdict() if m else {}
371
372 @staticmethod
373 def common_project_path(
374 project: str,
375 ) -> str:
376 """Returns a fully-qualified project string."""
377 return "projects/{project}".format(
378 project=project,
379 )
380
381 @staticmethod
382 def parse_common_project_path(path: str) -> Dict[str, str]:
383 """Parse a project path into its component segments."""
384 m = re.match(r"^projects/(?P<project>.+?)$", path)
385 return m.groupdict() if m else {}
386
387 @staticmethod
388 def common_location_path(
389 project: str,
390 location: str,
391 ) -> str:
392 """Returns a fully-qualified location string."""
393 return "projects/{project}/locations/{location}".format(
394 project=project,
395 location=location,
396 )
397
398 @staticmethod
399 def parse_common_location_path(path: str) -> Dict[str, str]:
400 """Parse a location path into its component segments."""
401 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
402 return m.groupdict() if m else {}
403
404 @classmethod
405 def get_mtls_endpoint_and_cert_source(
406 cls, client_options: Optional[client_options_lib.ClientOptions] = None
407 ):
408 """Deprecated. Return the API endpoint and client cert source for mutual TLS.
409
410 The client cert source is determined in the following order:
411 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
412 client cert source is None.
413 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
414 default client cert source exists, use the default one; otherwise the client cert
415 source is None.
416
417 The API endpoint is determined in the following order:
418 (1) if `client_options.api_endpoint` if provided, use the provided one.
419 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
420 default mTLS endpoint; if the environment variable is "never", use the default API
421 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
422 use the default API endpoint.
423
424 More details can be found at https://google.aip.dev/auth/4114.
425
426 Args:
427 client_options (google.api_core.client_options.ClientOptions): Custom options for the
428 client. Only the `api_endpoint` and `client_cert_source` properties may be used
429 in this method.
430
431 Returns:
432 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
433 client cert source to use.
434
435 Raises:
436 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
437 """
438
439 warnings.warn(
440 "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.",
441 DeprecationWarning,
442 )
443 if client_options is None:
444 client_options = client_options_lib.ClientOptions()
445 use_client_cert = SubscriberClient._use_client_cert_effective()
446 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
447 if use_mtls_endpoint not in ("auto", "never", "always"):
448 raise MutualTLSChannelError(
449 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
450 )
451
452 # Figure out the client cert source to use.
453 client_cert_source = None
454 if use_client_cert:
455 if client_options.client_cert_source:
456 client_cert_source = client_options.client_cert_source
457 elif mtls.has_default_client_cert_source():
458 client_cert_source = mtls.default_client_cert_source()
459
460 # Figure out which api endpoint to use.
461 if client_options.api_endpoint is not None:
462 api_endpoint = client_options.api_endpoint
463 elif use_mtls_endpoint == "always" or (
464 use_mtls_endpoint == "auto" and client_cert_source
465 ):
466 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
467 else:
468 api_endpoint = cls.DEFAULT_ENDPOINT
469
470 return api_endpoint, client_cert_source
471
472 @staticmethod
473 def _read_environment_variables():
474 """Returns the environment variables used by the client.
475
476 Returns:
477 Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE,
478 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables.
479
480 Raises:
481 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not
482 any of ["true", "false"].
483 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT
484 is not any of ["auto", "never", "always"].
485 """
486 use_client_cert = SubscriberClient._use_client_cert_effective()
487 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower()
488 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
489 if use_mtls_endpoint not in ("auto", "never", "always"):
490 raise MutualTLSChannelError(
491 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
492 )
493 return use_client_cert, use_mtls_endpoint, universe_domain_env
494
495 @staticmethod
496 def _get_client_cert_source(provided_cert_source, use_cert_flag):
497 """Return the client cert source to be used by the client.
498
499 Args:
500 provided_cert_source (bytes): The client certificate source provided.
501 use_cert_flag (bool): A flag indicating whether to use the client certificate.
502
503 Returns:
504 bytes or None: The client cert source to be used by the client.
505 """
506 client_cert_source = None
507 if use_cert_flag:
508 if provided_cert_source:
509 client_cert_source = provided_cert_source
510 elif mtls.has_default_client_cert_source():
511 client_cert_source = mtls.default_client_cert_source()
512 return client_cert_source
513
514 @staticmethod
515 def _get_api_endpoint(
516 api_override, client_cert_source, universe_domain, use_mtls_endpoint
517 ):
518 """Return the API endpoint used by the client.
519
520 Args:
521 api_override (str): The API endpoint override. If specified, this is always
522 the return value of this function and the other arguments are not used.
523 client_cert_source (bytes): The client certificate source used by the client.
524 universe_domain (str): The universe domain used by the client.
525 use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters.
526 Possible values are "always", "auto", or "never".
527
528 Returns:
529 str: The API endpoint to be used by the client.
530 """
531 if api_override is not None:
532 api_endpoint = api_override
533 elif use_mtls_endpoint == "always" or (
534 use_mtls_endpoint == "auto" and client_cert_source
535 ):
536 _default_universe = SubscriberClient._DEFAULT_UNIVERSE
537 if universe_domain != _default_universe:
538 raise MutualTLSChannelError(
539 f"mTLS is not supported in any universe other than {_default_universe}."
540 )
541 api_endpoint = SubscriberClient.DEFAULT_MTLS_ENDPOINT
542 else:
543 api_endpoint = SubscriberClient._DEFAULT_ENDPOINT_TEMPLATE.format(
544 UNIVERSE_DOMAIN=universe_domain
545 )
546 return api_endpoint
547
548 @staticmethod
549 def _get_universe_domain(
550 client_universe_domain: Optional[str], universe_domain_env: Optional[str]
551 ) -> str:
552 """Return the universe domain used by the client.
553
554 Args:
555 client_universe_domain (Optional[str]): The universe domain configured via the client options.
556 universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
557
558 Returns:
559 str: The universe domain to be used by the client.
560
561 Raises:
562 ValueError: If the universe domain is an empty string.
563 """
564 universe_domain = SubscriberClient._DEFAULT_UNIVERSE
565 if client_universe_domain is not None:
566 universe_domain = client_universe_domain
567 elif universe_domain_env is not None:
568 universe_domain = universe_domain_env
569 if len(universe_domain.strip()) == 0:
570 raise ValueError("Universe Domain cannot be an empty string.")
571 return universe_domain
572
573 def _validate_universe_domain(self):
574 """Validates client's and credentials' universe domains are consistent.
575
576 Returns:
577 bool: True iff the configured universe domain is valid.
578
579 Raises:
580 ValueError: If the configured universe domain is not valid.
581 """
582
583 # NOTE (b/349488459): universe validation is disabled until further notice.
584 return True
585
586 def _add_cred_info_for_auth_errors(
587 self, error: core_exceptions.GoogleAPICallError
588 ) -> None:
589 """Adds credential info string to error details for 401/403/404 errors.
590
591 Args:
592 error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info.
593 """
594 if error.code not in [
595 HTTPStatus.UNAUTHORIZED,
596 HTTPStatus.FORBIDDEN,
597 HTTPStatus.NOT_FOUND,
598 ]:
599 return
600
601 cred = self._transport._credentials
602
603 # get_cred_info is only available in google-auth>=2.35.0
604 if not hasattr(cred, "get_cred_info"):
605 return
606
607 # ignore the type check since pypy test fails when get_cred_info
608 # is not available
609 cred_info = cred.get_cred_info() # type: ignore
610 if cred_info and hasattr(error._details, "append"):
611 error._details.append(json.dumps(cred_info))
612
613 @property
614 def api_endpoint(self):
615 """Return the API endpoint used by the client instance.
616
617 Returns:
618 str: The API endpoint used by the client instance.
619 """
620 return self._api_endpoint
621
622 @property
623 def universe_domain(self) -> str:
624 """Return the universe domain used by the client instance.
625
626 Returns:
627 str: The universe domain used by the client instance.
628 """
629 return self._universe_domain
630
631 def __init__(
632 self,
633 *,
634 credentials: Optional[ga_credentials.Credentials] = None,
635 transport: Optional[
636 Union[str, SubscriberTransport, Callable[..., SubscriberTransport]]
637 ] = None,
638 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
639 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
640 ) -> None:
641 """Instantiates the subscriber client.
642
643 Args:
644 credentials (Optional[google.auth.credentials.Credentials]): The
645 authorization credentials to attach to requests. These
646 credentials identify the application to the service; if none
647 are specified, the client will attempt to ascertain the
648 credentials from the environment.
649 transport (Optional[Union[str,SubscriberTransport,Callable[..., SubscriberTransport]]]):
650 The transport to use, or a Callable that constructs and returns a new transport.
651 If a Callable is given, it will be called with the same set of initialization
652 arguments as used in the SubscriberTransport constructor.
653 If set to None, a transport is chosen automatically.
654 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
655 Custom options for the client.
656
657 1. The ``api_endpoint`` property can be used to override the
658 default endpoint provided by the client when ``transport`` is
659 not explicitly provided. Only if this property is not set and
660 ``transport`` was not explicitly provided, the endpoint is
661 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
662 variable, which have one of the following values:
663 "always" (always use the default mTLS endpoint), "never" (always
664 use the default regular endpoint) and "auto" (auto-switch to the
665 default mTLS endpoint if client certificate is present; this is
666 the default value).
667
668 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
669 is "true", then the ``client_cert_source`` property can be used
670 to provide a client certificate for mTLS transport. If
671 not provided, the default SSL client certificate will be used if
672 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
673 set, no client certificate will be used.
674
675 3. The ``universe_domain`` property can be used to override the
676 default "googleapis.com" universe. Note that the ``api_endpoint``
677 property still takes precedence; and ``universe_domain`` is
678 currently not supported for mTLS.
679
680 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
681 The client info used to send a user-agent string along with
682 API requests. If ``None``, then default info will be used.
683 Generally, you only need to set this if you're developing
684 your own client library.
685
686 Raises:
687 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
688 creation failed for any reason.
689 """
690 self._client_options = client_options
691 if isinstance(self._client_options, dict):
692 self._client_options = client_options_lib.from_dict(self._client_options)
693 if self._client_options is None:
694 self._client_options = client_options_lib.ClientOptions()
695 self._client_options = cast(
696 client_options_lib.ClientOptions, self._client_options
697 )
698
699 universe_domain_opt = getattr(self._client_options, "universe_domain", None)
700
701 (
702 self._use_client_cert,
703 self._use_mtls_endpoint,
704 self._universe_domain_env,
705 ) = SubscriberClient._read_environment_variables()
706 self._client_cert_source = SubscriberClient._get_client_cert_source(
707 self._client_options.client_cert_source, self._use_client_cert
708 )
709 self._universe_domain = SubscriberClient._get_universe_domain(
710 universe_domain_opt, self._universe_domain_env
711 )
712 self._api_endpoint = None # updated below, depending on `transport`
713
714 # Initialize the universe domain validation.
715 self._is_universe_domain_valid = False
716
717 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
718 # Setup logging.
719 client_logging.initialize_logging()
720
721 api_key_value = getattr(self._client_options, "api_key", None)
722 if api_key_value and credentials:
723 raise ValueError(
724 "client_options.api_key and credentials are mutually exclusive"
725 )
726
727 # Save or instantiate the transport.
728 # Ordinarily, we provide the transport, but allowing a custom transport
729 # instance provides an extensibility point for unusual situations.
730 transport_provided = isinstance(transport, SubscriberTransport)
731 if transport_provided:
732 # transport is a SubscriberTransport instance.
733 if credentials or self._client_options.credentials_file or api_key_value:
734 raise ValueError(
735 "When providing a transport instance, "
736 "provide its credentials directly."
737 )
738 if self._client_options.scopes:
739 raise ValueError(
740 "When providing a transport instance, provide its scopes "
741 "directly."
742 )
743 self._transport = cast(SubscriberTransport, transport)
744 self._api_endpoint = self._transport.host
745
746 self._api_endpoint = self._api_endpoint or SubscriberClient._get_api_endpoint(
747 self._client_options.api_endpoint,
748 self._client_cert_source,
749 self._universe_domain,
750 self._use_mtls_endpoint,
751 )
752
753 if not transport_provided:
754 import google.auth._default # type: ignore
755
756 if api_key_value and hasattr(
757 google.auth._default, "get_api_key_credentials"
758 ):
759 credentials = google.auth._default.get_api_key_credentials(
760 api_key_value
761 )
762
763 transport_init: Union[
764 Type[SubscriberTransport], Callable[..., SubscriberTransport]
765 ] = (
766 SubscriberClient.get_transport_class(transport)
767 if isinstance(transport, str) or transport is None
768 else cast(Callable[..., SubscriberTransport], transport)
769 )
770 # initialize with the provided callable or the passed in class
771
772 emulator_host = os.environ.get("PUBSUB_EMULATOR_HOST")
773 if emulator_host:
774 if issubclass(transport_init, type(self)._transport_registry["grpc"]): # type: ignore
775 channel = grpc.insecure_channel(target=emulator_host)
776 else:
777 channel = grpc.aio.insecure_channel(target=emulator_host)
778 transport_init = functools.partial(transport_init, channel=channel)
779
780 self._transport = transport_init(
781 credentials=credentials,
782 credentials_file=self._client_options.credentials_file,
783 host=self._api_endpoint,
784 scopes=self._client_options.scopes,
785 client_cert_source_for_mtls=self._client_cert_source,
786 quota_project_id=self._client_options.quota_project_id,
787 client_info=client_info,
788 always_use_jwt_access=True,
789 api_audience=self._client_options.api_audience,
790 )
791
792 if "async" not in str(self._transport):
793 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
794 std_logging.DEBUG
795 ): # pragma: NO COVER
796 _LOGGER.debug(
797 "Created client `google.pubsub_v1.SubscriberClient`.",
798 extra={
799 "serviceName": "google.pubsub.v1.Subscriber",
800 "universeDomain": getattr(
801 self._transport._credentials, "universe_domain", ""
802 ),
803 "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
804 "credentialsInfo": getattr(
805 self.transport._credentials, "get_cred_info", lambda: None
806 )(),
807 }
808 if hasattr(self._transport, "_credentials")
809 else {
810 "serviceName": "google.pubsub.v1.Subscriber",
811 "credentialsType": None,
812 },
813 )
814
815 def create_subscription(
816 self,
817 request: Optional[Union[pubsub.Subscription, dict]] = None,
818 *,
819 name: Optional[str] = None,
820 topic: Optional[str] = None,
821 push_config: Optional[pubsub.PushConfig] = None,
822 ack_deadline_seconds: Optional[int] = None,
823 retry: OptionalRetry = gapic_v1.method.DEFAULT,
824 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
825 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
826 ) -> pubsub.Subscription:
827 r"""Creates a subscription to a given topic. See the [resource name
828 rules]
829 (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names).
830 If the subscription already exists, returns ``ALREADY_EXISTS``.
831 If the corresponding topic doesn't exist, returns ``NOT_FOUND``.
832
833 If the name is not provided in the request, the server will
834 assign a random name for this subscription on the same project
835 as the topic, conforming to the [resource name format]
836 (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names).
837 The generated name is populated in the returned Subscription
838 object. Note that for REST API requests, you must specify a name
839 in the request.
840
841 .. code-block:: python
842
843 # This snippet has been automatically generated and should be regarded as a
844 # code template only.
845 # It will require modifications to work:
846 # - It may require correct/in-range values for request initialization.
847 # - It may require specifying regional endpoints when creating the service
848 # client as shown in:
849 # https://googleapis.dev/python/google-api-core/latest/client_options.html
850 from google import pubsub_v1
851
852 def sample_create_subscription():
853 # Create a client
854 client = pubsub_v1.SubscriberClient()
855
856 # Initialize request argument(s)
857 request = pubsub_v1.Subscription(
858 name="name_value",
859 topic="topic_value",
860 )
861
862 # Make the request
863 response = client.create_subscription(request=request)
864
865 # Handle the response
866 print(response)
867
868 Args:
869 request (Union[google.pubsub_v1.types.Subscription, dict]):
870 The request object. A subscription resource. If none of ``push_config``,
871 ``bigquery_config``, or ``cloud_storage_config`` is set,
872 then the subscriber will pull and ack messages using API
873 methods. At most one of these fields may be set.
874 name (str):
875 Required. The name of the subscription. It must have the
876 format
877 ``"projects/{project}/subscriptions/{subscription}"``.
878 ``{subscription}`` must start with a letter, and contain
879 only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes
880 (``-``), underscores (``_``), periods (``.``), tildes
881 (``~``), plus (``+``) or percent signs (``%``). It must
882 be between 3 and 255 characters in length, and it must
883 not start with ``"goog"``.
884
885 This corresponds to the ``name`` field
886 on the ``request`` instance; if ``request`` is provided, this
887 should not be set.
888 topic (str):
889 Required. The name of the topic from which this
890 subscription is receiving messages. Format is
891 ``projects/{project}/topics/{topic}``. The value of this
892 field will be ``_deleted-topic_`` if the topic has been
893 deleted.
894
895 This corresponds to the ``topic`` field
896 on the ``request`` instance; if ``request`` is provided, this
897 should not be set.
898 push_config (google.pubsub_v1.types.PushConfig):
899 Optional. If push delivery is used
900 with this subscription, this field is
901 used to configure it.
902
903 This corresponds to the ``push_config`` field
904 on the ``request`` instance; if ``request`` is provided, this
905 should not be set.
906 ack_deadline_seconds (int):
907 Optional. The approximate amount of time (on a
908 best-effort basis) Pub/Sub waits for the subscriber to
909 acknowledge receipt before resending the message. In the
910 interval after the message is delivered and before it is
911 acknowledged, it is considered to be *outstanding*.
912 During that time period, the message will not be
913 redelivered (on a best-effort basis).
914
915 For pull subscriptions, this value is used as the
916 initial value for the ack deadline. To override this
917 value for a given message, call ``ModifyAckDeadline``
918 with the corresponding ``ack_id`` if using non-streaming
919 pull or send the ``ack_id`` in a
920 ``StreamingModifyAckDeadlineRequest`` if using streaming
921 pull. The minimum custom deadline you can specify is 10
922 seconds. The maximum custom deadline you can specify is
923 600 seconds (10 minutes). If this parameter is 0, a
924 default value of 10 seconds is used.
925
926 For push delivery, this value is also used to set the
927 request timeout for the call to the push endpoint.
928
929 If the subscriber never acknowledges the message, the
930 Pub/Sub system will eventually redeliver the message.
931
932 This corresponds to the ``ack_deadline_seconds`` field
933 on the ``request`` instance; if ``request`` is provided, this
934 should not be set.
935 retry (google.api_core.retry.Retry): Designation of what errors, if any,
936 should be retried.
937 timeout (float): The timeout for this request.
938 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
939 sent along with the request as metadata. Normally, each value must be of type `str`,
940 but for metadata keys ending with the suffix `-bin`, the corresponding values must
941 be of type `bytes`.
942
943 Returns:
944 google.pubsub_v1.types.Subscription:
945 A subscription resource. If none of push_config, bigquery_config, or
946 cloud_storage_config is set, then the subscriber will
947 pull and ack messages using API methods. At most one
948 of these fields may be set.
949
950 """
951 # Create or coerce a protobuf request object.
952 # - Quick check: If we got a request object, we should *not* have
953 # gotten any keyword arguments that map to the request.
954 flattened_params = [name, topic, push_config, ack_deadline_seconds]
955 has_flattened_params = (
956 len([param for param in flattened_params if param is not None]) > 0
957 )
958 if request is not None and has_flattened_params:
959 raise ValueError(
960 "If the `request` argument is set, then none of "
961 "the individual field arguments should be set."
962 )
963
964 # - Use the request object if provided (there's no risk of modifying the input as
965 # there are no flattened fields), or create one.
966 if not isinstance(request, pubsub.Subscription):
967 request = pubsub.Subscription(request)
968 # If we have keyword arguments corresponding to fields on the
969 # request, apply these.
970 if name is not None:
971 request.name = name
972 if topic is not None:
973 request.topic = topic
974 if push_config is not None:
975 request.push_config = push_config
976 if ack_deadline_seconds is not None:
977 request.ack_deadline_seconds = ack_deadline_seconds
978
979 # Wrap the RPC method; this adds retry and timeout information,
980 # and friendly error handling.
981 rpc = self._transport._wrapped_methods[self._transport.create_subscription]
982
983 # Certain fields should be provided within the metadata header;
984 # add these here.
985 metadata = tuple(metadata) + (
986 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
987 )
988
989 # Validate the universe domain.
990 self._validate_universe_domain()
991
992 # Send the request.
993 response = rpc(
994 request,
995 retry=retry,
996 timeout=timeout,
997 metadata=metadata,
998 )
999
1000 # Done; return the response.
1001 return response
1002
1003 def get_subscription(
1004 self,
1005 request: Optional[Union[pubsub.GetSubscriptionRequest, dict]] = None,
1006 *,
1007 subscription: Optional[str] = None,
1008 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1009 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1010 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1011 ) -> pubsub.Subscription:
1012 r"""Gets the configuration details of a subscription.
1013
1014 .. code-block:: python
1015
1016 # This snippet has been automatically generated and should be regarded as a
1017 # code template only.
1018 # It will require modifications to work:
1019 # - It may require correct/in-range values for request initialization.
1020 # - It may require specifying regional endpoints when creating the service
1021 # client as shown in:
1022 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1023 from google import pubsub_v1
1024
1025 def sample_get_subscription():
1026 # Create a client
1027 client = pubsub_v1.SubscriberClient()
1028
1029 # Initialize request argument(s)
1030 request = pubsub_v1.GetSubscriptionRequest(
1031 subscription="subscription_value",
1032 )
1033
1034 # Make the request
1035 response = client.get_subscription(request=request)
1036
1037 # Handle the response
1038 print(response)
1039
1040 Args:
1041 request (Union[google.pubsub_v1.types.GetSubscriptionRequest, dict]):
1042 The request object. Request for the GetSubscription
1043 method.
1044 subscription (str):
1045 Required. The name of the subscription to get. Format is
1046 ``projects/{project}/subscriptions/{sub}``.
1047
1048 This corresponds to the ``subscription`` field
1049 on the ``request`` instance; if ``request`` is provided, this
1050 should not be set.
1051 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1052 should be retried.
1053 timeout (float): The timeout for this request.
1054 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1055 sent along with the request as metadata. Normally, each value must be of type `str`,
1056 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1057 be of type `bytes`.
1058
1059 Returns:
1060 google.pubsub_v1.types.Subscription:
1061 A subscription resource. If none of push_config, bigquery_config, or
1062 cloud_storage_config is set, then the subscriber will
1063 pull and ack messages using API methods. At most one
1064 of these fields may be set.
1065
1066 """
1067 # Create or coerce a protobuf request object.
1068 # - Quick check: If we got a request object, we should *not* have
1069 # gotten any keyword arguments that map to the request.
1070 flattened_params = [subscription]
1071 has_flattened_params = (
1072 len([param for param in flattened_params if param is not None]) > 0
1073 )
1074 if request is not None and has_flattened_params:
1075 raise ValueError(
1076 "If the `request` argument is set, then none of "
1077 "the individual field arguments should be set."
1078 )
1079
1080 # - Use the request object if provided (there's no risk of modifying the input as
1081 # there are no flattened fields), or create one.
1082 if not isinstance(request, pubsub.GetSubscriptionRequest):
1083 request = pubsub.GetSubscriptionRequest(request)
1084 # If we have keyword arguments corresponding to fields on the
1085 # request, apply these.
1086 if subscription is not None:
1087 request.subscription = subscription
1088
1089 # Wrap the RPC method; this adds retry and timeout information,
1090 # and friendly error handling.
1091 rpc = self._transport._wrapped_methods[self._transport.get_subscription]
1092
1093 # Certain fields should be provided within the metadata header;
1094 # add these here.
1095 metadata = tuple(metadata) + (
1096 gapic_v1.routing_header.to_grpc_metadata(
1097 (("subscription", request.subscription),)
1098 ),
1099 )
1100
1101 # Validate the universe domain.
1102 self._validate_universe_domain()
1103
1104 # Send the request.
1105 response = rpc(
1106 request,
1107 retry=retry,
1108 timeout=timeout,
1109 metadata=metadata,
1110 )
1111
1112 # Done; return the response.
1113 return response
1114
1115 def update_subscription(
1116 self,
1117 request: Optional[Union[pubsub.UpdateSubscriptionRequest, dict]] = None,
1118 *,
1119 subscription: Optional[pubsub.Subscription] = None,
1120 update_mask: Optional[field_mask_pb2.FieldMask] = None,
1121 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1122 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1123 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1124 ) -> pubsub.Subscription:
1125 r"""Updates an existing subscription by updating the
1126 fields specified in the update mask. Note that certain
1127 properties of a subscription, such as its topic, are not
1128 modifiable.
1129
1130 .. code-block:: python
1131
1132 # This snippet has been automatically generated and should be regarded as a
1133 # code template only.
1134 # It will require modifications to work:
1135 # - It may require correct/in-range values for request initialization.
1136 # - It may require specifying regional endpoints when creating the service
1137 # client as shown in:
1138 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1139 from google import pubsub_v1
1140
1141 def sample_update_subscription():
1142 # Create a client
1143 client = pubsub_v1.SubscriberClient()
1144
1145 # Initialize request argument(s)
1146 subscription = pubsub_v1.Subscription()
1147 subscription.name = "name_value"
1148 subscription.topic = "topic_value"
1149
1150 request = pubsub_v1.UpdateSubscriptionRequest(
1151 subscription=subscription,
1152 )
1153
1154 # Make the request
1155 response = client.update_subscription(request=request)
1156
1157 # Handle the response
1158 print(response)
1159
1160 Args:
1161 request (Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]):
1162 The request object. Request for the UpdateSubscription
1163 method.
1164 subscription (google.pubsub_v1.types.Subscription):
1165 Required. The updated subscription
1166 object.
1167
1168 This corresponds to the ``subscription`` field
1169 on the ``request`` instance; if ``request`` is provided, this
1170 should not be set.
1171 update_mask (google.protobuf.field_mask_pb2.FieldMask):
1172 Required. Indicates which fields in
1173 the provided subscription to update.
1174 Must be specified and non-empty.
1175
1176 This corresponds to the ``update_mask`` field
1177 on the ``request`` instance; if ``request`` is provided, this
1178 should not be set.
1179 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1180 should be retried.
1181 timeout (float): The timeout for this request.
1182 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1183 sent along with the request as metadata. Normally, each value must be of type `str`,
1184 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1185 be of type `bytes`.
1186
1187 Returns:
1188 google.pubsub_v1.types.Subscription:
1189 A subscription resource. If none of push_config, bigquery_config, or
1190 cloud_storage_config is set, then the subscriber will
1191 pull and ack messages using API methods. At most one
1192 of these fields may be set.
1193
1194 """
1195 # Create or coerce a protobuf request object.
1196 # - Quick check: If we got a request object, we should *not* have
1197 # gotten any keyword arguments that map to the request.
1198 flattened_params = [subscription, update_mask]
1199 has_flattened_params = (
1200 len([param for param in flattened_params if param is not None]) > 0
1201 )
1202 if request is not None and has_flattened_params:
1203 raise ValueError(
1204 "If the `request` argument is set, then none of "
1205 "the individual field arguments should be set."
1206 )
1207
1208 # - Use the request object if provided (there's no risk of modifying the input as
1209 # there are no flattened fields), or create one.
1210 if not isinstance(request, pubsub.UpdateSubscriptionRequest):
1211 request = pubsub.UpdateSubscriptionRequest(request)
1212 # If we have keyword arguments corresponding to fields on the
1213 # request, apply these.
1214 if subscription is not None:
1215 request.subscription = subscription
1216 if update_mask is not None:
1217 request.update_mask = update_mask
1218
1219 # Wrap the RPC method; this adds retry and timeout information,
1220 # and friendly error handling.
1221 rpc = self._transport._wrapped_methods[self._transport.update_subscription]
1222
1223 # Certain fields should be provided within the metadata header;
1224 # add these here.
1225 metadata = tuple(metadata) + (
1226 gapic_v1.routing_header.to_grpc_metadata(
1227 (("subscription.name", request.subscription.name),)
1228 ),
1229 )
1230
1231 # Validate the universe domain.
1232 self._validate_universe_domain()
1233
1234 # Send the request.
1235 response = rpc(
1236 request,
1237 retry=retry,
1238 timeout=timeout,
1239 metadata=metadata,
1240 )
1241
1242 # Done; return the response.
1243 return response
1244
1245 def list_subscriptions(
1246 self,
1247 request: Optional[Union[pubsub.ListSubscriptionsRequest, dict]] = None,
1248 *,
1249 project: Optional[str] = None,
1250 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1251 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1252 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1253 ) -> pagers.ListSubscriptionsPager:
1254 r"""Lists matching subscriptions.
1255
1256 .. code-block:: python
1257
1258 # This snippet has been automatically generated and should be regarded as a
1259 # code template only.
1260 # It will require modifications to work:
1261 # - It may require correct/in-range values for request initialization.
1262 # - It may require specifying regional endpoints when creating the service
1263 # client as shown in:
1264 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1265 from google import pubsub_v1
1266
1267 def sample_list_subscriptions():
1268 # Create a client
1269 client = pubsub_v1.SubscriberClient()
1270
1271 # Initialize request argument(s)
1272 request = pubsub_v1.ListSubscriptionsRequest(
1273 project="project_value",
1274 )
1275
1276 # Make the request
1277 page_result = client.list_subscriptions(request=request)
1278
1279 # Handle the response
1280 for response in page_result:
1281 print(response)
1282
1283 Args:
1284 request (Union[google.pubsub_v1.types.ListSubscriptionsRequest, dict]):
1285 The request object. Request for the ``ListSubscriptions`` method.
1286 project (str):
1287 Required. The name of the project in which to list
1288 subscriptions. Format is ``projects/{project-id}``.
1289
1290 This corresponds to the ``project`` field
1291 on the ``request`` instance; if ``request`` is provided, this
1292 should not be set.
1293 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1294 should be retried.
1295 timeout (float): The timeout for this request.
1296 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1297 sent along with the request as metadata. Normally, each value must be of type `str`,
1298 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1299 be of type `bytes`.
1300
1301 Returns:
1302 google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsPager:
1303 Response for the ListSubscriptions method.
1304
1305 Iterating over this object will yield results and
1306 resolve additional pages automatically.
1307
1308 """
1309 # Create or coerce a protobuf request object.
1310 # - Quick check: If we got a request object, we should *not* have
1311 # gotten any keyword arguments that map to the request.
1312 flattened_params = [project]
1313 has_flattened_params = (
1314 len([param for param in flattened_params if param is not None]) > 0
1315 )
1316 if request is not None and has_flattened_params:
1317 raise ValueError(
1318 "If the `request` argument is set, then none of "
1319 "the individual field arguments should be set."
1320 )
1321
1322 # - Use the request object if provided (there's no risk of modifying the input as
1323 # there are no flattened fields), or create one.
1324 if not isinstance(request, pubsub.ListSubscriptionsRequest):
1325 request = pubsub.ListSubscriptionsRequest(request)
1326 # If we have keyword arguments corresponding to fields on the
1327 # request, apply these.
1328 if project is not None:
1329 request.project = project
1330
1331 # Wrap the RPC method; this adds retry and timeout information,
1332 # and friendly error handling.
1333 rpc = self._transport._wrapped_methods[self._transport.list_subscriptions]
1334
1335 # Certain fields should be provided within the metadata header;
1336 # add these here.
1337 metadata = tuple(metadata) + (
1338 gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)),
1339 )
1340
1341 # Validate the universe domain.
1342 self._validate_universe_domain()
1343
1344 # Send the request.
1345 response = rpc(
1346 request,
1347 retry=retry,
1348 timeout=timeout,
1349 metadata=metadata,
1350 )
1351
1352 # This method is paged; wrap the response in a pager, which provides
1353 # an `__iter__` convenience method.
1354 response = pagers.ListSubscriptionsPager(
1355 method=rpc,
1356 request=request,
1357 response=response,
1358 retry=retry,
1359 timeout=timeout,
1360 metadata=metadata,
1361 )
1362
1363 # Done; return the response.
1364 return response
1365
1366 def delete_subscription(
1367 self,
1368 request: Optional[Union[pubsub.DeleteSubscriptionRequest, dict]] = None,
1369 *,
1370 subscription: Optional[str] = None,
1371 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1372 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1373 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1374 ) -> None:
1375 r"""Deletes an existing subscription. All messages retained in the
1376 subscription are immediately dropped. Calls to ``Pull`` after
1377 deletion will return ``NOT_FOUND``. After a subscription is
1378 deleted, a new one may be created with the same name, but the
1379 new one has no association with the old subscription or its
1380 topic unless the same topic is specified.
1381
1382 .. code-block:: python
1383
1384 # This snippet has been automatically generated and should be regarded as a
1385 # code template only.
1386 # It will require modifications to work:
1387 # - It may require correct/in-range values for request initialization.
1388 # - It may require specifying regional endpoints when creating the service
1389 # client as shown in:
1390 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1391 from google import pubsub_v1
1392
1393 def sample_delete_subscription():
1394 # Create a client
1395 client = pubsub_v1.SubscriberClient()
1396
1397 # Initialize request argument(s)
1398 request = pubsub_v1.DeleteSubscriptionRequest(
1399 subscription="subscription_value",
1400 )
1401
1402 # Make the request
1403 client.delete_subscription(request=request)
1404
1405 Args:
1406 request (Union[google.pubsub_v1.types.DeleteSubscriptionRequest, dict]):
1407 The request object. Request for the DeleteSubscription
1408 method.
1409 subscription (str):
1410 Required. The subscription to delete. Format is
1411 ``projects/{project}/subscriptions/{sub}``.
1412
1413 This corresponds to the ``subscription`` field
1414 on the ``request`` instance; if ``request`` is provided, this
1415 should not be set.
1416 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1417 should be retried.
1418 timeout (float): The timeout for this request.
1419 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1420 sent along with the request as metadata. Normally, each value must be of type `str`,
1421 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1422 be of type `bytes`.
1423 """
1424 # Create or coerce a protobuf request object.
1425 # - Quick check: If we got a request object, we should *not* have
1426 # gotten any keyword arguments that map to the request.
1427 flattened_params = [subscription]
1428 has_flattened_params = (
1429 len([param for param in flattened_params if param is not None]) > 0
1430 )
1431 if request is not None and has_flattened_params:
1432 raise ValueError(
1433 "If the `request` argument is set, then none of "
1434 "the individual field arguments should be set."
1435 )
1436
1437 # - Use the request object if provided (there's no risk of modifying the input as
1438 # there are no flattened fields), or create one.
1439 if not isinstance(request, pubsub.DeleteSubscriptionRequest):
1440 request = pubsub.DeleteSubscriptionRequest(request)
1441 # If we have keyword arguments corresponding to fields on the
1442 # request, apply these.
1443 if subscription is not None:
1444 request.subscription = subscription
1445
1446 # Wrap the RPC method; this adds retry and timeout information,
1447 # and friendly error handling.
1448 rpc = self._transport._wrapped_methods[self._transport.delete_subscription]
1449
1450 # Certain fields should be provided within the metadata header;
1451 # add these here.
1452 metadata = tuple(metadata) + (
1453 gapic_v1.routing_header.to_grpc_metadata(
1454 (("subscription", request.subscription),)
1455 ),
1456 )
1457
1458 # Validate the universe domain.
1459 self._validate_universe_domain()
1460
1461 # Send the request.
1462 rpc(
1463 request,
1464 retry=retry,
1465 timeout=timeout,
1466 metadata=metadata,
1467 )
1468
1469 def modify_ack_deadline(
1470 self,
1471 request: Optional[Union[pubsub.ModifyAckDeadlineRequest, dict]] = None,
1472 *,
1473 subscription: Optional[str] = None,
1474 ack_ids: Optional[MutableSequence[str]] = None,
1475 ack_deadline_seconds: Optional[int] = None,
1476 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1477 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1478 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1479 ) -> None:
1480 r"""Modifies the ack deadline for a specific message. This method is
1481 useful to indicate that more time is needed to process a message
1482 by the subscriber, or to make the message available for
1483 redelivery if the processing was interrupted. Note that this
1484 does not modify the subscription-level ``ackDeadlineSeconds``
1485 used for subsequent messages.
1486
1487 .. code-block:: python
1488
1489 # This snippet has been automatically generated and should be regarded as a
1490 # code template only.
1491 # It will require modifications to work:
1492 # - It may require correct/in-range values for request initialization.
1493 # - It may require specifying regional endpoints when creating the service
1494 # client as shown in:
1495 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1496 from google import pubsub_v1
1497
1498 def sample_modify_ack_deadline():
1499 # Create a client
1500 client = pubsub_v1.SubscriberClient()
1501
1502 # Initialize request argument(s)
1503 request = pubsub_v1.ModifyAckDeadlineRequest(
1504 subscription="subscription_value",
1505 ack_ids=['ack_ids_value1', 'ack_ids_value2'],
1506 ack_deadline_seconds=2066,
1507 )
1508
1509 # Make the request
1510 client.modify_ack_deadline(request=request)
1511
1512 Args:
1513 request (Union[google.pubsub_v1.types.ModifyAckDeadlineRequest, dict]):
1514 The request object. Request for the ModifyAckDeadline
1515 method.
1516 subscription (str):
1517 Required. The name of the subscription. Format is
1518 ``projects/{project}/subscriptions/{sub}``.
1519
1520 This corresponds to the ``subscription`` field
1521 on the ``request`` instance; if ``request`` is provided, this
1522 should not be set.
1523 ack_ids (MutableSequence[str]):
1524 Required. List of acknowledgment IDs.
1525 This corresponds to the ``ack_ids`` field
1526 on the ``request`` instance; if ``request`` is provided, this
1527 should not be set.
1528 ack_deadline_seconds (int):
1529 Required. The new ack deadline with respect to the time
1530 this request was sent to the Pub/Sub system. For
1531 example, if the value is 10, the new ack deadline will
1532 expire 10 seconds after the ``ModifyAckDeadline`` call
1533 was made. Specifying zero might immediately make the
1534 message available for delivery to another subscriber
1535 client. This typically results in an increase in the
1536 rate of message redeliveries (that is, duplicates). The
1537 minimum deadline you can specify is 0 seconds. The
1538 maximum deadline you can specify in a single request is
1539 600 seconds (10 minutes).
1540
1541 This corresponds to the ``ack_deadline_seconds`` field
1542 on the ``request`` instance; if ``request`` is provided, this
1543 should not be set.
1544 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1545 should be retried.
1546 timeout (float): The timeout for this request.
1547 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1548 sent along with the request as metadata. Normally, each value must be of type `str`,
1549 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1550 be of type `bytes`.
1551 """
1552 # Create or coerce a protobuf request object.
1553 # - Quick check: If we got a request object, we should *not* have
1554 # gotten any keyword arguments that map to the request.
1555 flattened_params = [subscription, ack_ids, ack_deadline_seconds]
1556 has_flattened_params = (
1557 len([param for param in flattened_params if param is not None]) > 0
1558 )
1559 if request is not None and has_flattened_params:
1560 raise ValueError(
1561 "If the `request` argument is set, then none of "
1562 "the individual field arguments should be set."
1563 )
1564
1565 # - Use the request object if provided (there's no risk of modifying the input as
1566 # there are no flattened fields), or create one.
1567 if not isinstance(request, pubsub.ModifyAckDeadlineRequest):
1568 request = pubsub.ModifyAckDeadlineRequest(request)
1569 # If we have keyword arguments corresponding to fields on the
1570 # request, apply these.
1571 if subscription is not None:
1572 request.subscription = subscription
1573 if ack_ids is not None:
1574 request.ack_ids = ack_ids
1575 if ack_deadline_seconds is not None:
1576 request.ack_deadline_seconds = ack_deadline_seconds
1577
1578 # Wrap the RPC method; this adds retry and timeout information,
1579 # and friendly error handling.
1580 rpc = self._transport._wrapped_methods[self._transport.modify_ack_deadline]
1581
1582 # Certain fields should be provided within the metadata header;
1583 # add these here.
1584 metadata = tuple(metadata) + (
1585 gapic_v1.routing_header.to_grpc_metadata(
1586 (("subscription", request.subscription),)
1587 ),
1588 )
1589
1590 # Validate the universe domain.
1591 self._validate_universe_domain()
1592
1593 # Send the request.
1594 rpc(
1595 request,
1596 retry=retry,
1597 timeout=timeout,
1598 metadata=metadata,
1599 )
1600
1601 def acknowledge(
1602 self,
1603 request: Optional[Union[pubsub.AcknowledgeRequest, dict]] = None,
1604 *,
1605 subscription: Optional[str] = None,
1606 ack_ids: Optional[MutableSequence[str]] = None,
1607 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1608 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1609 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1610 ) -> None:
1611 r"""Acknowledges the messages associated with the ``ack_ids`` in the
1612 ``AcknowledgeRequest``. The Pub/Sub system can remove the
1613 relevant messages from the subscription.
1614
1615 Acknowledging a message whose ack deadline has expired may
1616 succeed, but such a message may be redelivered later.
1617 Acknowledging a message more than once will not result in an
1618 error.
1619
1620 .. code-block:: python
1621
1622 # This snippet has been automatically generated and should be regarded as a
1623 # code template only.
1624 # It will require modifications to work:
1625 # - It may require correct/in-range values for request initialization.
1626 # - It may require specifying regional endpoints when creating the service
1627 # client as shown in:
1628 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1629 from google import pubsub_v1
1630
1631 def sample_acknowledge():
1632 # Create a client
1633 client = pubsub_v1.SubscriberClient()
1634
1635 # Initialize request argument(s)
1636 request = pubsub_v1.AcknowledgeRequest(
1637 subscription="subscription_value",
1638 ack_ids=['ack_ids_value1', 'ack_ids_value2'],
1639 )
1640
1641 # Make the request
1642 client.acknowledge(request=request)
1643
1644 Args:
1645 request (Union[google.pubsub_v1.types.AcknowledgeRequest, dict]):
1646 The request object. Request for the Acknowledge method.
1647 subscription (str):
1648 Required. The subscription whose message is being
1649 acknowledged. Format is
1650 ``projects/{project}/subscriptions/{sub}``.
1651
1652 This corresponds to the ``subscription`` field
1653 on the ``request`` instance; if ``request`` is provided, this
1654 should not be set.
1655 ack_ids (MutableSequence[str]):
1656 Required. The acknowledgment ID for the messages being
1657 acknowledged that was returned by the Pub/Sub system in
1658 the ``Pull`` response. Must not be empty.
1659
1660 This corresponds to the ``ack_ids`` 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, Union[str, bytes]]]): Key/value pairs which should be
1667 sent along with the request as metadata. Normally, each value must be of type `str`,
1668 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1669 be of type `bytes`.
1670 """
1671 # Create or coerce a protobuf request object.
1672 # - Quick check: If we got a request object, we should *not* have
1673 # gotten any keyword arguments that map to the request.
1674 flattened_params = [subscription, ack_ids]
1675 has_flattened_params = (
1676 len([param for param in flattened_params if param is not None]) > 0
1677 )
1678 if request is not None and has_flattened_params:
1679 raise ValueError(
1680 "If the `request` argument is set, then none of "
1681 "the individual field arguments should be set."
1682 )
1683
1684 # - Use the request object if provided (there's no risk of modifying the input as
1685 # there are no flattened fields), or create one.
1686 if not isinstance(request, pubsub.AcknowledgeRequest):
1687 request = pubsub.AcknowledgeRequest(request)
1688 # If we have keyword arguments corresponding to fields on the
1689 # request, apply these.
1690 if subscription is not None:
1691 request.subscription = subscription
1692 if ack_ids is not None:
1693 request.ack_ids = ack_ids
1694
1695 # Wrap the RPC method; this adds retry and timeout information,
1696 # and friendly error handling.
1697 rpc = self._transport._wrapped_methods[self._transport.acknowledge]
1698
1699 # Certain fields should be provided within the metadata header;
1700 # add these here.
1701 metadata = tuple(metadata) + (
1702 gapic_v1.routing_header.to_grpc_metadata(
1703 (("subscription", request.subscription),)
1704 ),
1705 )
1706
1707 # Validate the universe domain.
1708 self._validate_universe_domain()
1709
1710 # Send the request.
1711 rpc(
1712 request,
1713 retry=retry,
1714 timeout=timeout,
1715 metadata=metadata,
1716 )
1717
1718 def pull(
1719 self,
1720 request: Optional[Union[pubsub.PullRequest, dict]] = None,
1721 *,
1722 subscription: Optional[str] = None,
1723 return_immediately: Optional[bool] = None,
1724 max_messages: Optional[int] = None,
1725 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1726 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1727 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1728 ) -> pubsub.PullResponse:
1729 r"""Pulls messages from the server.
1730
1731 .. code-block:: python
1732
1733 # This snippet has been automatically generated and should be regarded as a
1734 # code template only.
1735 # It will require modifications to work:
1736 # - It may require correct/in-range values for request initialization.
1737 # - It may require specifying regional endpoints when creating the service
1738 # client as shown in:
1739 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1740 from google import pubsub_v1
1741
1742 def sample_pull():
1743 # Create a client
1744 client = pubsub_v1.SubscriberClient()
1745
1746 # Initialize request argument(s)
1747 request = pubsub_v1.PullRequest(
1748 subscription="subscription_value",
1749 max_messages=1277,
1750 )
1751
1752 # Make the request
1753 response = client.pull(request=request)
1754
1755 # Handle the response
1756 print(response)
1757
1758 Args:
1759 request (Union[google.pubsub_v1.types.PullRequest, dict]):
1760 The request object. Request for the ``Pull`` method.
1761 subscription (str):
1762 Required. The subscription from which messages should be
1763 pulled. Format is
1764 ``projects/{project}/subscriptions/{sub}``.
1765
1766 This corresponds to the ``subscription`` field
1767 on the ``request`` instance; if ``request`` is provided, this
1768 should not be set.
1769 return_immediately (bool):
1770 Optional. If this field set to true, the system will
1771 respond immediately even if it there are no messages
1772 available to return in the ``Pull`` response. Otherwise,
1773 the system may wait (for a bounded amount of time) until
1774 at least one message is available, rather than returning
1775 no messages. Warning: setting this field to ``true`` is
1776 discouraged because it adversely impacts the performance
1777 of ``Pull`` operations. We recommend that users do not
1778 set this field.
1779
1780 This corresponds to the ``return_immediately`` field
1781 on the ``request`` instance; if ``request`` is provided, this
1782 should not be set.
1783 max_messages (int):
1784 Required. The maximum number of
1785 messages to return for this request.
1786 Must be a positive integer. The Pub/Sub
1787 system may return fewer than the number
1788 specified.
1789
1790 This corresponds to the ``max_messages`` field
1791 on the ``request`` instance; if ``request`` is provided, this
1792 should not be set.
1793 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1794 should be retried.
1795 timeout (float): The timeout for this request.
1796 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1797 sent along with the request as metadata. Normally, each value must be of type `str`,
1798 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1799 be of type `bytes`.
1800
1801 Returns:
1802 google.pubsub_v1.types.PullResponse:
1803 Response for the Pull method.
1804 """
1805 # Create or coerce a protobuf request object.
1806 # - Quick check: If we got a request object, we should *not* have
1807 # gotten any keyword arguments that map to the request.
1808 flattened_params = [subscription, return_immediately, max_messages]
1809 has_flattened_params = (
1810 len([param for param in flattened_params if param is not None]) > 0
1811 )
1812 if request is not None and has_flattened_params:
1813 raise ValueError(
1814 "If the `request` argument is set, then none of "
1815 "the individual field arguments should be set."
1816 )
1817
1818 # - Use the request object if provided (there's no risk of modifying the input as
1819 # there are no flattened fields), or create one.
1820 if not isinstance(request, pubsub.PullRequest):
1821 request = pubsub.PullRequest(request)
1822 # If we have keyword arguments corresponding to fields on the
1823 # request, apply these.
1824 if subscription is not None:
1825 request.subscription = subscription
1826 if return_immediately is not None:
1827 request.return_immediately = return_immediately
1828 if max_messages is not None:
1829 request.max_messages = max_messages
1830
1831 if request.return_immediately:
1832 warnings.warn(
1833 "The return_immediately flag is deprecated and should be set to False.",
1834 category=DeprecationWarning,
1835 )
1836
1837 # Wrap the RPC method; this adds retry and timeout information,
1838 # and friendly error handling.
1839 rpc = self._transport._wrapped_methods[self._transport.pull]
1840
1841 # Certain fields should be provided within the metadata header;
1842 # add these here.
1843 metadata = tuple(metadata) + (
1844 gapic_v1.routing_header.to_grpc_metadata(
1845 (("subscription", request.subscription),)
1846 ),
1847 )
1848
1849 # Validate the universe domain.
1850 self._validate_universe_domain()
1851
1852 # Send the request.
1853 response = rpc(
1854 request,
1855 retry=retry,
1856 timeout=timeout,
1857 metadata=metadata,
1858 )
1859
1860 # Done; return the response.
1861 return response
1862
1863 def streaming_pull(
1864 self,
1865 requests: Optional[Iterator[pubsub.StreamingPullRequest]] = None,
1866 *,
1867 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1868 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1869 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1870 ) -> Iterable[pubsub.StreamingPullResponse]:
1871 r"""Establishes a stream with the server, which sends messages down
1872 to the client. The client streams acknowledgments and ack
1873 deadline modifications back to the server. The server will close
1874 the stream and return the status on any error. The server may
1875 close the stream with status ``UNAVAILABLE`` to reassign
1876 server-side resources, in which case, the client should
1877 re-establish the stream. Flow control can be achieved by
1878 configuring the underlying RPC channel.
1879
1880 .. code-block:: python
1881
1882 # This snippet has been automatically generated and should be regarded as a
1883 # code template only.
1884 # It will require modifications to work:
1885 # - It may require correct/in-range values for request initialization.
1886 # - It may require specifying regional endpoints when creating the service
1887 # client as shown in:
1888 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1889 from google import pubsub_v1
1890
1891 def sample_streaming_pull():
1892 # Create a client
1893 client = pubsub_v1.SubscriberClient()
1894
1895 # Initialize request argument(s)
1896 request = pubsub_v1.StreamingPullRequest(
1897 subscription="subscription_value",
1898 stream_ack_deadline_seconds=2813,
1899 )
1900
1901 # This method expects an iterator which contains
1902 # 'pubsub_v1.StreamingPullRequest' objects
1903 # Here we create a generator that yields a single `request` for
1904 # demonstrative purposes.
1905 requests = [request]
1906
1907 def request_generator():
1908 for request in requests:
1909 yield request
1910
1911 # Make the request
1912 stream = client.streaming_pull(requests=request_generator())
1913
1914 # Handle the response
1915 for response in stream:
1916 print(response)
1917
1918 Args:
1919 requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]):
1920 The request object iterator. Request for the ``StreamingPull`` streaming RPC method.
1921 This request is used to establish the initial stream as
1922 well as to stream acknowledgments and ack deadline
1923 modifications from the client to the server.
1924 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1925 should be retried.
1926 timeout (float): The timeout for this request.
1927 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1928 sent along with the request as metadata. Normally, each value must be of type `str`,
1929 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1930 be of type `bytes`.
1931
1932 Returns:
1933 Iterable[google.pubsub_v1.types.StreamingPullResponse]:
1934 Response for the StreamingPull method. This response is used to stream
1935 messages from the server to the client.
1936
1937 """
1938
1939 # Wrappers in api-core should not automatically pre-fetch the first
1940 # stream result, as this breaks the stream when re-opening it.
1941 # https://github.com/googleapis/python-pubsub/issues/93#issuecomment-630762257
1942 self._transport.streaming_pull._prefetch_first_result_ = False
1943
1944 # Wrap the RPC method; this adds retry and timeout information,
1945 # and friendly error handling.
1946 rpc = self._transport._wrapped_methods[self._transport.streaming_pull]
1947
1948 # Validate the universe domain.
1949 self._validate_universe_domain()
1950
1951 # Send the request.
1952 response = rpc(
1953 requests,
1954 retry=retry,
1955 timeout=timeout,
1956 metadata=metadata,
1957 )
1958
1959 # Done; return the response.
1960 return response
1961
1962 def modify_push_config(
1963 self,
1964 request: Optional[Union[pubsub.ModifyPushConfigRequest, dict]] = None,
1965 *,
1966 subscription: Optional[str] = None,
1967 push_config: Optional[pubsub.PushConfig] = None,
1968 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1969 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1970 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1971 ) -> None:
1972 r"""Modifies the ``PushConfig`` for a specified subscription.
1973
1974 This may be used to change a push subscription to a pull one
1975 (signified by an empty ``PushConfig``) or vice versa, or change
1976 the endpoint URL and other attributes of a push subscription.
1977 Messages will accumulate for delivery continuously through the
1978 call regardless of changes to the ``PushConfig``.
1979
1980 .. code-block:: python
1981
1982 # This snippet has been automatically generated and should be regarded as a
1983 # code template only.
1984 # It will require modifications to work:
1985 # - It may require correct/in-range values for request initialization.
1986 # - It may require specifying regional endpoints when creating the service
1987 # client as shown in:
1988 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1989 from google import pubsub_v1
1990
1991 def sample_modify_push_config():
1992 # Create a client
1993 client = pubsub_v1.SubscriberClient()
1994
1995 # Initialize request argument(s)
1996 request = pubsub_v1.ModifyPushConfigRequest(
1997 subscription="subscription_value",
1998 )
1999
2000 # Make the request
2001 client.modify_push_config(request=request)
2002
2003 Args:
2004 request (Union[google.pubsub_v1.types.ModifyPushConfigRequest, dict]):
2005 The request object. Request for the ModifyPushConfig
2006 method.
2007 subscription (str):
2008 Required. The name of the subscription. Format is
2009 ``projects/{project}/subscriptions/{sub}``.
2010
2011 This corresponds to the ``subscription`` field
2012 on the ``request`` instance; if ``request`` is provided, this
2013 should not be set.
2014 push_config (google.pubsub_v1.types.PushConfig):
2015 Required. The push configuration for future deliveries.
2016
2017 An empty ``pushConfig`` indicates that the Pub/Sub
2018 system should stop pushing messages from the given
2019 subscription and allow messages to be pulled and
2020 acknowledged - effectively pausing the subscription if
2021 ``Pull`` or ``StreamingPull`` is not called.
2022
2023 This corresponds to the ``push_config`` field
2024 on the ``request`` instance; if ``request`` is provided, this
2025 should not be set.
2026 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2027 should be retried.
2028 timeout (float): The timeout for this request.
2029 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2030 sent along with the request as metadata. Normally, each value must be of type `str`,
2031 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2032 be of type `bytes`.
2033 """
2034 # Create or coerce a protobuf request object.
2035 # - Quick check: If we got a request object, we should *not* have
2036 # gotten any keyword arguments that map to the request.
2037 flattened_params = [subscription, push_config]
2038 has_flattened_params = (
2039 len([param for param in flattened_params if param is not None]) > 0
2040 )
2041 if request is not None and has_flattened_params:
2042 raise ValueError(
2043 "If the `request` argument is set, then none of "
2044 "the individual field arguments should be set."
2045 )
2046
2047 # - Use the request object if provided (there's no risk of modifying the input as
2048 # there are no flattened fields), or create one.
2049 if not isinstance(request, pubsub.ModifyPushConfigRequest):
2050 request = pubsub.ModifyPushConfigRequest(request)
2051 # If we have keyword arguments corresponding to fields on the
2052 # request, apply these.
2053 if subscription is not None:
2054 request.subscription = subscription
2055 if push_config is not None:
2056 request.push_config = push_config
2057
2058 # Wrap the RPC method; this adds retry and timeout information,
2059 # and friendly error handling.
2060 rpc = self._transport._wrapped_methods[self._transport.modify_push_config]
2061
2062 # Certain fields should be provided within the metadata header;
2063 # add these here.
2064 metadata = tuple(metadata) + (
2065 gapic_v1.routing_header.to_grpc_metadata(
2066 (("subscription", request.subscription),)
2067 ),
2068 )
2069
2070 # Validate the universe domain.
2071 self._validate_universe_domain()
2072
2073 # Send the request.
2074 rpc(
2075 request,
2076 retry=retry,
2077 timeout=timeout,
2078 metadata=metadata,
2079 )
2080
2081 def get_snapshot(
2082 self,
2083 request: Optional[Union[pubsub.GetSnapshotRequest, dict]] = None,
2084 *,
2085 snapshot: Optional[str] = None,
2086 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2087 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2088 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2089 ) -> pubsub.Snapshot:
2090 r"""Gets the configuration details of a snapshot. Snapshots are used
2091 in
2092 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
2093 operations, which allow you to manage message acknowledgments in
2094 bulk. That is, you can set the acknowledgment state of messages
2095 in an existing subscription to the state captured by a snapshot.
2096
2097 .. code-block:: python
2098
2099 # This snippet has been automatically generated and should be regarded as a
2100 # code template only.
2101 # It will require modifications to work:
2102 # - It may require correct/in-range values for request initialization.
2103 # - It may require specifying regional endpoints when creating the service
2104 # client as shown in:
2105 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2106 from google import pubsub_v1
2107
2108 def sample_get_snapshot():
2109 # Create a client
2110 client = pubsub_v1.SubscriberClient()
2111
2112 # Initialize request argument(s)
2113 request = pubsub_v1.GetSnapshotRequest(
2114 snapshot="snapshot_value",
2115 )
2116
2117 # Make the request
2118 response = client.get_snapshot(request=request)
2119
2120 # Handle the response
2121 print(response)
2122
2123 Args:
2124 request (Union[google.pubsub_v1.types.GetSnapshotRequest, dict]):
2125 The request object. Request for the GetSnapshot method.
2126 snapshot (str):
2127 Required. The name of the snapshot to get. Format is
2128 ``projects/{project}/snapshots/{snap}``.
2129
2130 This corresponds to the ``snapshot`` field
2131 on the ``request`` instance; if ``request`` is provided, this
2132 should not be set.
2133 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2134 should be retried.
2135 timeout (float): The timeout for this request.
2136 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2137 sent along with the request as metadata. Normally, each value must be of type `str`,
2138 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2139 be of type `bytes`.
2140
2141 Returns:
2142 google.pubsub_v1.types.Snapshot:
2143 A snapshot resource. Snapshots are used in
2144 [Seek](https://cloud.google.com/pubsub/docs/replay-overview)
2145 operations, which allow you to manage message
2146 acknowledgments in bulk. That is, you can set the
2147 acknowledgment state of messages in an existing
2148 subscription to the state captured by a snapshot.
2149
2150 """
2151 # Create or coerce a protobuf request object.
2152 # - Quick check: If we got a request object, we should *not* have
2153 # gotten any keyword arguments that map to the request.
2154 flattened_params = [snapshot]
2155 has_flattened_params = (
2156 len([param for param in flattened_params if param is not None]) > 0
2157 )
2158 if request is not None and has_flattened_params:
2159 raise ValueError(
2160 "If the `request` argument is set, then none of "
2161 "the individual field arguments should be set."
2162 )
2163
2164 # - Use the request object if provided (there's no risk of modifying the input as
2165 # there are no flattened fields), or create one.
2166 if not isinstance(request, pubsub.GetSnapshotRequest):
2167 request = pubsub.GetSnapshotRequest(request)
2168 # If we have keyword arguments corresponding to fields on the
2169 # request, apply these.
2170 if snapshot is not None:
2171 request.snapshot = snapshot
2172
2173 # Wrap the RPC method; this adds retry and timeout information,
2174 # and friendly error handling.
2175 rpc = self._transport._wrapped_methods[self._transport.get_snapshot]
2176
2177 # Certain fields should be provided within the metadata header;
2178 # add these here.
2179 metadata = tuple(metadata) + (
2180 gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)),
2181 )
2182
2183 # Validate the universe domain.
2184 self._validate_universe_domain()
2185
2186 # Send the request.
2187 response = rpc(
2188 request,
2189 retry=retry,
2190 timeout=timeout,
2191 metadata=metadata,
2192 )
2193
2194 # Done; return the response.
2195 return response
2196
2197 def list_snapshots(
2198 self,
2199 request: Optional[Union[pubsub.ListSnapshotsRequest, dict]] = None,
2200 *,
2201 project: Optional[str] = None,
2202 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2203 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2204 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2205 ) -> pagers.ListSnapshotsPager:
2206 r"""Lists the existing snapshots. Snapshots are used in
2207 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
2208 operations, which allow you to manage message acknowledgments in
2209 bulk. That is, you can set the acknowledgment state of messages
2210 in an existing subscription to the state captured by a snapshot.
2211
2212 .. code-block:: python
2213
2214 # This snippet has been automatically generated and should be regarded as a
2215 # code template only.
2216 # It will require modifications to work:
2217 # - It may require correct/in-range values for request initialization.
2218 # - It may require specifying regional endpoints when creating the service
2219 # client as shown in:
2220 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2221 from google import pubsub_v1
2222
2223 def sample_list_snapshots():
2224 # Create a client
2225 client = pubsub_v1.SubscriberClient()
2226
2227 # Initialize request argument(s)
2228 request = pubsub_v1.ListSnapshotsRequest(
2229 project="project_value",
2230 )
2231
2232 # Make the request
2233 page_result = client.list_snapshots(request=request)
2234
2235 # Handle the response
2236 for response in page_result:
2237 print(response)
2238
2239 Args:
2240 request (Union[google.pubsub_v1.types.ListSnapshotsRequest, dict]):
2241 The request object. Request for the ``ListSnapshots`` method.
2242 project (str):
2243 Required. The name of the project in which to list
2244 snapshots. Format is ``projects/{project-id}``.
2245
2246 This corresponds to the ``project`` field
2247 on the ``request`` instance; if ``request`` is provided, this
2248 should not be set.
2249 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2250 should be retried.
2251 timeout (float): The timeout for this request.
2252 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2253 sent along with the request as metadata. Normally, each value must be of type `str`,
2254 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2255 be of type `bytes`.
2256
2257 Returns:
2258 google.pubsub_v1.services.subscriber.pagers.ListSnapshotsPager:
2259 Response for the ListSnapshots method.
2260
2261 Iterating over this object will yield results and
2262 resolve additional pages automatically.
2263
2264 """
2265 # Create or coerce a protobuf request object.
2266 # - Quick check: If we got a request object, we should *not* have
2267 # gotten any keyword arguments that map to the request.
2268 flattened_params = [project]
2269 has_flattened_params = (
2270 len([param for param in flattened_params if param is not None]) > 0
2271 )
2272 if request is not None and has_flattened_params:
2273 raise ValueError(
2274 "If the `request` argument is set, then none of "
2275 "the individual field arguments should be set."
2276 )
2277
2278 # - Use the request object if provided (there's no risk of modifying the input as
2279 # there are no flattened fields), or create one.
2280 if not isinstance(request, pubsub.ListSnapshotsRequest):
2281 request = pubsub.ListSnapshotsRequest(request)
2282 # If we have keyword arguments corresponding to fields on the
2283 # request, apply these.
2284 if project is not None:
2285 request.project = project
2286
2287 # Wrap the RPC method; this adds retry and timeout information,
2288 # and friendly error handling.
2289 rpc = self._transport._wrapped_methods[self._transport.list_snapshots]
2290
2291 # Certain fields should be provided within the metadata header;
2292 # add these here.
2293 metadata = tuple(metadata) + (
2294 gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)),
2295 )
2296
2297 # Validate the universe domain.
2298 self._validate_universe_domain()
2299
2300 # Send the request.
2301 response = rpc(
2302 request,
2303 retry=retry,
2304 timeout=timeout,
2305 metadata=metadata,
2306 )
2307
2308 # This method is paged; wrap the response in a pager, which provides
2309 # an `__iter__` convenience method.
2310 response = pagers.ListSnapshotsPager(
2311 method=rpc,
2312 request=request,
2313 response=response,
2314 retry=retry,
2315 timeout=timeout,
2316 metadata=metadata,
2317 )
2318
2319 # Done; return the response.
2320 return response
2321
2322 def create_snapshot(
2323 self,
2324 request: Optional[Union[pubsub.CreateSnapshotRequest, dict]] = None,
2325 *,
2326 name: Optional[str] = None,
2327 subscription: Optional[str] = None,
2328 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2329 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2330 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2331 ) -> pubsub.Snapshot:
2332 r"""Creates a snapshot from the requested subscription. Snapshots
2333 are used in
2334 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
2335 operations, which allow you to manage message acknowledgments in
2336 bulk. That is, you can set the acknowledgment state of messages
2337 in an existing subscription to the state captured by a snapshot.
2338 If the snapshot already exists, returns ``ALREADY_EXISTS``. If
2339 the requested subscription doesn't exist, returns ``NOT_FOUND``.
2340 If the backlog in the subscription is too old -- and the
2341 resulting snapshot would expire in less than 1 hour -- then
2342 ``FAILED_PRECONDITION`` is returned. See also the
2343 ``Snapshot.expire_time`` field. If the name is not provided in
2344 the request, the server will assign a random name for this
2345 snapshot on the same project as the subscription, conforming to
2346 the [resource name format]
2347 (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names).
2348 The generated name is populated in the returned Snapshot object.
2349 Note that for REST API requests, you must specify a name in the
2350 request.
2351
2352 .. code-block:: python
2353
2354 # This snippet has been automatically generated and should be regarded as a
2355 # code template only.
2356 # It will require modifications to work:
2357 # - It may require correct/in-range values for request initialization.
2358 # - It may require specifying regional endpoints when creating the service
2359 # client as shown in:
2360 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2361 from google import pubsub_v1
2362
2363 def sample_create_snapshot():
2364 # Create a client
2365 client = pubsub_v1.SubscriberClient()
2366
2367 # Initialize request argument(s)
2368 request = pubsub_v1.CreateSnapshotRequest(
2369 name="name_value",
2370 subscription="subscription_value",
2371 )
2372
2373 # Make the request
2374 response = client.create_snapshot(request=request)
2375
2376 # Handle the response
2377 print(response)
2378
2379 Args:
2380 request (Union[google.pubsub_v1.types.CreateSnapshotRequest, dict]):
2381 The request object. Request for the ``CreateSnapshot`` method.
2382 name (str):
2383 Required. User-provided name for this snapshot. If the
2384 name is not provided in the request, the server will
2385 assign a random name for this snapshot on the same
2386 project as the subscription. Note that for REST API
2387 requests, you must specify a name. See the `resource
2388 name
2389 rules <https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names>`__.
2390 Format is ``projects/{project}/snapshots/{snap}``.
2391
2392 This corresponds to the ``name`` field
2393 on the ``request`` instance; if ``request`` is provided, this
2394 should not be set.
2395 subscription (str):
2396 Required. The subscription whose backlog the snapshot
2397 retains. Specifically, the created snapshot is
2398 guaranteed to retain: (a) The existing backlog on the
2399 subscription. More precisely, this is defined as the
2400 messages in the subscription's backlog that are
2401 unacknowledged upon the successful completion of the
2402 ``CreateSnapshot`` request; as well as: (b) Any messages
2403 published to the subscription's topic following the
2404 successful completion of the CreateSnapshot request.
2405 Format is ``projects/{project}/subscriptions/{sub}``.
2406
2407 This corresponds to the ``subscription`` field
2408 on the ``request`` instance; if ``request`` is provided, this
2409 should not be set.
2410 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2411 should be retried.
2412 timeout (float): The timeout for this request.
2413 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2414 sent along with the request as metadata. Normally, each value must be of type `str`,
2415 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2416 be of type `bytes`.
2417
2418 Returns:
2419 google.pubsub_v1.types.Snapshot:
2420 A snapshot resource. Snapshots are used in
2421 [Seek](https://cloud.google.com/pubsub/docs/replay-overview)
2422 operations, which allow you to manage message
2423 acknowledgments in bulk. That is, you can set the
2424 acknowledgment state of messages in an existing
2425 subscription to the state captured by a snapshot.
2426
2427 """
2428 # Create or coerce a protobuf request object.
2429 # - Quick check: If we got a request object, we should *not* have
2430 # gotten any keyword arguments that map to the request.
2431 flattened_params = [name, subscription]
2432 has_flattened_params = (
2433 len([param for param in flattened_params if param is not None]) > 0
2434 )
2435 if request is not None and has_flattened_params:
2436 raise ValueError(
2437 "If the `request` argument is set, then none of "
2438 "the individual field arguments should be set."
2439 )
2440
2441 # - Use the request object if provided (there's no risk of modifying the input as
2442 # there are no flattened fields), or create one.
2443 if not isinstance(request, pubsub.CreateSnapshotRequest):
2444 request = pubsub.CreateSnapshotRequest(request)
2445 # If we have keyword arguments corresponding to fields on the
2446 # request, apply these.
2447 if name is not None:
2448 request.name = name
2449 if subscription is not None:
2450 request.subscription = subscription
2451
2452 # Wrap the RPC method; this adds retry and timeout information,
2453 # and friendly error handling.
2454 rpc = self._transport._wrapped_methods[self._transport.create_snapshot]
2455
2456 # Certain fields should be provided within the metadata header;
2457 # add these here.
2458 metadata = tuple(metadata) + (
2459 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
2460 )
2461
2462 # Validate the universe domain.
2463 self._validate_universe_domain()
2464
2465 # Send the request.
2466 response = rpc(
2467 request,
2468 retry=retry,
2469 timeout=timeout,
2470 metadata=metadata,
2471 )
2472
2473 # Done; return the response.
2474 return response
2475
2476 def update_snapshot(
2477 self,
2478 request: Optional[Union[pubsub.UpdateSnapshotRequest, dict]] = None,
2479 *,
2480 snapshot: Optional[pubsub.Snapshot] = None,
2481 update_mask: Optional[field_mask_pb2.FieldMask] = None,
2482 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2483 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2484 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2485 ) -> pubsub.Snapshot:
2486 r"""Updates an existing snapshot by updating the fields specified in
2487 the update mask. Snapshots are used in
2488 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__
2489 operations, which allow you to manage message acknowledgments in
2490 bulk. That is, you can set the acknowledgment state of messages
2491 in an existing subscription to the state captured by a snapshot.
2492
2493 .. code-block:: python
2494
2495 # This snippet has been automatically generated and should be regarded as a
2496 # code template only.
2497 # It will require modifications to work:
2498 # - It may require correct/in-range values for request initialization.
2499 # - It may require specifying regional endpoints when creating the service
2500 # client as shown in:
2501 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2502 from google import pubsub_v1
2503
2504 def sample_update_snapshot():
2505 # Create a client
2506 client = pubsub_v1.SubscriberClient()
2507
2508 # Initialize request argument(s)
2509 request = pubsub_v1.UpdateSnapshotRequest(
2510 )
2511
2512 # Make the request
2513 response = client.update_snapshot(request=request)
2514
2515 # Handle the response
2516 print(response)
2517
2518 Args:
2519 request (Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]):
2520 The request object. Request for the UpdateSnapshot
2521 method.
2522 snapshot (google.pubsub_v1.types.Snapshot):
2523 Required. The updated snapshot
2524 object.
2525
2526 This corresponds to the ``snapshot`` field
2527 on the ``request`` instance; if ``request`` is provided, this
2528 should not be set.
2529 update_mask (google.protobuf.field_mask_pb2.FieldMask):
2530 Required. Indicates which fields in
2531 the provided snapshot to update. Must be
2532 specified and non-empty.
2533
2534 This corresponds to the ``update_mask`` field
2535 on the ``request`` instance; if ``request`` is provided, this
2536 should not be set.
2537 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2538 should be retried.
2539 timeout (float): The timeout for this request.
2540 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2541 sent along with the request as metadata. Normally, each value must be of type `str`,
2542 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2543 be of type `bytes`.
2544
2545 Returns:
2546 google.pubsub_v1.types.Snapshot:
2547 A snapshot resource. Snapshots are used in
2548 [Seek](https://cloud.google.com/pubsub/docs/replay-overview)
2549 operations, which allow you to manage message
2550 acknowledgments in bulk. That is, you can set the
2551 acknowledgment state of messages in an existing
2552 subscription to the state captured by a snapshot.
2553
2554 """
2555 # Create or coerce a protobuf request object.
2556 # - Quick check: If we got a request object, we should *not* have
2557 # gotten any keyword arguments that map to the request.
2558 flattened_params = [snapshot, update_mask]
2559 has_flattened_params = (
2560 len([param for param in flattened_params if param is not None]) > 0
2561 )
2562 if request is not None and has_flattened_params:
2563 raise ValueError(
2564 "If the `request` argument is set, then none of "
2565 "the individual field arguments should be set."
2566 )
2567
2568 # - Use the request object if provided (there's no risk of modifying the input as
2569 # there are no flattened fields), or create one.
2570 if not isinstance(request, pubsub.UpdateSnapshotRequest):
2571 request = pubsub.UpdateSnapshotRequest(request)
2572 # If we have keyword arguments corresponding to fields on the
2573 # request, apply these.
2574 if snapshot is not None:
2575 request.snapshot = snapshot
2576 if update_mask is not None:
2577 request.update_mask = update_mask
2578
2579 # Wrap the RPC method; this adds retry and timeout information,
2580 # and friendly error handling.
2581 rpc = self._transport._wrapped_methods[self._transport.update_snapshot]
2582
2583 # Certain fields should be provided within the metadata header;
2584 # add these here.
2585 metadata = tuple(metadata) + (
2586 gapic_v1.routing_header.to_grpc_metadata(
2587 (("snapshot.name", request.snapshot.name),)
2588 ),
2589 )
2590
2591 # Validate the universe domain.
2592 self._validate_universe_domain()
2593
2594 # Send the request.
2595 response = rpc(
2596 request,
2597 retry=retry,
2598 timeout=timeout,
2599 metadata=metadata,
2600 )
2601
2602 # Done; return the response.
2603 return response
2604
2605 def delete_snapshot(
2606 self,
2607 request: Optional[Union[pubsub.DeleteSnapshotRequest, dict]] = None,
2608 *,
2609 snapshot: Optional[str] = None,
2610 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2611 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2612 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2613 ) -> None:
2614 r"""Removes an existing snapshot. Snapshots are used in [Seek]
2615 (https://cloud.google.com/pubsub/docs/replay-overview)
2616 operations, which allow you to manage message acknowledgments in
2617 bulk. That is, you can set the acknowledgment state of messages
2618 in an existing subscription to the state captured by a snapshot.
2619 When the snapshot is deleted, all messages retained in the
2620 snapshot are immediately dropped. After a snapshot is deleted, a
2621 new one may be created with the same name, but the new one has
2622 no association with the old snapshot or its subscription, unless
2623 the same subscription is specified.
2624
2625 .. code-block:: python
2626
2627 # This snippet has been automatically generated and should be regarded as a
2628 # code template only.
2629 # It will require modifications to work:
2630 # - It may require correct/in-range values for request initialization.
2631 # - It may require specifying regional endpoints when creating the service
2632 # client as shown in:
2633 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2634 from google import pubsub_v1
2635
2636 def sample_delete_snapshot():
2637 # Create a client
2638 client = pubsub_v1.SubscriberClient()
2639
2640 # Initialize request argument(s)
2641 request = pubsub_v1.DeleteSnapshotRequest(
2642 snapshot="snapshot_value",
2643 )
2644
2645 # Make the request
2646 client.delete_snapshot(request=request)
2647
2648 Args:
2649 request (Union[google.pubsub_v1.types.DeleteSnapshotRequest, dict]):
2650 The request object. Request for the ``DeleteSnapshot`` method.
2651 snapshot (str):
2652 Required. The name of the snapshot to delete. Format is
2653 ``projects/{project}/snapshots/{snap}``.
2654
2655 This corresponds to the ``snapshot`` field
2656 on the ``request`` instance; if ``request`` is provided, this
2657 should not be set.
2658 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2659 should be retried.
2660 timeout (float): The timeout for this request.
2661 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2662 sent along with the request as metadata. Normally, each value must be of type `str`,
2663 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2664 be of type `bytes`.
2665 """
2666 # Create or coerce a protobuf request object.
2667 # - Quick check: If we got a request object, we should *not* have
2668 # gotten any keyword arguments that map to the request.
2669 flattened_params = [snapshot]
2670 has_flattened_params = (
2671 len([param for param in flattened_params if param is not None]) > 0
2672 )
2673 if request is not None and has_flattened_params:
2674 raise ValueError(
2675 "If the `request` argument is set, then none of "
2676 "the individual field arguments should be set."
2677 )
2678
2679 # - Use the request object if provided (there's no risk of modifying the input as
2680 # there are no flattened fields), or create one.
2681 if not isinstance(request, pubsub.DeleteSnapshotRequest):
2682 request = pubsub.DeleteSnapshotRequest(request)
2683 # If we have keyword arguments corresponding to fields on the
2684 # request, apply these.
2685 if snapshot is not None:
2686 request.snapshot = snapshot
2687
2688 # Wrap the RPC method; this adds retry and timeout information,
2689 # and friendly error handling.
2690 rpc = self._transport._wrapped_methods[self._transport.delete_snapshot]
2691
2692 # Certain fields should be provided within the metadata header;
2693 # add these here.
2694 metadata = tuple(metadata) + (
2695 gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)),
2696 )
2697
2698 # Validate the universe domain.
2699 self._validate_universe_domain()
2700
2701 # Send the request.
2702 rpc(
2703 request,
2704 retry=retry,
2705 timeout=timeout,
2706 metadata=metadata,
2707 )
2708
2709 def seek(
2710 self,
2711 request: Optional[Union[pubsub.SeekRequest, dict]] = None,
2712 *,
2713 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2714 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2715 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2716 ) -> pubsub.SeekResponse:
2717 r"""Seeks an existing subscription to a point in time or to a given
2718 snapshot, whichever is provided in the request. Snapshots are
2719 used in [Seek]
2720 (https://cloud.google.com/pubsub/docs/replay-overview)
2721 operations, which allow you to manage message acknowledgments in
2722 bulk. That is, you can set the acknowledgment state of messages
2723 in an existing subscription to the state captured by a snapshot.
2724 Note that both the subscription and the snapshot must be on the
2725 same topic.
2726
2727 .. code-block:: python
2728
2729 # This snippet has been automatically generated and should be regarded as a
2730 # code template only.
2731 # It will require modifications to work:
2732 # - It may require correct/in-range values for request initialization.
2733 # - It may require specifying regional endpoints when creating the service
2734 # client as shown in:
2735 # https://googleapis.dev/python/google-api-core/latest/client_options.html
2736 from google import pubsub_v1
2737
2738 def sample_seek():
2739 # Create a client
2740 client = pubsub_v1.SubscriberClient()
2741
2742 # Initialize request argument(s)
2743 request = pubsub_v1.SeekRequest(
2744 subscription="subscription_value",
2745 )
2746
2747 # Make the request
2748 response = client.seek(request=request)
2749
2750 # Handle the response
2751 print(response)
2752
2753 Args:
2754 request (Union[google.pubsub_v1.types.SeekRequest, dict]):
2755 The request object. Request for the ``Seek`` method.
2756 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2757 should be retried.
2758 timeout (float): The timeout for this request.
2759 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2760 sent along with the request as metadata. Normally, each value must be of type `str`,
2761 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2762 be of type `bytes`.
2763
2764 Returns:
2765 google.pubsub_v1.types.SeekResponse:
2766 Response for the Seek method (this response is empty).
2767 """
2768 # Create or coerce a protobuf request object.
2769 # - Use the request object if provided (there's no risk of modifying the input as
2770 # there are no flattened fields), or create one.
2771 if not isinstance(request, pubsub.SeekRequest):
2772 request = pubsub.SeekRequest(request)
2773
2774 # Wrap the RPC method; this adds retry and timeout information,
2775 # and friendly error handling.
2776 rpc = self._transport._wrapped_methods[self._transport.seek]
2777
2778 # Certain fields should be provided within the metadata header;
2779 # add these here.
2780 metadata = tuple(metadata) + (
2781 gapic_v1.routing_header.to_grpc_metadata(
2782 (("subscription", request.subscription),)
2783 ),
2784 )
2785
2786 # Validate the universe domain.
2787 self._validate_universe_domain()
2788
2789 # Send the request.
2790 response = rpc(
2791 request,
2792 retry=retry,
2793 timeout=timeout,
2794 metadata=metadata,
2795 )
2796
2797 # Done; return the response.
2798 return response
2799
2800 def __enter__(self) -> "SubscriberClient":
2801 return self
2802
2803 def __exit__(self, type, value, traceback):
2804 """Releases underlying transport's resources.
2805
2806 .. warning::
2807 ONLY use as a context manager if the transport is NOT shared
2808 with other clients! Exiting the with block will CLOSE the transport
2809 and may cause errors in other clients!
2810 """
2811 self.transport.close()
2812
2813 def set_iam_policy(
2814 self,
2815 request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None,
2816 *,
2817 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2818 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2819 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2820 ) -> policy_pb2.Policy:
2821 r"""Sets the IAM access control policy on the specified function.
2822
2823 Replaces any existing policy.
2824
2825 Args:
2826 request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`):
2827 The request object. Request message for `SetIamPolicy`
2828 method.
2829 retry (google.api_core.retry.Retry): Designation of what errors, if any,
2830 should be retried.
2831 timeout (float): The timeout for this request.
2832 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2833 sent along with the request as metadata. Normally, each value must be of type `str`,
2834 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2835 be of type `bytes`.
2836 Returns:
2837 ~.policy_pb2.Policy:
2838 Defines an Identity and Access Management (IAM) policy.
2839 It is used to specify access control policies for Cloud
2840 Platform resources.
2841 A ``Policy`` is a collection of ``bindings``. A
2842 ``binding`` binds one or more ``members`` to a single
2843 ``role``. Members can be user accounts, service
2844 accounts, Google groups, and domains (such as G Suite).
2845 A ``role`` is a named list of permissions (defined by
2846 IAM or configured by users). A ``binding`` can
2847 optionally specify a ``condition``, which is a logic
2848 expression that further constrains the role binding
2849 based on attributes about the request and/or target
2850 resource.
2851
2852 **JSON Example**
2853
2854 ::
2855
2856 {
2857 "bindings": [
2858 {
2859 "role": "roles/resourcemanager.organizationAdmin",
2860 "members": [
2861 "user:mike@example.com",
2862 "group:admins@example.com",
2863 "domain:google.com",
2864 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
2865 ]
2866 },
2867 {
2868 "role": "roles/resourcemanager.organizationViewer",
2869 "members": ["user:eve@example.com"],
2870 "condition": {
2871 "title": "expirable access",
2872 "description": "Does not grant access after Sep 2020",
2873 "expression": "request.time <
2874 timestamp('2020-10-01T00:00:00.000Z')",
2875 }
2876 }
2877 ]
2878 }
2879
2880 **YAML Example**
2881
2882 ::
2883
2884 bindings:
2885 - members:
2886 - user:mike@example.com
2887 - group:admins@example.com
2888 - domain:google.com
2889 - serviceAccount:my-project-id@appspot.gserviceaccount.com
2890 role: roles/resourcemanager.organizationAdmin
2891 - members:
2892 - user:eve@example.com
2893 role: roles/resourcemanager.organizationViewer
2894 condition:
2895 title: expirable access
2896 description: Does not grant access after Sep 2020
2897 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
2898
2899 For a description of IAM and its features, see the `IAM
2900 developer's
2901 guide <https://cloud.google.com/iam/docs>`__.
2902 """
2903 # Create or coerce a protobuf request object.
2904
2905 # The request isn't a proto-plus wrapped type,
2906 # so it must be constructed via keyword expansion.
2907 if isinstance(request, dict):
2908 request = iam_policy_pb2.SetIamPolicyRequest(**request)
2909
2910 # Wrap the RPC method; this adds retry and timeout information,
2911 # and friendly error handling.
2912 rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]
2913
2914 # Certain fields should be provided within the metadata header;
2915 # add these here.
2916 metadata = tuple(metadata) + (
2917 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2918 )
2919
2920 # Validate the universe domain.
2921 self._validate_universe_domain()
2922
2923 try:
2924 # Send the request.
2925 response = rpc(
2926 request,
2927 retry=retry,
2928 timeout=timeout,
2929 metadata=metadata,
2930 )
2931
2932 # Done; return the response.
2933 return response
2934 except core_exceptions.GoogleAPICallError as e:
2935 self._add_cred_info_for_auth_errors(e)
2936 raise e
2937
2938 def get_iam_policy(
2939 self,
2940 request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None,
2941 *,
2942 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2943 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2944 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2945 ) -> policy_pb2.Policy:
2946 r"""Gets the IAM access control policy for a function.
2947
2948 Returns an empty policy if the function exists and does not have a
2949 policy set.
2950
2951 Args:
2952 request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`):
2953 The request object. Request message for `GetIamPolicy`
2954 method.
2955 retry (google.api_core.retry.Retry): Designation of what errors, if
2956 any, should be retried.
2957 timeout (float): The timeout for this request.
2958 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2959 sent along with the request as metadata. Normally, each value must be of type `str`,
2960 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2961 be of type `bytes`.
2962 Returns:
2963 ~.policy_pb2.Policy:
2964 Defines an Identity and Access Management (IAM) policy.
2965 It is used to specify access control policies for Cloud
2966 Platform resources.
2967 A ``Policy`` is a collection of ``bindings``. A
2968 ``binding`` binds one or more ``members`` to a single
2969 ``role``. Members can be user accounts, service
2970 accounts, Google groups, and domains (such as G Suite).
2971 A ``role`` is a named list of permissions (defined by
2972 IAM or configured by users). A ``binding`` can
2973 optionally specify a ``condition``, which is a logic
2974 expression that further constrains the role binding
2975 based on attributes about the request and/or target
2976 resource.
2977
2978 **JSON Example**
2979
2980 ::
2981
2982 {
2983 "bindings": [
2984 {
2985 "role": "roles/resourcemanager.organizationAdmin",
2986 "members": [
2987 "user:mike@example.com",
2988 "group:admins@example.com",
2989 "domain:google.com",
2990 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
2991 ]
2992 },
2993 {
2994 "role": "roles/resourcemanager.organizationViewer",
2995 "members": ["user:eve@example.com"],
2996 "condition": {
2997 "title": "expirable access",
2998 "description": "Does not grant access after Sep 2020",
2999 "expression": "request.time <
3000 timestamp('2020-10-01T00:00:00.000Z')",
3001 }
3002 }
3003 ]
3004 }
3005
3006 **YAML Example**
3007
3008 ::
3009
3010 bindings:
3011 - members:
3012 - user:mike@example.com
3013 - group:admins@example.com
3014 - domain:google.com
3015 - serviceAccount:my-project-id@appspot.gserviceaccount.com
3016 role: roles/resourcemanager.organizationAdmin
3017 - members:
3018 - user:eve@example.com
3019 role: roles/resourcemanager.organizationViewer
3020 condition:
3021 title: expirable access
3022 description: Does not grant access after Sep 2020
3023 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
3024
3025 For a description of IAM and its features, see the `IAM
3026 developer's
3027 guide <https://cloud.google.com/iam/docs>`__.
3028 """
3029 # Create or coerce a protobuf request object.
3030
3031 # The request isn't a proto-plus wrapped type,
3032 # so it must be constructed via keyword expansion.
3033 if isinstance(request, dict):
3034 request = iam_policy_pb2.GetIamPolicyRequest(**request)
3035
3036 # Wrap the RPC method; this adds retry and timeout information,
3037 # and friendly error handling.
3038 rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]
3039
3040 # Certain fields should be provided within the metadata header;
3041 # add these here.
3042 metadata = tuple(metadata) + (
3043 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
3044 )
3045
3046 # Validate the universe domain.
3047 self._validate_universe_domain()
3048
3049 try:
3050 # Send the request.
3051 response = rpc(
3052 request,
3053 retry=retry,
3054 timeout=timeout,
3055 metadata=metadata,
3056 )
3057
3058 # Done; return the response.
3059 return response
3060 except core_exceptions.GoogleAPICallError as e:
3061 self._add_cred_info_for_auth_errors(e)
3062 raise e
3063
3064 def test_iam_permissions(
3065 self,
3066 request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None,
3067 *,
3068 retry: OptionalRetry = gapic_v1.method.DEFAULT,
3069 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
3070 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
3071 ) -> iam_policy_pb2.TestIamPermissionsResponse:
3072 r"""Tests the specified IAM permissions against the IAM access control
3073 policy for a function.
3074
3075 If the function does not exist, this will return an empty set
3076 of permissions, not a NOT_FOUND error.
3077
3078 Args:
3079 request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`):
3080 The request object. Request message for
3081 `TestIamPermissions` method.
3082 retry (google.api_core.retry.Retry): Designation of what errors,
3083 if any, should be retried.
3084 timeout (float): The timeout for this request.
3085 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
3086 sent along with the request as metadata. Normally, each value must be of type `str`,
3087 but for metadata keys ending with the suffix `-bin`, the corresponding values must
3088 be of type `bytes`.
3089 Returns:
3090 ~.iam_policy_pb2.TestIamPermissionsResponse:
3091 Response message for ``TestIamPermissions`` method.
3092 """
3093 # Create or coerce a protobuf request object.
3094
3095 # The request isn't a proto-plus wrapped type,
3096 # so it must be constructed via keyword expansion.
3097 if isinstance(request, dict):
3098 request = iam_policy_pb2.TestIamPermissionsRequest(**request)
3099
3100 # Wrap the RPC method; this adds retry and timeout information,
3101 # and friendly error handling.
3102 rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions]
3103
3104 # Certain fields should be provided within the metadata header;
3105 # add these here.
3106 metadata = tuple(metadata) + (
3107 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
3108 )
3109
3110 # Validate the universe domain.
3111 self._validate_universe_domain()
3112
3113 try:
3114 # Send the request.
3115 response = rpc(
3116 request,
3117 retry=retry,
3118 timeout=timeout,
3119 metadata=metadata,
3120 )
3121
3122 # Done; return the response.
3123 return response
3124 except core_exceptions.GoogleAPICallError as e:
3125 self._add_cred_info_for_auth_errors(e)
3126 raise e
3127
3128
3129DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
3130 client_library_version=package_version.__version__
3131)
3132
3133if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER
3134 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
3135
3136__all__ = ("SubscriberClient",)