Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.10/site-packages/google/pubsub_v1/services/subscriber/client.py: 26%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

529 statements  

1# -*- coding: utf-8 -*- 

2# Copyright 2024 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 

52 

53try: 

54 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None] 

55except AttributeError: # pragma: NO COVER 

56 OptionalRetry = Union[retries.Retry, object, None] # type: ignore 

57 

58try: 

59 from google.api_core import client_logging # type: ignore 

60 

61 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

62except ImportError: # pragma: NO COVER 

63 CLIENT_LOGGING_SUPPORTED = False 

64 

65_LOGGER = std_logging.getLogger(__name__) 

66 

67from google.iam.v1 import iam_policy_pb2 # type: ignore 

68from google.iam.v1 import policy_pb2 # type: ignore 

69from google.protobuf import duration_pb2 # type: ignore 

70from google.protobuf import field_mask_pb2 # type: ignore 

71from google.protobuf import timestamp_pb2 # type: ignore 

72from google.pubsub_v1.services.subscriber import pagers 

73from google.pubsub_v1.types import pubsub 

74 

75import grpc 

76from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO 

77from .transports.grpc import SubscriberGrpcTransport 

78from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport 

79from .transports.rest import SubscriberRestTransport 

80 

81 

82class SubscriberClientMeta(type): 

83 """Metaclass for the Subscriber client. 

84 

85 This provides class-level methods for building and retrieving 

86 support objects (e.g. transport) without polluting the client instance 

87 objects. 

88 """ 

89 

90 _transport_registry = OrderedDict() # type: Dict[str, Type[SubscriberTransport]] 

91 _transport_registry["grpc"] = SubscriberGrpcTransport 

92 _transport_registry["grpc_asyncio"] = SubscriberGrpcAsyncIOTransport 

93 _transport_registry["rest"] = SubscriberRestTransport 

94 

95 def get_transport_class( 

96 cls, 

97 label: Optional[str] = None, 

98 ) -> Type[SubscriberTransport]: 

99 """Returns an appropriate transport class. 

100 

101 Args: 

102 label: The name of the desired transport. If none is 

103 provided, then the first transport in the registry is used. 

104 

105 Returns: 

106 The transport class to use. 

107 """ 

108 # If a specific transport is requested, return that one. 

109 if label: 

110 return cls._transport_registry[label] 

111 

112 # No transport is requested; return the default (that is, the first one 

113 # in the dictionary). 

114 return next(iter(cls._transport_registry.values())) 

115 

116 

117class SubscriberClient(metaclass=SubscriberClientMeta): 

118 """The service that an application uses to manipulate subscriptions and 

119 to consume messages from a subscription via the ``Pull`` method or 

120 by establishing a bi-directional stream using the ``StreamingPull`` 

121 method. 

122 """ 

123 

124 @staticmethod 

125 def _get_default_mtls_endpoint(api_endpoint): 

126 """Converts api endpoint to mTLS endpoint. 

127 

128 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to 

129 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively. 

130 Args: 

131 api_endpoint (Optional[str]): the api endpoint to convert. 

132 Returns: 

133 str: converted mTLS api endpoint. 

134 """ 

135 if not api_endpoint: 

136 return api_endpoint 

137 

138 mtls_endpoint_re = re.compile( 

139 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?" 

140 ) 

141 

142 m = mtls_endpoint_re.match(api_endpoint) 

143 name, mtls, sandbox, googledomain = m.groups() 

144 if mtls or not googledomain: 

145 return api_endpoint 

146 

147 if sandbox: 

148 return api_endpoint.replace( 

149 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

150 ) 

151 

152 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com") 

153 

154 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead. 

155 

156 # The scopes needed to make gRPC calls to all of the methods defined in 

157 # this service 

158 _DEFAULT_SCOPES = ( 

159 "https://www.googleapis.com/auth/cloud-platform", 

160 "https://www.googleapis.com/auth/pubsub", 

161 ) 

162 

163 SERVICE_ADDRESS = "pubsub.googleapis.com:443" 

164 """The default address of the service.""" 

165 

166 DEFAULT_ENDPOINT = "pubsub.googleapis.com" 

167 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

168 DEFAULT_ENDPOINT 

169 ) 

170 

171 _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}" 

172 _DEFAULT_UNIVERSE = "googleapis.com" 

173 

174 @classmethod 

175 def from_service_account_info(cls, info: dict, *args, **kwargs): 

176 """Creates an instance of this client using the provided credentials 

177 info. 

178 

179 Args: 

180 info (dict): The service account private key info. 

181 args: Additional arguments to pass to the constructor. 

182 kwargs: Additional arguments to pass to the constructor. 

183 

184 Returns: 

185 SubscriberClient: The constructed client. 

186 """ 

187 credentials = service_account.Credentials.from_service_account_info(info) 

188 kwargs["credentials"] = credentials 

189 return cls(*args, **kwargs) 

190 

191 @classmethod 

192 def from_service_account_file(cls, filename: str, *args, **kwargs): 

193 """Creates an instance of this client using the provided credentials 

194 file. 

195 

196 Args: 

197 filename (str): The path to the service account private key json 

198 file. 

199 args: Additional arguments to pass to the constructor. 

200 kwargs: Additional arguments to pass to the constructor. 

201 

202 Returns: 

203 SubscriberClient: The constructed client. 

204 """ 

205 credentials = service_account.Credentials.from_service_account_file(filename) 

206 kwargs["credentials"] = credentials 

207 return cls(*args, **kwargs) 

208 

209 from_service_account_json = from_service_account_file 

210 

211 @property 

212 def transport(self) -> SubscriberTransport: 

213 """Returns the transport used by the client instance. 

214 

215 Returns: 

216 SubscriberTransport: The transport used by the client 

217 instance. 

218 """ 

219 return self._transport 

220 

221 @staticmethod 

222 def snapshot_path( 

223 project: str, 

224 snapshot: str, 

225 ) -> str: 

226 """Returns a fully-qualified snapshot string.""" 

227 return "projects/{project}/snapshots/{snapshot}".format( 

228 project=project, 

229 snapshot=snapshot, 

230 ) 

231 

232 @staticmethod 

233 def parse_snapshot_path(path: str) -> Dict[str, str]: 

234 """Parses a snapshot path into its component segments.""" 

235 m = re.match(r"^projects/(?P<project>.+?)/snapshots/(?P<snapshot>.+?)$", path) 

236 return m.groupdict() if m else {} 

237 

238 @staticmethod 

239 def subscription_path( 

240 project: str, 

241 subscription: str, 

242 ) -> str: 

243 """Returns a fully-qualified subscription string.""" 

244 return "projects/{project}/subscriptions/{subscription}".format( 

245 project=project, 

246 subscription=subscription, 

247 ) 

248 

249 @staticmethod 

250 def parse_subscription_path(path: str) -> Dict[str, str]: 

251 """Parses a subscription path into its component segments.""" 

252 m = re.match( 

253 r"^projects/(?P<project>.+?)/subscriptions/(?P<subscription>.+?)$", path 

254 ) 

255 return m.groupdict() if m else {} 

256 

257 @staticmethod 

258 def topic_path( 

259 project: str, 

260 topic: str, 

261 ) -> str: 

262 """Returns a fully-qualified topic string.""" 

263 return "projects/{project}/topics/{topic}".format( 

264 project=project, 

265 topic=topic, 

266 ) 

267 

268 @staticmethod 

269 def parse_topic_path(path: str) -> Dict[str, str]: 

270 """Parses a topic path into its component segments.""" 

271 m = re.match(r"^projects/(?P<project>.+?)/topics/(?P<topic>.+?)$", path) 

272 return m.groupdict() if m else {} 

273 

274 @staticmethod 

275 def common_billing_account_path( 

276 billing_account: str, 

277 ) -> str: 

278 """Returns a fully-qualified billing_account string.""" 

279 return "billingAccounts/{billing_account}".format( 

280 billing_account=billing_account, 

281 ) 

282 

283 @staticmethod 

284 def parse_common_billing_account_path(path: str) -> Dict[str, str]: 

285 """Parse a billing_account path into its component segments.""" 

286 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path) 

287 return m.groupdict() if m else {} 

288 

289 @staticmethod 

290 def common_folder_path( 

291 folder: str, 

292 ) -> str: 

293 """Returns a fully-qualified folder string.""" 

294 return "folders/{folder}".format( 

295 folder=folder, 

296 ) 

297 

298 @staticmethod 

299 def parse_common_folder_path(path: str) -> Dict[str, str]: 

300 """Parse a folder path into its component segments.""" 

301 m = re.match(r"^folders/(?P<folder>.+?)$", path) 

302 return m.groupdict() if m else {} 

303 

304 @staticmethod 

305 def common_organization_path( 

306 organization: str, 

307 ) -> str: 

308 """Returns a fully-qualified organization string.""" 

309 return "organizations/{organization}".format( 

310 organization=organization, 

311 ) 

312 

313 @staticmethod 

314 def parse_common_organization_path(path: str) -> Dict[str, str]: 

315 """Parse a organization path into its component segments.""" 

316 m = re.match(r"^organizations/(?P<organization>.+?)$", path) 

317 return m.groupdict() if m else {} 

318 

319 @staticmethod 

320 def common_project_path( 

321 project: str, 

322 ) -> str: 

323 """Returns a fully-qualified project string.""" 

324 return "projects/{project}".format( 

325 project=project, 

326 ) 

327 

328 @staticmethod 

329 def parse_common_project_path(path: str) -> Dict[str, str]: 

330 """Parse a project path into its component segments.""" 

331 m = re.match(r"^projects/(?P<project>.+?)$", path) 

332 return m.groupdict() if m else {} 

333 

334 @staticmethod 

335 def common_location_path( 

336 project: str, 

337 location: str, 

338 ) -> str: 

339 """Returns a fully-qualified location string.""" 

340 return "projects/{project}/locations/{location}".format( 

341 project=project, 

342 location=location, 

343 ) 

344 

345 @staticmethod 

346 def parse_common_location_path(path: str) -> Dict[str, str]: 

347 """Parse a location path into its component segments.""" 

348 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path) 

349 return m.groupdict() if m else {} 

350 

351 @classmethod 

352 def get_mtls_endpoint_and_cert_source( 

353 cls, client_options: Optional[client_options_lib.ClientOptions] = None 

354 ): 

355 """Deprecated. Return the API endpoint and client cert source for mutual TLS. 

356 

357 The client cert source is determined in the following order: 

358 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the 

359 client cert source is None. 

360 (2) if `client_options.client_cert_source` is provided, use the provided one; if the 

361 default client cert source exists, use the default one; otherwise the client cert 

362 source is None. 

363 

364 The API endpoint is determined in the following order: 

365 (1) if `client_options.api_endpoint` if provided, use the provided one. 

366 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the 

367 default mTLS endpoint; if the environment variable is "never", use the default API 

368 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise 

369 use the default API endpoint. 

370 

371 More details can be found at https://google.aip.dev/auth/4114. 

372 

373 Args: 

374 client_options (google.api_core.client_options.ClientOptions): Custom options for the 

375 client. Only the `api_endpoint` and `client_cert_source` properties may be used 

376 in this method. 

377 

378 Returns: 

379 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the 

380 client cert source to use. 

381 

382 Raises: 

383 google.auth.exceptions.MutualTLSChannelError: If any errors happen. 

384 """ 

385 

386 warnings.warn( 

387 "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.", 

388 DeprecationWarning, 

389 ) 

390 if client_options is None: 

391 client_options = client_options_lib.ClientOptions() 

392 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false") 

393 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto") 

394 if use_client_cert not in ("true", "false"): 

395 raise ValueError( 

396 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" 

397 ) 

398 if use_mtls_endpoint not in ("auto", "never", "always"): 

399 raise MutualTLSChannelError( 

400 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" 

401 ) 

402 

403 # Figure out the client cert source to use. 

404 client_cert_source = None 

405 if use_client_cert == "true": 

406 if client_options.client_cert_source: 

407 client_cert_source = client_options.client_cert_source 

408 elif mtls.has_default_client_cert_source(): 

409 client_cert_source = mtls.default_client_cert_source() 

410 

411 # Figure out which api endpoint to use. 

412 if client_options.api_endpoint is not None: 

413 api_endpoint = client_options.api_endpoint 

414 elif use_mtls_endpoint == "always" or ( 

415 use_mtls_endpoint == "auto" and client_cert_source 

416 ): 

417 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

418 else: 

419 api_endpoint = cls.DEFAULT_ENDPOINT 

420 

421 return api_endpoint, client_cert_source 

422 

423 @staticmethod 

424 def _read_environment_variables(): 

425 """Returns the environment variables used by the client. 

426 

427 Returns: 

428 Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE, 

429 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. 

430 

431 Raises: 

432 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not 

433 any of ["true", "false"]. 

434 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT 

435 is not any of ["auto", "never", "always"]. 

436 """ 

437 use_client_cert = os.getenv( 

438 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" 

439 ).lower() 

440 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower() 

441 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") 

442 if use_client_cert not in ("true", "false"): 

443 raise ValueError( 

444 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`" 

445 ) 

446 if use_mtls_endpoint not in ("auto", "never", "always"): 

447 raise MutualTLSChannelError( 

448 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`" 

449 ) 

450 return use_client_cert == "true", use_mtls_endpoint, universe_domain_env 

451 

452 @staticmethod 

453 def _get_client_cert_source(provided_cert_source, use_cert_flag): 

454 """Return the client cert source to be used by the client. 

455 

456 Args: 

457 provided_cert_source (bytes): The client certificate source provided. 

458 use_cert_flag (bool): A flag indicating whether to use the client certificate. 

459 

460 Returns: 

461 bytes or None: The client cert source to be used by the client. 

462 """ 

463 client_cert_source = None 

464 if use_cert_flag: 

465 if provided_cert_source: 

466 client_cert_source = provided_cert_source 

467 elif mtls.has_default_client_cert_source(): 

468 client_cert_source = mtls.default_client_cert_source() 

469 return client_cert_source 

470 

471 @staticmethod 

472 def _get_api_endpoint( 

473 api_override, client_cert_source, universe_domain, use_mtls_endpoint 

474 ): 

475 """Return the API endpoint used by the client. 

476 

477 Args: 

478 api_override (str): The API endpoint override. If specified, this is always 

479 the return value of this function and the other arguments are not used. 

480 client_cert_source (bytes): The client certificate source used by the client. 

481 universe_domain (str): The universe domain used by the client. 

482 use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters. 

483 Possible values are "always", "auto", or "never". 

484 

485 Returns: 

486 str: The API endpoint to be used by the client. 

487 """ 

488 if api_override is not None: 

489 api_endpoint = api_override 

490 elif use_mtls_endpoint == "always" or ( 

491 use_mtls_endpoint == "auto" and client_cert_source 

492 ): 

493 _default_universe = SubscriberClient._DEFAULT_UNIVERSE 

494 if universe_domain != _default_universe: 

495 raise MutualTLSChannelError( 

496 f"mTLS is not supported in any universe other than {_default_universe}." 

497 ) 

498 api_endpoint = SubscriberClient.DEFAULT_MTLS_ENDPOINT 

499 else: 

500 api_endpoint = SubscriberClient._DEFAULT_ENDPOINT_TEMPLATE.format( 

501 UNIVERSE_DOMAIN=universe_domain 

502 ) 

503 return api_endpoint 

504 

505 @staticmethod 

506 def _get_universe_domain( 

507 client_universe_domain: Optional[str], universe_domain_env: Optional[str] 

508 ) -> str: 

509 """Return the universe domain used by the client. 

510 

511 Args: 

512 client_universe_domain (Optional[str]): The universe domain configured via the client options. 

513 universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable. 

514 

515 Returns: 

516 str: The universe domain to be used by the client. 

517 

518 Raises: 

519 ValueError: If the universe domain is an empty string. 

520 """ 

521 universe_domain = SubscriberClient._DEFAULT_UNIVERSE 

522 if client_universe_domain is not None: 

523 universe_domain = client_universe_domain 

524 elif universe_domain_env is not None: 

525 universe_domain = universe_domain_env 

526 if len(universe_domain.strip()) == 0: 

527 raise ValueError("Universe Domain cannot be an empty string.") 

528 return universe_domain 

529 

530 def _validate_universe_domain(self): 

531 """Validates client's and credentials' universe domains are consistent. 

532 

533 Returns: 

534 bool: True iff the configured universe domain is valid. 

535 

536 Raises: 

537 ValueError: If the configured universe domain is not valid. 

538 """ 

539 

540 # NOTE (b/349488459): universe validation is disabled until further notice. 

541 return True 

542 

543 def _add_cred_info_for_auth_errors( 

544 self, error: core_exceptions.GoogleAPICallError 

545 ) -> None: 

546 """Adds credential info string to error details for 401/403/404 errors. 

547 

548 Args: 

549 error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info. 

550 """ 

551 if error.code not in [ 

552 HTTPStatus.UNAUTHORIZED, 

553 HTTPStatus.FORBIDDEN, 

554 HTTPStatus.NOT_FOUND, 

555 ]: 

556 return 

557 

558 cred = self._transport._credentials 

559 

560 # get_cred_info is only available in google-auth>=2.35.0 

561 if not hasattr(cred, "get_cred_info"): 

562 return 

563 

564 # ignore the type check since pypy test fails when get_cred_info 

565 # is not available 

566 cred_info = cred.get_cred_info() # type: ignore 

567 if cred_info and hasattr(error._details, "append"): 

568 error._details.append(json.dumps(cred_info)) 

569 

570 @property 

571 def api_endpoint(self): 

572 """Return the API endpoint used by the client instance. 

573 

574 Returns: 

575 str: The API endpoint used by the client instance. 

576 """ 

577 return self._api_endpoint 

578 

579 @property 

580 def universe_domain(self) -> str: 

581 """Return the universe domain used by the client instance. 

582 

583 Returns: 

584 str: The universe domain used by the client instance. 

585 """ 

586 return self._universe_domain 

587 

588 def __init__( 

589 self, 

590 *, 

591 credentials: Optional[ga_credentials.Credentials] = None, 

592 transport: Optional[ 

593 Union[str, SubscriberTransport, Callable[..., SubscriberTransport]] 

594 ] = None, 

595 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None, 

596 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

597 ) -> None: 

598 """Instantiates the subscriber client. 

599 

600 Args: 

601 credentials (Optional[google.auth.credentials.Credentials]): The 

602 authorization credentials to attach to requests. These 

603 credentials identify the application to the service; if none 

604 are specified, the client will attempt to ascertain the 

605 credentials from the environment. 

606 transport (Optional[Union[str,SubscriberTransport,Callable[..., SubscriberTransport]]]): 

607 The transport to use, or a Callable that constructs and returns a new transport. 

608 If a Callable is given, it will be called with the same set of initialization 

609 arguments as used in the SubscriberTransport constructor. 

610 If set to None, a transport is chosen automatically. 

611 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): 

612 Custom options for the client. 

613 

614 1. The ``api_endpoint`` property can be used to override the 

615 default endpoint provided by the client when ``transport`` is 

616 not explicitly provided. Only if this property is not set and 

617 ``transport`` was not explicitly provided, the endpoint is 

618 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

619 variable, which have one of the following values: 

620 "always" (always use the default mTLS endpoint), "never" (always 

621 use the default regular endpoint) and "auto" (auto-switch to the 

622 default mTLS endpoint if client certificate is present; this is 

623 the default value). 

624 

625 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

626 is "true", then the ``client_cert_source`` property can be used 

627 to provide a client certificate for mTLS transport. If 

628 not provided, the default SSL client certificate will be used if 

629 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

630 set, no client certificate will be used. 

631 

632 3. The ``universe_domain`` property can be used to override the 

633 default "googleapis.com" universe. Note that the ``api_endpoint`` 

634 property still takes precedence; and ``universe_domain`` is 

635 currently not supported for mTLS. 

636 

637 client_info (google.api_core.gapic_v1.client_info.ClientInfo): 

638 The client info used to send a user-agent string along with 

639 API requests. If ``None``, then default info will be used. 

640 Generally, you only need to set this if you're developing 

641 your own client library. 

642 

643 Raises: 

644 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport 

645 creation failed for any reason. 

646 """ 

647 self._client_options = client_options 

648 if isinstance(self._client_options, dict): 

649 self._client_options = client_options_lib.from_dict(self._client_options) 

650 if self._client_options is None: 

651 self._client_options = client_options_lib.ClientOptions() 

652 self._client_options = cast( 

653 client_options_lib.ClientOptions, self._client_options 

654 ) 

655 

656 universe_domain_opt = getattr(self._client_options, "universe_domain", None) 

657 

658 ( 

659 self._use_client_cert, 

660 self._use_mtls_endpoint, 

661 self._universe_domain_env, 

662 ) = SubscriberClient._read_environment_variables() 

663 self._client_cert_source = SubscriberClient._get_client_cert_source( 

664 self._client_options.client_cert_source, self._use_client_cert 

665 ) 

666 self._universe_domain = SubscriberClient._get_universe_domain( 

667 universe_domain_opt, self._universe_domain_env 

668 ) 

669 self._api_endpoint = None # updated below, depending on `transport` 

670 

671 # Initialize the universe domain validation. 

672 self._is_universe_domain_valid = False 

673 

674 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER 

675 # Setup logging. 

676 client_logging.initialize_logging() 

677 

678 api_key_value = getattr(self._client_options, "api_key", None) 

679 if api_key_value and credentials: 

680 raise ValueError( 

681 "client_options.api_key and credentials are mutually exclusive" 

682 ) 

683 

684 # Save or instantiate the transport. 

685 # Ordinarily, we provide the transport, but allowing a custom transport 

686 # instance provides an extensibility point for unusual situations. 

687 transport_provided = isinstance(transport, SubscriberTransport) 

688 if transport_provided: 

689 # transport is a SubscriberTransport instance. 

690 if credentials or self._client_options.credentials_file or api_key_value: 

691 raise ValueError( 

692 "When providing a transport instance, " 

693 "provide its credentials directly." 

694 ) 

695 if self._client_options.scopes: 

696 raise ValueError( 

697 "When providing a transport instance, provide its scopes " 

698 "directly." 

699 ) 

700 self._transport = cast(SubscriberTransport, transport) 

701 self._api_endpoint = self._transport.host 

702 

703 self._api_endpoint = self._api_endpoint or SubscriberClient._get_api_endpoint( 

704 self._client_options.api_endpoint, 

705 self._client_cert_source, 

706 self._universe_domain, 

707 self._use_mtls_endpoint, 

708 ) 

709 

710 if not transport_provided: 

711 import google.auth._default # type: ignore 

712 

713 if api_key_value and hasattr( 

714 google.auth._default, "get_api_key_credentials" 

715 ): 

716 credentials = google.auth._default.get_api_key_credentials( 

717 api_key_value 

718 ) 

719 

720 transport_init: Union[ 

721 Type[SubscriberTransport], Callable[..., SubscriberTransport] 

722 ] = ( 

723 SubscriberClient.get_transport_class(transport) 

724 if isinstance(transport, str) or transport is None 

725 else cast(Callable[..., SubscriberTransport], transport) 

726 ) 

727 # initialize with the provided callable or the passed in class 

728 

729 emulator_host = os.environ.get("PUBSUB_EMULATOR_HOST") 

730 if emulator_host: 

731 if issubclass(transport_init, type(self)._transport_registry["grpc"]): 

732 channel = grpc.insecure_channel(target=emulator_host) 

733 else: 

734 channel = grpc.aio.insecure_channel(target=emulator_host) 

735 transport_init = functools.partial(transport_init, channel=channel) 

736 

737 self._transport = transport_init( 

738 credentials=credentials, 

739 credentials_file=self._client_options.credentials_file, 

740 host=self._api_endpoint, 

741 scopes=self._client_options.scopes, 

742 client_cert_source_for_mtls=self._client_cert_source, 

743 quota_project_id=self._client_options.quota_project_id, 

744 client_info=client_info, 

745 always_use_jwt_access=True, 

746 api_audience=self._client_options.api_audience, 

747 ) 

748 

749 if "async" not in str(self._transport): 

750 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

751 std_logging.DEBUG 

752 ): # pragma: NO COVER 

753 _LOGGER.debug( 

754 "Created client `google.pubsub_v1.SubscriberClient`.", 

755 extra={ 

756 "serviceName": "google.pubsub.v1.Subscriber", 

757 "universeDomain": getattr( 

758 self._transport._credentials, "universe_domain", "" 

759 ), 

760 "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}", 

761 "credentialsInfo": getattr( 

762 self.transport._credentials, "get_cred_info", lambda: None 

763 )(), 

764 } 

765 if hasattr(self._transport, "_credentials") 

766 else { 

767 "serviceName": "google.pubsub.v1.Subscriber", 

768 "credentialsType": None, 

769 }, 

770 ) 

771 

772 def create_subscription( 

773 self, 

774 request: Optional[Union[pubsub.Subscription, dict]] = None, 

775 *, 

776 name: Optional[str] = None, 

777 topic: Optional[str] = None, 

778 push_config: Optional[pubsub.PushConfig] = None, 

779 ack_deadline_seconds: Optional[int] = None, 

780 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

781 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

782 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

783 ) -> pubsub.Subscription: 

784 r"""Creates a subscription to a given topic. See the [resource name 

785 rules] 

786 (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). 

787 If the subscription already exists, returns ``ALREADY_EXISTS``. 

788 If the corresponding topic doesn't exist, returns ``NOT_FOUND``. 

789 

790 If the name is not provided in the request, the server will 

791 assign a random name for this subscription on the same project 

792 as the topic, conforming to the [resource name format] 

793 (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). 

794 The generated name is populated in the returned Subscription 

795 object. Note that for REST API requests, you must specify a name 

796 in the request. 

797 

798 .. code-block:: python 

799 

800 # This snippet has been automatically generated and should be regarded as a 

801 # code template only. 

802 # It will require modifications to work: 

803 # - It may require correct/in-range values for request initialization. 

804 # - It may require specifying regional endpoints when creating the service 

805 # client as shown in: 

806 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

807 from google import pubsub_v1 

808 

809 def sample_create_subscription(): 

810 # Create a client 

811 client = pubsub_v1.SubscriberClient() 

812 

813 # Initialize request argument(s) 

814 request = pubsub_v1.Subscription( 

815 name="name_value", 

816 topic="topic_value", 

817 ) 

818 

819 # Make the request 

820 response = client.create_subscription(request=request) 

821 

822 # Handle the response 

823 print(response) 

824 

825 Args: 

826 request (Union[google.pubsub_v1.types.Subscription, dict]): 

827 The request object. A subscription resource. If none of ``push_config``, 

828 ``bigquery_config``, or ``cloud_storage_config`` is set, 

829 then the subscriber will pull and ack messages using API 

830 methods. At most one of these fields may be set. 

831 name (str): 

832 Required. The name of the subscription. It must have the 

833 format 

834 ``"projects/{project}/subscriptions/{subscription}"``. 

835 ``{subscription}`` must start with a letter, and contain 

836 only letters (``[A-Za-z]``), numbers (``[0-9]``), dashes 

837 (``-``), underscores (``_``), periods (``.``), tildes 

838 (``~``), plus (``+``) or percent signs (``%``). It must 

839 be between 3 and 255 characters in length, and it must 

840 not start with ``"goog"``. 

841 

842 This corresponds to the ``name`` field 

843 on the ``request`` instance; if ``request`` is provided, this 

844 should not be set. 

845 topic (str): 

846 Required. The name of the topic from which this 

847 subscription is receiving messages. Format is 

848 ``projects/{project}/topics/{topic}``. The value of this 

849 field will be ``_deleted-topic_`` if the topic has been 

850 deleted. 

851 

852 This corresponds to the ``topic`` field 

853 on the ``request`` instance; if ``request`` is provided, this 

854 should not be set. 

855 push_config (google.pubsub_v1.types.PushConfig): 

856 Optional. If push delivery is used 

857 with this subscription, this field is 

858 used to configure it. 

859 

860 This corresponds to the ``push_config`` field 

861 on the ``request`` instance; if ``request`` is provided, this 

862 should not be set. 

863 ack_deadline_seconds (int): 

864 Optional. The approximate amount of time (on a 

865 best-effort basis) Pub/Sub waits for the subscriber to 

866 acknowledge receipt before resending the message. In the 

867 interval after the message is delivered and before it is 

868 acknowledged, it is considered to be *outstanding*. 

869 During that time period, the message will not be 

870 redelivered (on a best-effort basis). 

871 

872 For pull subscriptions, this value is used as the 

873 initial value for the ack deadline. To override this 

874 value for a given message, call ``ModifyAckDeadline`` 

875 with the corresponding ``ack_id`` if using non-streaming 

876 pull or send the ``ack_id`` in a 

877 ``StreamingModifyAckDeadlineRequest`` if using streaming 

878 pull. The minimum custom deadline you can specify is 10 

879 seconds. The maximum custom deadline you can specify is 

880 600 seconds (10 minutes). If this parameter is 0, a 

881 default value of 10 seconds is used. 

882 

883 For push delivery, this value is also used to set the 

884 request timeout for the call to the push endpoint. 

885 

886 If the subscriber never acknowledges the message, the 

887 Pub/Sub system will eventually redeliver the message. 

888 

889 This corresponds to the ``ack_deadline_seconds`` field 

890 on the ``request`` instance; if ``request`` is provided, this 

891 should not be set. 

892 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

893 should be retried. 

894 timeout (float): The timeout for this request. 

895 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

896 sent along with the request as metadata. Normally, each value must be of type `str`, 

897 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

898 be of type `bytes`. 

899 

900 Returns: 

901 google.pubsub_v1.types.Subscription: 

902 A subscription resource. If none of push_config, bigquery_config, or 

903 cloud_storage_config is set, then the subscriber will 

904 pull and ack messages using API methods. At most one 

905 of these fields may be set. 

906 

907 """ 

908 # Create or coerce a protobuf request object. 

909 # - Quick check: If we got a request object, we should *not* have 

910 # gotten any keyword arguments that map to the request. 

911 flattened_params = [name, topic, push_config, ack_deadline_seconds] 

912 has_flattened_params = ( 

913 len([param for param in flattened_params if param is not None]) > 0 

914 ) 

915 if request is not None and has_flattened_params: 

916 raise ValueError( 

917 "If the `request` argument is set, then none of " 

918 "the individual field arguments should be set." 

919 ) 

920 

921 # - Use the request object if provided (there's no risk of modifying the input as 

922 # there are no flattened fields), or create one. 

923 if not isinstance(request, pubsub.Subscription): 

924 request = pubsub.Subscription(request) 

925 # If we have keyword arguments corresponding to fields on the 

926 # request, apply these. 

927 if name is not None: 

928 request.name = name 

929 if topic is not None: 

930 request.topic = topic 

931 if push_config is not None: 

932 request.push_config = push_config 

933 if ack_deadline_seconds is not None: 

934 request.ack_deadline_seconds = ack_deadline_seconds 

935 

936 # Wrap the RPC method; this adds retry and timeout information, 

937 # and friendly error handling. 

938 rpc = self._transport._wrapped_methods[self._transport.create_subscription] 

939 

940 # Certain fields should be provided within the metadata header; 

941 # add these here. 

942 metadata = tuple(metadata) + ( 

943 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

944 ) 

945 

946 # Validate the universe domain. 

947 self._validate_universe_domain() 

948 

949 # Send the request. 

950 response = rpc( 

951 request, 

952 retry=retry, 

953 timeout=timeout, 

954 metadata=metadata, 

955 ) 

956 

957 # Done; return the response. 

958 return response 

959 

960 def get_subscription( 

961 self, 

962 request: Optional[Union[pubsub.GetSubscriptionRequest, dict]] = None, 

963 *, 

964 subscription: Optional[str] = None, 

965 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

966 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

967 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

968 ) -> pubsub.Subscription: 

969 r"""Gets the configuration details of a subscription. 

970 

971 .. code-block:: python 

972 

973 # This snippet has been automatically generated and should be regarded as a 

974 # code template only. 

975 # It will require modifications to work: 

976 # - It may require correct/in-range values for request initialization. 

977 # - It may require specifying regional endpoints when creating the service 

978 # client as shown in: 

979 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

980 from google import pubsub_v1 

981 

982 def sample_get_subscription(): 

983 # Create a client 

984 client = pubsub_v1.SubscriberClient() 

985 

986 # Initialize request argument(s) 

987 request = pubsub_v1.GetSubscriptionRequest( 

988 subscription="subscription_value", 

989 ) 

990 

991 # Make the request 

992 response = client.get_subscription(request=request) 

993 

994 # Handle the response 

995 print(response) 

996 

997 Args: 

998 request (Union[google.pubsub_v1.types.GetSubscriptionRequest, dict]): 

999 The request object. Request for the GetSubscription 

1000 method. 

1001 subscription (str): 

1002 Required. The name of the subscription to get. Format is 

1003 ``projects/{project}/subscriptions/{sub}``. 

1004 

1005 This corresponds to the ``subscription`` field 

1006 on the ``request`` instance; if ``request`` is provided, this 

1007 should not be set. 

1008 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1009 should be retried. 

1010 timeout (float): The timeout for this request. 

1011 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1012 sent along with the request as metadata. Normally, each value must be of type `str`, 

1013 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1014 be of type `bytes`. 

1015 

1016 Returns: 

1017 google.pubsub_v1.types.Subscription: 

1018 A subscription resource. If none of push_config, bigquery_config, or 

1019 cloud_storage_config is set, then the subscriber will 

1020 pull and ack messages using API methods. At most one 

1021 of these fields may be set. 

1022 

1023 """ 

1024 # Create or coerce a protobuf request object. 

1025 # - Quick check: If we got a request object, we should *not* have 

1026 # gotten any keyword arguments that map to the request. 

1027 flattened_params = [subscription] 

1028 has_flattened_params = ( 

1029 len([param for param in flattened_params if param is not None]) > 0 

1030 ) 

1031 if request is not None and has_flattened_params: 

1032 raise ValueError( 

1033 "If the `request` argument is set, then none of " 

1034 "the individual field arguments should be set." 

1035 ) 

1036 

1037 # - Use the request object if provided (there's no risk of modifying the input as 

1038 # there are no flattened fields), or create one. 

1039 if not isinstance(request, pubsub.GetSubscriptionRequest): 

1040 request = pubsub.GetSubscriptionRequest(request) 

1041 # If we have keyword arguments corresponding to fields on the 

1042 # request, apply these. 

1043 if subscription is not None: 

1044 request.subscription = subscription 

1045 

1046 # Wrap the RPC method; this adds retry and timeout information, 

1047 # and friendly error handling. 

1048 rpc = self._transport._wrapped_methods[self._transport.get_subscription] 

1049 

1050 # Certain fields should be provided within the metadata header; 

1051 # add these here. 

1052 metadata = tuple(metadata) + ( 

1053 gapic_v1.routing_header.to_grpc_metadata( 

1054 (("subscription", request.subscription),) 

1055 ), 

1056 ) 

1057 

1058 # Validate the universe domain. 

1059 self._validate_universe_domain() 

1060 

1061 # Send the request. 

1062 response = rpc( 

1063 request, 

1064 retry=retry, 

1065 timeout=timeout, 

1066 metadata=metadata, 

1067 ) 

1068 

1069 # Done; return the response. 

1070 return response 

1071 

1072 def update_subscription( 

1073 self, 

1074 request: Optional[Union[pubsub.UpdateSubscriptionRequest, dict]] = None, 

1075 *, 

1076 subscription: Optional[pubsub.Subscription] = None, 

1077 update_mask: Optional[field_mask_pb2.FieldMask] = None, 

1078 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1079 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1080 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1081 ) -> pubsub.Subscription: 

1082 r"""Updates an existing subscription by updating the 

1083 fields specified in the update mask. Note that certain 

1084 properties of a subscription, such as its topic, are not 

1085 modifiable. 

1086 

1087 .. code-block:: python 

1088 

1089 # This snippet has been automatically generated and should be regarded as a 

1090 # code template only. 

1091 # It will require modifications to work: 

1092 # - It may require correct/in-range values for request initialization. 

1093 # - It may require specifying regional endpoints when creating the service 

1094 # client as shown in: 

1095 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1096 from google import pubsub_v1 

1097 

1098 def sample_update_subscription(): 

1099 # Create a client 

1100 client = pubsub_v1.SubscriberClient() 

1101 

1102 # Initialize request argument(s) 

1103 subscription = pubsub_v1.Subscription() 

1104 subscription.name = "name_value" 

1105 subscription.topic = "topic_value" 

1106 

1107 request = pubsub_v1.UpdateSubscriptionRequest( 

1108 subscription=subscription, 

1109 ) 

1110 

1111 # Make the request 

1112 response = client.update_subscription(request=request) 

1113 

1114 # Handle the response 

1115 print(response) 

1116 

1117 Args: 

1118 request (Union[google.pubsub_v1.types.UpdateSubscriptionRequest, dict]): 

1119 The request object. Request for the UpdateSubscription 

1120 method. 

1121 subscription (google.pubsub_v1.types.Subscription): 

1122 Required. The updated subscription 

1123 object. 

1124 

1125 This corresponds to the ``subscription`` field 

1126 on the ``request`` instance; if ``request`` is provided, this 

1127 should not be set. 

1128 update_mask (google.protobuf.field_mask_pb2.FieldMask): 

1129 Required. Indicates which fields in 

1130 the provided subscription to update. 

1131 Must be specified and non-empty. 

1132 

1133 This corresponds to the ``update_mask`` field 

1134 on the ``request`` instance; if ``request`` is provided, this 

1135 should not be set. 

1136 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1137 should be retried. 

1138 timeout (float): The timeout for this request. 

1139 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1140 sent along with the request as metadata. Normally, each value must be of type `str`, 

1141 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1142 be of type `bytes`. 

1143 

1144 Returns: 

1145 google.pubsub_v1.types.Subscription: 

1146 A subscription resource. If none of push_config, bigquery_config, or 

1147 cloud_storage_config is set, then the subscriber will 

1148 pull and ack messages using API methods. At most one 

1149 of these fields may be set. 

1150 

1151 """ 

1152 # Create or coerce a protobuf request object. 

1153 # - Quick check: If we got a request object, we should *not* have 

1154 # gotten any keyword arguments that map to the request. 

1155 flattened_params = [subscription, update_mask] 

1156 has_flattened_params = ( 

1157 len([param for param in flattened_params if param is not None]) > 0 

1158 ) 

1159 if request is not None and has_flattened_params: 

1160 raise ValueError( 

1161 "If the `request` argument is set, then none of " 

1162 "the individual field arguments should be set." 

1163 ) 

1164 

1165 # - Use the request object if provided (there's no risk of modifying the input as 

1166 # there are no flattened fields), or create one. 

1167 if not isinstance(request, pubsub.UpdateSubscriptionRequest): 

1168 request = pubsub.UpdateSubscriptionRequest(request) 

1169 # If we have keyword arguments corresponding to fields on the 

1170 # request, apply these. 

1171 if subscription is not None: 

1172 request.subscription = subscription 

1173 if update_mask is not None: 

1174 request.update_mask = update_mask 

1175 

1176 # Wrap the RPC method; this adds retry and timeout information, 

1177 # and friendly error handling. 

1178 rpc = self._transport._wrapped_methods[self._transport.update_subscription] 

1179 

1180 # Certain fields should be provided within the metadata header; 

1181 # add these here. 

1182 metadata = tuple(metadata) + ( 

1183 gapic_v1.routing_header.to_grpc_metadata( 

1184 (("subscription.name", request.subscription.name),) 

1185 ), 

1186 ) 

1187 

1188 # Validate the universe domain. 

1189 self._validate_universe_domain() 

1190 

1191 # Send the request. 

1192 response = rpc( 

1193 request, 

1194 retry=retry, 

1195 timeout=timeout, 

1196 metadata=metadata, 

1197 ) 

1198 

1199 # Done; return the response. 

1200 return response 

1201 

1202 def list_subscriptions( 

1203 self, 

1204 request: Optional[Union[pubsub.ListSubscriptionsRequest, dict]] = None, 

1205 *, 

1206 project: Optional[str] = None, 

1207 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1208 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1209 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1210 ) -> pagers.ListSubscriptionsPager: 

1211 r"""Lists matching subscriptions. 

1212 

1213 .. code-block:: python 

1214 

1215 # This snippet has been automatically generated and should be regarded as a 

1216 # code template only. 

1217 # It will require modifications to work: 

1218 # - It may require correct/in-range values for request initialization. 

1219 # - It may require specifying regional endpoints when creating the service 

1220 # client as shown in: 

1221 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1222 from google import pubsub_v1 

1223 

1224 def sample_list_subscriptions(): 

1225 # Create a client 

1226 client = pubsub_v1.SubscriberClient() 

1227 

1228 # Initialize request argument(s) 

1229 request = pubsub_v1.ListSubscriptionsRequest( 

1230 project="project_value", 

1231 ) 

1232 

1233 # Make the request 

1234 page_result = client.list_subscriptions(request=request) 

1235 

1236 # Handle the response 

1237 for response in page_result: 

1238 print(response) 

1239 

1240 Args: 

1241 request (Union[google.pubsub_v1.types.ListSubscriptionsRequest, dict]): 

1242 The request object. Request for the ``ListSubscriptions`` method. 

1243 project (str): 

1244 Required. The name of the project in which to list 

1245 subscriptions. Format is ``projects/{project-id}``. 

1246 

1247 This corresponds to the ``project`` field 

1248 on the ``request`` instance; if ``request`` is provided, this 

1249 should not be set. 

1250 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1251 should be retried. 

1252 timeout (float): The timeout for this request. 

1253 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1254 sent along with the request as metadata. Normally, each value must be of type `str`, 

1255 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1256 be of type `bytes`. 

1257 

1258 Returns: 

1259 google.pubsub_v1.services.subscriber.pagers.ListSubscriptionsPager: 

1260 Response for the ListSubscriptions method. 

1261 

1262 Iterating over this object will yield results and 

1263 resolve additional pages automatically. 

1264 

1265 """ 

1266 # Create or coerce a protobuf request object. 

1267 # - Quick check: If we got a request object, we should *not* have 

1268 # gotten any keyword arguments that map to the request. 

1269 flattened_params = [project] 

1270 has_flattened_params = ( 

1271 len([param for param in flattened_params if param is not None]) > 0 

1272 ) 

1273 if request is not None and has_flattened_params: 

1274 raise ValueError( 

1275 "If the `request` argument is set, then none of " 

1276 "the individual field arguments should be set." 

1277 ) 

1278 

1279 # - Use the request object if provided (there's no risk of modifying the input as 

1280 # there are no flattened fields), or create one. 

1281 if not isinstance(request, pubsub.ListSubscriptionsRequest): 

1282 request = pubsub.ListSubscriptionsRequest(request) 

1283 # If we have keyword arguments corresponding to fields on the 

1284 # request, apply these. 

1285 if project is not None: 

1286 request.project = project 

1287 

1288 # Wrap the RPC method; this adds retry and timeout information, 

1289 # and friendly error handling. 

1290 rpc = self._transport._wrapped_methods[self._transport.list_subscriptions] 

1291 

1292 # Certain fields should be provided within the metadata header; 

1293 # add these here. 

1294 metadata = tuple(metadata) + ( 

1295 gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), 

1296 ) 

1297 

1298 # Validate the universe domain. 

1299 self._validate_universe_domain() 

1300 

1301 # Send the request. 

1302 response = rpc( 

1303 request, 

1304 retry=retry, 

1305 timeout=timeout, 

1306 metadata=metadata, 

1307 ) 

1308 

1309 # This method is paged; wrap the response in a pager, which provides 

1310 # an `__iter__` convenience method. 

1311 response = pagers.ListSubscriptionsPager( 

1312 method=rpc, 

1313 request=request, 

1314 response=response, 

1315 retry=retry, 

1316 timeout=timeout, 

1317 metadata=metadata, 

1318 ) 

1319 

1320 # Done; return the response. 

1321 return response 

1322 

1323 def delete_subscription( 

1324 self, 

1325 request: Optional[Union[pubsub.DeleteSubscriptionRequest, dict]] = None, 

1326 *, 

1327 subscription: Optional[str] = None, 

1328 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1329 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1330 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1331 ) -> None: 

1332 r"""Deletes an existing subscription. All messages retained in the 

1333 subscription are immediately dropped. Calls to ``Pull`` after 

1334 deletion will return ``NOT_FOUND``. After a subscription is 

1335 deleted, a new one may be created with the same name, but the 

1336 new one has no association with the old subscription or its 

1337 topic unless the same topic is specified. 

1338 

1339 .. code-block:: python 

1340 

1341 # This snippet has been automatically generated and should be regarded as a 

1342 # code template only. 

1343 # It will require modifications to work: 

1344 # - It may require correct/in-range values for request initialization. 

1345 # - It may require specifying regional endpoints when creating the service 

1346 # client as shown in: 

1347 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1348 from google import pubsub_v1 

1349 

1350 def sample_delete_subscription(): 

1351 # Create a client 

1352 client = pubsub_v1.SubscriberClient() 

1353 

1354 # Initialize request argument(s) 

1355 request = pubsub_v1.DeleteSubscriptionRequest( 

1356 subscription="subscription_value", 

1357 ) 

1358 

1359 # Make the request 

1360 client.delete_subscription(request=request) 

1361 

1362 Args: 

1363 request (Union[google.pubsub_v1.types.DeleteSubscriptionRequest, dict]): 

1364 The request object. Request for the DeleteSubscription 

1365 method. 

1366 subscription (str): 

1367 Required. The subscription to delete. Format is 

1368 ``projects/{project}/subscriptions/{sub}``. 

1369 

1370 This corresponds to the ``subscription`` field 

1371 on the ``request`` instance; if ``request`` is provided, this 

1372 should not be set. 

1373 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1374 should be retried. 

1375 timeout (float): The timeout for this request. 

1376 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1377 sent along with the request as metadata. Normally, each value must be of type `str`, 

1378 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1379 be of type `bytes`. 

1380 """ 

1381 # Create or coerce a protobuf request object. 

1382 # - Quick check: If we got a request object, we should *not* have 

1383 # gotten any keyword arguments that map to the request. 

1384 flattened_params = [subscription] 

1385 has_flattened_params = ( 

1386 len([param for param in flattened_params if param is not None]) > 0 

1387 ) 

1388 if request is not None and has_flattened_params: 

1389 raise ValueError( 

1390 "If the `request` argument is set, then none of " 

1391 "the individual field arguments should be set." 

1392 ) 

1393 

1394 # - Use the request object if provided (there's no risk of modifying the input as 

1395 # there are no flattened fields), or create one. 

1396 if not isinstance(request, pubsub.DeleteSubscriptionRequest): 

1397 request = pubsub.DeleteSubscriptionRequest(request) 

1398 # If we have keyword arguments corresponding to fields on the 

1399 # request, apply these. 

1400 if subscription is not None: 

1401 request.subscription = subscription 

1402 

1403 # Wrap the RPC method; this adds retry and timeout information, 

1404 # and friendly error handling. 

1405 rpc = self._transport._wrapped_methods[self._transport.delete_subscription] 

1406 

1407 # Certain fields should be provided within the metadata header; 

1408 # add these here. 

1409 metadata = tuple(metadata) + ( 

1410 gapic_v1.routing_header.to_grpc_metadata( 

1411 (("subscription", request.subscription),) 

1412 ), 

1413 ) 

1414 

1415 # Validate the universe domain. 

1416 self._validate_universe_domain() 

1417 

1418 # Send the request. 

1419 rpc( 

1420 request, 

1421 retry=retry, 

1422 timeout=timeout, 

1423 metadata=metadata, 

1424 ) 

1425 

1426 def modify_ack_deadline( 

1427 self, 

1428 request: Optional[Union[pubsub.ModifyAckDeadlineRequest, dict]] = None, 

1429 *, 

1430 subscription: Optional[str] = None, 

1431 ack_ids: Optional[MutableSequence[str]] = None, 

1432 ack_deadline_seconds: Optional[int] = None, 

1433 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1434 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1435 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1436 ) -> None: 

1437 r"""Modifies the ack deadline for a specific message. This method is 

1438 useful to indicate that more time is needed to process a message 

1439 by the subscriber, or to make the message available for 

1440 redelivery if the processing was interrupted. Note that this 

1441 does not modify the subscription-level ``ackDeadlineSeconds`` 

1442 used for subsequent messages. 

1443 

1444 .. code-block:: python 

1445 

1446 # This snippet has been automatically generated and should be regarded as a 

1447 # code template only. 

1448 # It will require modifications to work: 

1449 # - It may require correct/in-range values for request initialization. 

1450 # - It may require specifying regional endpoints when creating the service 

1451 # client as shown in: 

1452 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1453 from google import pubsub_v1 

1454 

1455 def sample_modify_ack_deadline(): 

1456 # Create a client 

1457 client = pubsub_v1.SubscriberClient() 

1458 

1459 # Initialize request argument(s) 

1460 request = pubsub_v1.ModifyAckDeadlineRequest( 

1461 subscription="subscription_value", 

1462 ack_ids=['ack_ids_value1', 'ack_ids_value2'], 

1463 ack_deadline_seconds=2066, 

1464 ) 

1465 

1466 # Make the request 

1467 client.modify_ack_deadline(request=request) 

1468 

1469 Args: 

1470 request (Union[google.pubsub_v1.types.ModifyAckDeadlineRequest, dict]): 

1471 The request object. Request for the ModifyAckDeadline 

1472 method. 

1473 subscription (str): 

1474 Required. The name of the subscription. Format is 

1475 ``projects/{project}/subscriptions/{sub}``. 

1476 

1477 This corresponds to the ``subscription`` field 

1478 on the ``request`` instance; if ``request`` is provided, this 

1479 should not be set. 

1480 ack_ids (MutableSequence[str]): 

1481 Required. List of acknowledgment IDs. 

1482 This corresponds to the ``ack_ids`` field 

1483 on the ``request`` instance; if ``request`` is provided, this 

1484 should not be set. 

1485 ack_deadline_seconds (int): 

1486 Required. The new ack deadline with respect to the time 

1487 this request was sent to the Pub/Sub system. For 

1488 example, if the value is 10, the new ack deadline will 

1489 expire 10 seconds after the ``ModifyAckDeadline`` call 

1490 was made. Specifying zero might immediately make the 

1491 message available for delivery to another subscriber 

1492 client. This typically results in an increase in the 

1493 rate of message redeliveries (that is, duplicates). The 

1494 minimum deadline you can specify is 0 seconds. The 

1495 maximum deadline you can specify in a single request is 

1496 600 seconds (10 minutes). 

1497 

1498 This corresponds to the ``ack_deadline_seconds`` field 

1499 on the ``request`` instance; if ``request`` is provided, this 

1500 should not be set. 

1501 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1502 should be retried. 

1503 timeout (float): The timeout for this request. 

1504 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1505 sent along with the request as metadata. Normally, each value must be of type `str`, 

1506 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1507 be of type `bytes`. 

1508 """ 

1509 # Create or coerce a protobuf request object. 

1510 # - Quick check: If we got a request object, we should *not* have 

1511 # gotten any keyword arguments that map to the request. 

1512 flattened_params = [subscription, ack_ids, ack_deadline_seconds] 

1513 has_flattened_params = ( 

1514 len([param for param in flattened_params if param is not None]) > 0 

1515 ) 

1516 if request is not None and has_flattened_params: 

1517 raise ValueError( 

1518 "If the `request` argument is set, then none of " 

1519 "the individual field arguments should be set." 

1520 ) 

1521 

1522 # - Use the request object if provided (there's no risk of modifying the input as 

1523 # there are no flattened fields), or create one. 

1524 if not isinstance(request, pubsub.ModifyAckDeadlineRequest): 

1525 request = pubsub.ModifyAckDeadlineRequest(request) 

1526 # If we have keyword arguments corresponding to fields on the 

1527 # request, apply these. 

1528 if subscription is not None: 

1529 request.subscription = subscription 

1530 if ack_ids is not None: 

1531 request.ack_ids = ack_ids 

1532 if ack_deadline_seconds is not None: 

1533 request.ack_deadline_seconds = ack_deadline_seconds 

1534 

1535 # Wrap the RPC method; this adds retry and timeout information, 

1536 # and friendly error handling. 

1537 rpc = self._transport._wrapped_methods[self._transport.modify_ack_deadline] 

1538 

1539 # Certain fields should be provided within the metadata header; 

1540 # add these here. 

1541 metadata = tuple(metadata) + ( 

1542 gapic_v1.routing_header.to_grpc_metadata( 

1543 (("subscription", request.subscription),) 

1544 ), 

1545 ) 

1546 

1547 # Validate the universe domain. 

1548 self._validate_universe_domain() 

1549 

1550 # Send the request. 

1551 rpc( 

1552 request, 

1553 retry=retry, 

1554 timeout=timeout, 

1555 metadata=metadata, 

1556 ) 

1557 

1558 def acknowledge( 

1559 self, 

1560 request: Optional[Union[pubsub.AcknowledgeRequest, dict]] = None, 

1561 *, 

1562 subscription: Optional[str] = None, 

1563 ack_ids: Optional[MutableSequence[str]] = None, 

1564 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1565 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1566 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1567 ) -> None: 

1568 r"""Acknowledges the messages associated with the ``ack_ids`` in the 

1569 ``AcknowledgeRequest``. The Pub/Sub system can remove the 

1570 relevant messages from the subscription. 

1571 

1572 Acknowledging a message whose ack deadline has expired may 

1573 succeed, but such a message may be redelivered later. 

1574 Acknowledging a message more than once will not result in an 

1575 error. 

1576 

1577 .. code-block:: python 

1578 

1579 # This snippet has been automatically generated and should be regarded as a 

1580 # code template only. 

1581 # It will require modifications to work: 

1582 # - It may require correct/in-range values for request initialization. 

1583 # - It may require specifying regional endpoints when creating the service 

1584 # client as shown in: 

1585 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1586 from google import pubsub_v1 

1587 

1588 def sample_acknowledge(): 

1589 # Create a client 

1590 client = pubsub_v1.SubscriberClient() 

1591 

1592 # Initialize request argument(s) 

1593 request = pubsub_v1.AcknowledgeRequest( 

1594 subscription="subscription_value", 

1595 ack_ids=['ack_ids_value1', 'ack_ids_value2'], 

1596 ) 

1597 

1598 # Make the request 

1599 client.acknowledge(request=request) 

1600 

1601 Args: 

1602 request (Union[google.pubsub_v1.types.AcknowledgeRequest, dict]): 

1603 The request object. Request for the Acknowledge method. 

1604 subscription (str): 

1605 Required. The subscription whose message is being 

1606 acknowledged. Format is 

1607 ``projects/{project}/subscriptions/{sub}``. 

1608 

1609 This corresponds to the ``subscription`` field 

1610 on the ``request`` instance; if ``request`` is provided, this 

1611 should not be set. 

1612 ack_ids (MutableSequence[str]): 

1613 Required. The acknowledgment ID for the messages being 

1614 acknowledged that was returned by the Pub/Sub system in 

1615 the ``Pull`` response. Must not be empty. 

1616 

1617 This corresponds to the ``ack_ids`` field 

1618 on the ``request`` instance; if ``request`` is provided, this 

1619 should not be set. 

1620 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1621 should be retried. 

1622 timeout (float): The timeout for this request. 

1623 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1624 sent along with the request as metadata. Normally, each value must be of type `str`, 

1625 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1626 be of type `bytes`. 

1627 """ 

1628 # Create or coerce a protobuf request object. 

1629 # - Quick check: If we got a request object, we should *not* have 

1630 # gotten any keyword arguments that map to the request. 

1631 flattened_params = [subscription, ack_ids] 

1632 has_flattened_params = ( 

1633 len([param for param in flattened_params if param is not None]) > 0 

1634 ) 

1635 if request is not None and has_flattened_params: 

1636 raise ValueError( 

1637 "If the `request` argument is set, then none of " 

1638 "the individual field arguments should be set." 

1639 ) 

1640 

1641 # - Use the request object if provided (there's no risk of modifying the input as 

1642 # there are no flattened fields), or create one. 

1643 if not isinstance(request, pubsub.AcknowledgeRequest): 

1644 request = pubsub.AcknowledgeRequest(request) 

1645 # If we have keyword arguments corresponding to fields on the 

1646 # request, apply these. 

1647 if subscription is not None: 

1648 request.subscription = subscription 

1649 if ack_ids is not None: 

1650 request.ack_ids = ack_ids 

1651 

1652 # Wrap the RPC method; this adds retry and timeout information, 

1653 # and friendly error handling. 

1654 rpc = self._transport._wrapped_methods[self._transport.acknowledge] 

1655 

1656 # Certain fields should be provided within the metadata header; 

1657 # add these here. 

1658 metadata = tuple(metadata) + ( 

1659 gapic_v1.routing_header.to_grpc_metadata( 

1660 (("subscription", request.subscription),) 

1661 ), 

1662 ) 

1663 

1664 # Validate the universe domain. 

1665 self._validate_universe_domain() 

1666 

1667 # Send the request. 

1668 rpc( 

1669 request, 

1670 retry=retry, 

1671 timeout=timeout, 

1672 metadata=metadata, 

1673 ) 

1674 

1675 def pull( 

1676 self, 

1677 request: Optional[Union[pubsub.PullRequest, dict]] = None, 

1678 *, 

1679 subscription: Optional[str] = None, 

1680 return_immediately: Optional[bool] = None, 

1681 max_messages: Optional[int] = None, 

1682 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1683 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1684 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1685 ) -> pubsub.PullResponse: 

1686 r"""Pulls messages from the server. 

1687 

1688 .. code-block:: python 

1689 

1690 # This snippet has been automatically generated and should be regarded as a 

1691 # code template only. 

1692 # It will require modifications to work: 

1693 # - It may require correct/in-range values for request initialization. 

1694 # - It may require specifying regional endpoints when creating the service 

1695 # client as shown in: 

1696 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1697 from google import pubsub_v1 

1698 

1699 def sample_pull(): 

1700 # Create a client 

1701 client = pubsub_v1.SubscriberClient() 

1702 

1703 # Initialize request argument(s) 

1704 request = pubsub_v1.PullRequest( 

1705 subscription="subscription_value", 

1706 max_messages=1277, 

1707 ) 

1708 

1709 # Make the request 

1710 response = client.pull(request=request) 

1711 

1712 # Handle the response 

1713 print(response) 

1714 

1715 Args: 

1716 request (Union[google.pubsub_v1.types.PullRequest, dict]): 

1717 The request object. Request for the ``Pull`` method. 

1718 subscription (str): 

1719 Required. The subscription from which messages should be 

1720 pulled. Format is 

1721 ``projects/{project}/subscriptions/{sub}``. 

1722 

1723 This corresponds to the ``subscription`` field 

1724 on the ``request`` instance; if ``request`` is provided, this 

1725 should not be set. 

1726 return_immediately (bool): 

1727 Optional. If this field set to true, the system will 

1728 respond immediately even if it there are no messages 

1729 available to return in the ``Pull`` response. Otherwise, 

1730 the system may wait (for a bounded amount of time) until 

1731 at least one message is available, rather than returning 

1732 no messages. Warning: setting this field to ``true`` is 

1733 discouraged because it adversely impacts the performance 

1734 of ``Pull`` operations. We recommend that users do not 

1735 set this field. 

1736 

1737 This corresponds to the ``return_immediately`` field 

1738 on the ``request`` instance; if ``request`` is provided, this 

1739 should not be set. 

1740 max_messages (int): 

1741 Required. The maximum number of 

1742 messages to return for this request. 

1743 Must be a positive integer. The Pub/Sub 

1744 system may return fewer than the number 

1745 specified. 

1746 

1747 This corresponds to the ``max_messages`` field 

1748 on the ``request`` instance; if ``request`` is provided, this 

1749 should not be set. 

1750 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1751 should be retried. 

1752 timeout (float): The timeout for this request. 

1753 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1754 sent along with the request as metadata. Normally, each value must be of type `str`, 

1755 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1756 be of type `bytes`. 

1757 

1758 Returns: 

1759 google.pubsub_v1.types.PullResponse: 

1760 Response for the Pull method. 

1761 """ 

1762 # Create or coerce a protobuf request object. 

1763 # - Quick check: If we got a request object, we should *not* have 

1764 # gotten any keyword arguments that map to the request. 

1765 flattened_params = [subscription, return_immediately, max_messages] 

1766 has_flattened_params = ( 

1767 len([param for param in flattened_params if param is not None]) > 0 

1768 ) 

1769 if request is not None and has_flattened_params: 

1770 raise ValueError( 

1771 "If the `request` argument is set, then none of " 

1772 "the individual field arguments should be set." 

1773 ) 

1774 

1775 # - Use the request object if provided (there's no risk of modifying the input as 

1776 # there are no flattened fields), or create one. 

1777 if not isinstance(request, pubsub.PullRequest): 

1778 request = pubsub.PullRequest(request) 

1779 # If we have keyword arguments corresponding to fields on the 

1780 # request, apply these. 

1781 if subscription is not None: 

1782 request.subscription = subscription 

1783 if return_immediately is not None: 

1784 request.return_immediately = return_immediately 

1785 if max_messages is not None: 

1786 request.max_messages = max_messages 

1787 

1788 if request.return_immediately: 

1789 warnings.warn( 

1790 "The return_immediately flag is deprecated and should be set to False.", 

1791 category=DeprecationWarning, 

1792 ) 

1793 

1794 # Wrap the RPC method; this adds retry and timeout information, 

1795 # and friendly error handling. 

1796 rpc = self._transport._wrapped_methods[self._transport.pull] 

1797 

1798 # Certain fields should be provided within the metadata header; 

1799 # add these here. 

1800 metadata = tuple(metadata) + ( 

1801 gapic_v1.routing_header.to_grpc_metadata( 

1802 (("subscription", request.subscription),) 

1803 ), 

1804 ) 

1805 

1806 # Validate the universe domain. 

1807 self._validate_universe_domain() 

1808 

1809 # Send the request. 

1810 response = rpc( 

1811 request, 

1812 retry=retry, 

1813 timeout=timeout, 

1814 metadata=metadata, 

1815 ) 

1816 

1817 # Done; return the response. 

1818 return response 

1819 

1820 def streaming_pull( 

1821 self, 

1822 requests: Optional[Iterator[pubsub.StreamingPullRequest]] = None, 

1823 *, 

1824 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1825 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1826 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1827 ) -> Iterable[pubsub.StreamingPullResponse]: 

1828 r"""Establishes a stream with the server, which sends messages down 

1829 to the client. The client streams acknowledgements and ack 

1830 deadline modifications back to the server. The server will close 

1831 the stream and return the status on any error. The server may 

1832 close the stream with status ``UNAVAILABLE`` to reassign 

1833 server-side resources, in which case, the client should 

1834 re-establish the stream. Flow control can be achieved by 

1835 configuring the underlying RPC channel. 

1836 

1837 .. code-block:: python 

1838 

1839 # This snippet has been automatically generated and should be regarded as a 

1840 # code template only. 

1841 # It will require modifications to work: 

1842 # - It may require correct/in-range values for request initialization. 

1843 # - It may require specifying regional endpoints when creating the service 

1844 # client as shown in: 

1845 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1846 from google import pubsub_v1 

1847 

1848 def sample_streaming_pull(): 

1849 # Create a client 

1850 client = pubsub_v1.SubscriberClient() 

1851 

1852 # Initialize request argument(s) 

1853 request = pubsub_v1.StreamingPullRequest( 

1854 subscription="subscription_value", 

1855 stream_ack_deadline_seconds=2813, 

1856 ) 

1857 

1858 # This method expects an iterator which contains 

1859 # 'pubsub_v1.StreamingPullRequest' objects 

1860 # Here we create a generator that yields a single `request` for 

1861 # demonstrative purposes. 

1862 requests = [request] 

1863 

1864 def request_generator(): 

1865 for request in requests: 

1866 yield request 

1867 

1868 # Make the request 

1869 stream = client.streaming_pull(requests=request_generator()) 

1870 

1871 # Handle the response 

1872 for response in stream: 

1873 print(response) 

1874 

1875 Args: 

1876 requests (Iterator[google.pubsub_v1.types.StreamingPullRequest]): 

1877 The request object iterator. Request for the ``StreamingPull`` streaming RPC method. 

1878 This request is used to establish the initial stream as 

1879 well as to stream acknowledgements and ack deadline 

1880 modifications from the client to the server. 

1881 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1882 should be retried. 

1883 timeout (float): The timeout for this request. 

1884 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1885 sent along with the request as metadata. Normally, each value must be of type `str`, 

1886 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1887 be of type `bytes`. 

1888 

1889 Returns: 

1890 Iterable[google.pubsub_v1.types.StreamingPullResponse]: 

1891 Response for the StreamingPull method. This response is used to stream 

1892 messages from the server to the client. 

1893 

1894 """ 

1895 

1896 # Wrappers in api-core should not automatically pre-fetch the first 

1897 # stream result, as this breaks the stream when re-opening it. 

1898 # https://github.com/googleapis/python-pubsub/issues/93#issuecomment-630762257 

1899 self._transport.streaming_pull._prefetch_first_result_ = False 

1900 

1901 # Wrap the RPC method; this adds retry and timeout information, 

1902 # and friendly error handling. 

1903 rpc = self._transport._wrapped_methods[self._transport.streaming_pull] 

1904 

1905 # Validate the universe domain. 

1906 self._validate_universe_domain() 

1907 

1908 # Send the request. 

1909 response = rpc( 

1910 requests, 

1911 retry=retry, 

1912 timeout=timeout, 

1913 metadata=metadata, 

1914 ) 

1915 

1916 # Done; return the response. 

1917 return response 

1918 

1919 def modify_push_config( 

1920 self, 

1921 request: Optional[Union[pubsub.ModifyPushConfigRequest, dict]] = None, 

1922 *, 

1923 subscription: Optional[str] = None, 

1924 push_config: Optional[pubsub.PushConfig] = None, 

1925 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1926 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

1927 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

1928 ) -> None: 

1929 r"""Modifies the ``PushConfig`` for a specified subscription. 

1930 

1931 This may be used to change a push subscription to a pull one 

1932 (signified by an empty ``PushConfig``) or vice versa, or change 

1933 the endpoint URL and other attributes of a push subscription. 

1934 Messages will accumulate for delivery continuously through the 

1935 call regardless of changes to the ``PushConfig``. 

1936 

1937 .. code-block:: python 

1938 

1939 # This snippet has been automatically generated and should be regarded as a 

1940 # code template only. 

1941 # It will require modifications to work: 

1942 # - It may require correct/in-range values for request initialization. 

1943 # - It may require specifying regional endpoints when creating the service 

1944 # client as shown in: 

1945 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

1946 from google import pubsub_v1 

1947 

1948 def sample_modify_push_config(): 

1949 # Create a client 

1950 client = pubsub_v1.SubscriberClient() 

1951 

1952 # Initialize request argument(s) 

1953 request = pubsub_v1.ModifyPushConfigRequest( 

1954 subscription="subscription_value", 

1955 ) 

1956 

1957 # Make the request 

1958 client.modify_push_config(request=request) 

1959 

1960 Args: 

1961 request (Union[google.pubsub_v1.types.ModifyPushConfigRequest, dict]): 

1962 The request object. Request for the ModifyPushConfig 

1963 method. 

1964 subscription (str): 

1965 Required. The name of the subscription. Format is 

1966 ``projects/{project}/subscriptions/{sub}``. 

1967 

1968 This corresponds to the ``subscription`` field 

1969 on the ``request`` instance; if ``request`` is provided, this 

1970 should not be set. 

1971 push_config (google.pubsub_v1.types.PushConfig): 

1972 Required. The push configuration for future deliveries. 

1973 

1974 An empty ``pushConfig`` indicates that the Pub/Sub 

1975 system should stop pushing messages from the given 

1976 subscription and allow messages to be pulled and 

1977 acknowledged - effectively pausing the subscription if 

1978 ``Pull`` or ``StreamingPull`` is not called. 

1979 

1980 This corresponds to the ``push_config`` field 

1981 on the ``request`` instance; if ``request`` is provided, this 

1982 should not be set. 

1983 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

1984 should be retried. 

1985 timeout (float): The timeout for this request. 

1986 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

1987 sent along with the request as metadata. Normally, each value must be of type `str`, 

1988 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

1989 be of type `bytes`. 

1990 """ 

1991 # Create or coerce a protobuf request object. 

1992 # - Quick check: If we got a request object, we should *not* have 

1993 # gotten any keyword arguments that map to the request. 

1994 flattened_params = [subscription, push_config] 

1995 has_flattened_params = ( 

1996 len([param for param in flattened_params if param is not None]) > 0 

1997 ) 

1998 if request is not None and has_flattened_params: 

1999 raise ValueError( 

2000 "If the `request` argument is set, then none of " 

2001 "the individual field arguments should be set." 

2002 ) 

2003 

2004 # - Use the request object if provided (there's no risk of modifying the input as 

2005 # there are no flattened fields), or create one. 

2006 if not isinstance(request, pubsub.ModifyPushConfigRequest): 

2007 request = pubsub.ModifyPushConfigRequest(request) 

2008 # If we have keyword arguments corresponding to fields on the 

2009 # request, apply these. 

2010 if subscription is not None: 

2011 request.subscription = subscription 

2012 if push_config is not None: 

2013 request.push_config = push_config 

2014 

2015 # Wrap the RPC method; this adds retry and timeout information, 

2016 # and friendly error handling. 

2017 rpc = self._transport._wrapped_methods[self._transport.modify_push_config] 

2018 

2019 # Certain fields should be provided within the metadata header; 

2020 # add these here. 

2021 metadata = tuple(metadata) + ( 

2022 gapic_v1.routing_header.to_grpc_metadata( 

2023 (("subscription", request.subscription),) 

2024 ), 

2025 ) 

2026 

2027 # Validate the universe domain. 

2028 self._validate_universe_domain() 

2029 

2030 # Send the request. 

2031 rpc( 

2032 request, 

2033 retry=retry, 

2034 timeout=timeout, 

2035 metadata=metadata, 

2036 ) 

2037 

2038 def get_snapshot( 

2039 self, 

2040 request: Optional[Union[pubsub.GetSnapshotRequest, dict]] = None, 

2041 *, 

2042 snapshot: Optional[str] = None, 

2043 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2044 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2045 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2046 ) -> pubsub.Snapshot: 

2047 r"""Gets the configuration details of a snapshot. Snapshots are used 

2048 in 

2049 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__ 

2050 operations, which allow you to manage message acknowledgments in 

2051 bulk. That is, you can set the acknowledgment state of messages 

2052 in an existing subscription to the state captured by a snapshot. 

2053 

2054 .. code-block:: python 

2055 

2056 # This snippet has been automatically generated and should be regarded as a 

2057 # code template only. 

2058 # It will require modifications to work: 

2059 # - It may require correct/in-range values for request initialization. 

2060 # - It may require specifying regional endpoints when creating the service 

2061 # client as shown in: 

2062 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2063 from google import pubsub_v1 

2064 

2065 def sample_get_snapshot(): 

2066 # Create a client 

2067 client = pubsub_v1.SubscriberClient() 

2068 

2069 # Initialize request argument(s) 

2070 request = pubsub_v1.GetSnapshotRequest( 

2071 snapshot="snapshot_value", 

2072 ) 

2073 

2074 # Make the request 

2075 response = client.get_snapshot(request=request) 

2076 

2077 # Handle the response 

2078 print(response) 

2079 

2080 Args: 

2081 request (Union[google.pubsub_v1.types.GetSnapshotRequest, dict]): 

2082 The request object. Request for the GetSnapshot method. 

2083 snapshot (str): 

2084 Required. The name of the snapshot to get. Format is 

2085 ``projects/{project}/snapshots/{snap}``. 

2086 

2087 This corresponds to the ``snapshot`` field 

2088 on the ``request`` instance; if ``request`` is provided, this 

2089 should not be set. 

2090 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2091 should be retried. 

2092 timeout (float): The timeout for this request. 

2093 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2094 sent along with the request as metadata. Normally, each value must be of type `str`, 

2095 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2096 be of type `bytes`. 

2097 

2098 Returns: 

2099 google.pubsub_v1.types.Snapshot: 

2100 A snapshot resource. Snapshots are used in 

2101 [Seek](https://cloud.google.com/pubsub/docs/replay-overview) 

2102 operations, which allow you to manage message 

2103 acknowledgments in bulk. That is, you can set the 

2104 acknowledgment state of messages in an existing 

2105 subscription to the state captured by a snapshot. 

2106 

2107 """ 

2108 # Create or coerce a protobuf request object. 

2109 # - Quick check: If we got a request object, we should *not* have 

2110 # gotten any keyword arguments that map to the request. 

2111 flattened_params = [snapshot] 

2112 has_flattened_params = ( 

2113 len([param for param in flattened_params if param is not None]) > 0 

2114 ) 

2115 if request is not None and has_flattened_params: 

2116 raise ValueError( 

2117 "If the `request` argument is set, then none of " 

2118 "the individual field arguments should be set." 

2119 ) 

2120 

2121 # - Use the request object if provided (there's no risk of modifying the input as 

2122 # there are no flattened fields), or create one. 

2123 if not isinstance(request, pubsub.GetSnapshotRequest): 

2124 request = pubsub.GetSnapshotRequest(request) 

2125 # If we have keyword arguments corresponding to fields on the 

2126 # request, apply these. 

2127 if snapshot is not None: 

2128 request.snapshot = snapshot 

2129 

2130 # Wrap the RPC method; this adds retry and timeout information, 

2131 # and friendly error handling. 

2132 rpc = self._transport._wrapped_methods[self._transport.get_snapshot] 

2133 

2134 # Certain fields should be provided within the metadata header; 

2135 # add these here. 

2136 metadata = tuple(metadata) + ( 

2137 gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)), 

2138 ) 

2139 

2140 # Validate the universe domain. 

2141 self._validate_universe_domain() 

2142 

2143 # Send the request. 

2144 response = rpc( 

2145 request, 

2146 retry=retry, 

2147 timeout=timeout, 

2148 metadata=metadata, 

2149 ) 

2150 

2151 # Done; return the response. 

2152 return response 

2153 

2154 def list_snapshots( 

2155 self, 

2156 request: Optional[Union[pubsub.ListSnapshotsRequest, dict]] = None, 

2157 *, 

2158 project: Optional[str] = None, 

2159 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2160 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2161 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2162 ) -> pagers.ListSnapshotsPager: 

2163 r"""Lists the existing snapshots. Snapshots are used in 

2164 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__ 

2165 operations, which allow you to manage message acknowledgments in 

2166 bulk. That is, you can set the acknowledgment state of messages 

2167 in an existing subscription to the state captured by a snapshot. 

2168 

2169 .. code-block:: python 

2170 

2171 # This snippet has been automatically generated and should be regarded as a 

2172 # code template only. 

2173 # It will require modifications to work: 

2174 # - It may require correct/in-range values for request initialization. 

2175 # - It may require specifying regional endpoints when creating the service 

2176 # client as shown in: 

2177 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2178 from google import pubsub_v1 

2179 

2180 def sample_list_snapshots(): 

2181 # Create a client 

2182 client = pubsub_v1.SubscriberClient() 

2183 

2184 # Initialize request argument(s) 

2185 request = pubsub_v1.ListSnapshotsRequest( 

2186 project="project_value", 

2187 ) 

2188 

2189 # Make the request 

2190 page_result = client.list_snapshots(request=request) 

2191 

2192 # Handle the response 

2193 for response in page_result: 

2194 print(response) 

2195 

2196 Args: 

2197 request (Union[google.pubsub_v1.types.ListSnapshotsRequest, dict]): 

2198 The request object. Request for the ``ListSnapshots`` method. 

2199 project (str): 

2200 Required. The name of the project in which to list 

2201 snapshots. Format is ``projects/{project-id}``. 

2202 

2203 This corresponds to the ``project`` field 

2204 on the ``request`` instance; if ``request`` is provided, this 

2205 should not be set. 

2206 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2207 should be retried. 

2208 timeout (float): The timeout for this request. 

2209 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2210 sent along with the request as metadata. Normally, each value must be of type `str`, 

2211 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2212 be of type `bytes`. 

2213 

2214 Returns: 

2215 google.pubsub_v1.services.subscriber.pagers.ListSnapshotsPager: 

2216 Response for the ListSnapshots method. 

2217 

2218 Iterating over this object will yield results and 

2219 resolve additional pages automatically. 

2220 

2221 """ 

2222 # Create or coerce a protobuf request object. 

2223 # - Quick check: If we got a request object, we should *not* have 

2224 # gotten any keyword arguments that map to the request. 

2225 flattened_params = [project] 

2226 has_flattened_params = ( 

2227 len([param for param in flattened_params if param is not None]) > 0 

2228 ) 

2229 if request is not None and has_flattened_params: 

2230 raise ValueError( 

2231 "If the `request` argument is set, then none of " 

2232 "the individual field arguments should be set." 

2233 ) 

2234 

2235 # - Use the request object if provided (there's no risk of modifying the input as 

2236 # there are no flattened fields), or create one. 

2237 if not isinstance(request, pubsub.ListSnapshotsRequest): 

2238 request = pubsub.ListSnapshotsRequest(request) 

2239 # If we have keyword arguments corresponding to fields on the 

2240 # request, apply these. 

2241 if project is not None: 

2242 request.project = project 

2243 

2244 # Wrap the RPC method; this adds retry and timeout information, 

2245 # and friendly error handling. 

2246 rpc = self._transport._wrapped_methods[self._transport.list_snapshots] 

2247 

2248 # Certain fields should be provided within the metadata header; 

2249 # add these here. 

2250 metadata = tuple(metadata) + ( 

2251 gapic_v1.routing_header.to_grpc_metadata((("project", request.project),)), 

2252 ) 

2253 

2254 # Validate the universe domain. 

2255 self._validate_universe_domain() 

2256 

2257 # Send the request. 

2258 response = rpc( 

2259 request, 

2260 retry=retry, 

2261 timeout=timeout, 

2262 metadata=metadata, 

2263 ) 

2264 

2265 # This method is paged; wrap the response in a pager, which provides 

2266 # an `__iter__` convenience method. 

2267 response = pagers.ListSnapshotsPager( 

2268 method=rpc, 

2269 request=request, 

2270 response=response, 

2271 retry=retry, 

2272 timeout=timeout, 

2273 metadata=metadata, 

2274 ) 

2275 

2276 # Done; return the response. 

2277 return response 

2278 

2279 def create_snapshot( 

2280 self, 

2281 request: Optional[Union[pubsub.CreateSnapshotRequest, dict]] = None, 

2282 *, 

2283 name: Optional[str] = None, 

2284 subscription: Optional[str] = None, 

2285 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2286 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2287 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2288 ) -> pubsub.Snapshot: 

2289 r"""Creates a snapshot from the requested subscription. Snapshots 

2290 are used in 

2291 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__ 

2292 operations, which allow you to manage message acknowledgments in 

2293 bulk. That is, you can set the acknowledgment state of messages 

2294 in an existing subscription to the state captured by a snapshot. 

2295 If the snapshot already exists, returns ``ALREADY_EXISTS``. If 

2296 the requested subscription doesn't exist, returns ``NOT_FOUND``. 

2297 If the backlog in the subscription is too old -- and the 

2298 resulting snapshot would expire in less than 1 hour -- then 

2299 ``FAILED_PRECONDITION`` is returned. See also the 

2300 ``Snapshot.expire_time`` field. If the name is not provided in 

2301 the request, the server will assign a random name for this 

2302 snapshot on the same project as the subscription, conforming to 

2303 the [resource name format] 

2304 (https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names). 

2305 The generated name is populated in the returned Snapshot object. 

2306 Note that for REST API requests, you must specify a name in the 

2307 request. 

2308 

2309 .. code-block:: python 

2310 

2311 # This snippet has been automatically generated and should be regarded as a 

2312 # code template only. 

2313 # It will require modifications to work: 

2314 # - It may require correct/in-range values for request initialization. 

2315 # - It may require specifying regional endpoints when creating the service 

2316 # client as shown in: 

2317 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2318 from google import pubsub_v1 

2319 

2320 def sample_create_snapshot(): 

2321 # Create a client 

2322 client = pubsub_v1.SubscriberClient() 

2323 

2324 # Initialize request argument(s) 

2325 request = pubsub_v1.CreateSnapshotRequest( 

2326 name="name_value", 

2327 subscription="subscription_value", 

2328 ) 

2329 

2330 # Make the request 

2331 response = client.create_snapshot(request=request) 

2332 

2333 # Handle the response 

2334 print(response) 

2335 

2336 Args: 

2337 request (Union[google.pubsub_v1.types.CreateSnapshotRequest, dict]): 

2338 The request object. Request for the ``CreateSnapshot`` method. 

2339 name (str): 

2340 Required. User-provided name for this snapshot. If the 

2341 name is not provided in the request, the server will 

2342 assign a random name for this snapshot on the same 

2343 project as the subscription. Note that for REST API 

2344 requests, you must specify a name. See the `resource 

2345 name 

2346 rules <https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names>`__. 

2347 Format is ``projects/{project}/snapshots/{snap}``. 

2348 

2349 This corresponds to the ``name`` field 

2350 on the ``request`` instance; if ``request`` is provided, this 

2351 should not be set. 

2352 subscription (str): 

2353 Required. The subscription whose backlog the snapshot 

2354 retains. Specifically, the created snapshot is 

2355 guaranteed to retain: (a) The existing backlog on the 

2356 subscription. More precisely, this is defined as the 

2357 messages in the subscription's backlog that are 

2358 unacknowledged upon the successful completion of the 

2359 ``CreateSnapshot`` request; as well as: (b) Any messages 

2360 published to the subscription's topic following the 

2361 successful completion of the CreateSnapshot request. 

2362 Format is ``projects/{project}/subscriptions/{sub}``. 

2363 

2364 This corresponds to the ``subscription`` field 

2365 on the ``request`` instance; if ``request`` is provided, this 

2366 should not be set. 

2367 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2368 should be retried. 

2369 timeout (float): The timeout for this request. 

2370 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2371 sent along with the request as metadata. Normally, each value must be of type `str`, 

2372 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2373 be of type `bytes`. 

2374 

2375 Returns: 

2376 google.pubsub_v1.types.Snapshot: 

2377 A snapshot resource. Snapshots are used in 

2378 [Seek](https://cloud.google.com/pubsub/docs/replay-overview) 

2379 operations, which allow you to manage message 

2380 acknowledgments in bulk. That is, you can set the 

2381 acknowledgment state of messages in an existing 

2382 subscription to the state captured by a snapshot. 

2383 

2384 """ 

2385 # Create or coerce a protobuf request object. 

2386 # - Quick check: If we got a request object, we should *not* have 

2387 # gotten any keyword arguments that map to the request. 

2388 flattened_params = [name, subscription] 

2389 has_flattened_params = ( 

2390 len([param for param in flattened_params if param is not None]) > 0 

2391 ) 

2392 if request is not None and has_flattened_params: 

2393 raise ValueError( 

2394 "If the `request` argument is set, then none of " 

2395 "the individual field arguments should be set." 

2396 ) 

2397 

2398 # - Use the request object if provided (there's no risk of modifying the input as 

2399 # there are no flattened fields), or create one. 

2400 if not isinstance(request, pubsub.CreateSnapshotRequest): 

2401 request = pubsub.CreateSnapshotRequest(request) 

2402 # If we have keyword arguments corresponding to fields on the 

2403 # request, apply these. 

2404 if name is not None: 

2405 request.name = name 

2406 if subscription is not None: 

2407 request.subscription = subscription 

2408 

2409 # Wrap the RPC method; this adds retry and timeout information, 

2410 # and friendly error handling. 

2411 rpc = self._transport._wrapped_methods[self._transport.create_snapshot] 

2412 

2413 # Certain fields should be provided within the metadata header; 

2414 # add these here. 

2415 metadata = tuple(metadata) + ( 

2416 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)), 

2417 ) 

2418 

2419 # Validate the universe domain. 

2420 self._validate_universe_domain() 

2421 

2422 # Send the request. 

2423 response = rpc( 

2424 request, 

2425 retry=retry, 

2426 timeout=timeout, 

2427 metadata=metadata, 

2428 ) 

2429 

2430 # Done; return the response. 

2431 return response 

2432 

2433 def update_snapshot( 

2434 self, 

2435 request: Optional[Union[pubsub.UpdateSnapshotRequest, dict]] = None, 

2436 *, 

2437 snapshot: Optional[pubsub.Snapshot] = None, 

2438 update_mask: Optional[field_mask_pb2.FieldMask] = None, 

2439 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2440 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2441 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2442 ) -> pubsub.Snapshot: 

2443 r"""Updates an existing snapshot by updating the fields specified in 

2444 the update mask. Snapshots are used in 

2445 `Seek <https://cloud.google.com/pubsub/docs/replay-overview>`__ 

2446 operations, which allow you to manage message acknowledgments in 

2447 bulk. That is, you can set the acknowledgment state of messages 

2448 in an existing subscription to the state captured by a snapshot. 

2449 

2450 .. code-block:: python 

2451 

2452 # This snippet has been automatically generated and should be regarded as a 

2453 # code template only. 

2454 # It will require modifications to work: 

2455 # - It may require correct/in-range values for request initialization. 

2456 # - It may require specifying regional endpoints when creating the service 

2457 # client as shown in: 

2458 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2459 from google import pubsub_v1 

2460 

2461 def sample_update_snapshot(): 

2462 # Create a client 

2463 client = pubsub_v1.SubscriberClient() 

2464 

2465 # Initialize request argument(s) 

2466 request = pubsub_v1.UpdateSnapshotRequest( 

2467 ) 

2468 

2469 # Make the request 

2470 response = client.update_snapshot(request=request) 

2471 

2472 # Handle the response 

2473 print(response) 

2474 

2475 Args: 

2476 request (Union[google.pubsub_v1.types.UpdateSnapshotRequest, dict]): 

2477 The request object. Request for the UpdateSnapshot 

2478 method. 

2479 snapshot (google.pubsub_v1.types.Snapshot): 

2480 Required. The updated snapshot 

2481 object. 

2482 

2483 This corresponds to the ``snapshot`` field 

2484 on the ``request`` instance; if ``request`` is provided, this 

2485 should not be set. 

2486 update_mask (google.protobuf.field_mask_pb2.FieldMask): 

2487 Required. Indicates which fields in 

2488 the provided snapshot to update. Must be 

2489 specified and non-empty. 

2490 

2491 This corresponds to the ``update_mask`` field 

2492 on the ``request`` instance; if ``request`` is provided, this 

2493 should not be set. 

2494 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2495 should be retried. 

2496 timeout (float): The timeout for this request. 

2497 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2498 sent along with the request as metadata. Normally, each value must be of type `str`, 

2499 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2500 be of type `bytes`. 

2501 

2502 Returns: 

2503 google.pubsub_v1.types.Snapshot: 

2504 A snapshot resource. Snapshots are used in 

2505 [Seek](https://cloud.google.com/pubsub/docs/replay-overview) 

2506 operations, which allow you to manage message 

2507 acknowledgments in bulk. That is, you can set the 

2508 acknowledgment state of messages in an existing 

2509 subscription to the state captured by a snapshot. 

2510 

2511 """ 

2512 # Create or coerce a protobuf request object. 

2513 # - Quick check: If we got a request object, we should *not* have 

2514 # gotten any keyword arguments that map to the request. 

2515 flattened_params = [snapshot, update_mask] 

2516 has_flattened_params = ( 

2517 len([param for param in flattened_params if param is not None]) > 0 

2518 ) 

2519 if request is not None and has_flattened_params: 

2520 raise ValueError( 

2521 "If the `request` argument is set, then none of " 

2522 "the individual field arguments should be set." 

2523 ) 

2524 

2525 # - Use the request object if provided (there's no risk of modifying the input as 

2526 # there are no flattened fields), or create one. 

2527 if not isinstance(request, pubsub.UpdateSnapshotRequest): 

2528 request = pubsub.UpdateSnapshotRequest(request) 

2529 # If we have keyword arguments corresponding to fields on the 

2530 # request, apply these. 

2531 if snapshot is not None: 

2532 request.snapshot = snapshot 

2533 if update_mask is not None: 

2534 request.update_mask = update_mask 

2535 

2536 # Wrap the RPC method; this adds retry and timeout information, 

2537 # and friendly error handling. 

2538 rpc = self._transport._wrapped_methods[self._transport.update_snapshot] 

2539 

2540 # Certain fields should be provided within the metadata header; 

2541 # add these here. 

2542 metadata = tuple(metadata) + ( 

2543 gapic_v1.routing_header.to_grpc_metadata( 

2544 (("snapshot.name", request.snapshot.name),) 

2545 ), 

2546 ) 

2547 

2548 # Validate the universe domain. 

2549 self._validate_universe_domain() 

2550 

2551 # Send the request. 

2552 response = rpc( 

2553 request, 

2554 retry=retry, 

2555 timeout=timeout, 

2556 metadata=metadata, 

2557 ) 

2558 

2559 # Done; return the response. 

2560 return response 

2561 

2562 def delete_snapshot( 

2563 self, 

2564 request: Optional[Union[pubsub.DeleteSnapshotRequest, dict]] = None, 

2565 *, 

2566 snapshot: Optional[str] = None, 

2567 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2568 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2569 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2570 ) -> None: 

2571 r"""Removes an existing snapshot. Snapshots are used in [Seek] 

2572 (https://cloud.google.com/pubsub/docs/replay-overview) 

2573 operations, which allow you to manage message acknowledgments in 

2574 bulk. That is, you can set the acknowledgment state of messages 

2575 in an existing subscription to the state captured by a snapshot. 

2576 When the snapshot is deleted, all messages retained in the 

2577 snapshot are immediately dropped. After a snapshot is deleted, a 

2578 new one may be created with the same name, but the new one has 

2579 no association with the old snapshot or its subscription, unless 

2580 the same subscription is specified. 

2581 

2582 .. code-block:: python 

2583 

2584 # This snippet has been automatically generated and should be regarded as a 

2585 # code template only. 

2586 # It will require modifications to work: 

2587 # - It may require correct/in-range values for request initialization. 

2588 # - It may require specifying regional endpoints when creating the service 

2589 # client as shown in: 

2590 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2591 from google import pubsub_v1 

2592 

2593 def sample_delete_snapshot(): 

2594 # Create a client 

2595 client = pubsub_v1.SubscriberClient() 

2596 

2597 # Initialize request argument(s) 

2598 request = pubsub_v1.DeleteSnapshotRequest( 

2599 snapshot="snapshot_value", 

2600 ) 

2601 

2602 # Make the request 

2603 client.delete_snapshot(request=request) 

2604 

2605 Args: 

2606 request (Union[google.pubsub_v1.types.DeleteSnapshotRequest, dict]): 

2607 The request object. Request for the ``DeleteSnapshot`` method. 

2608 snapshot (str): 

2609 Required. The name of the snapshot to delete. Format is 

2610 ``projects/{project}/snapshots/{snap}``. 

2611 

2612 This corresponds to the ``snapshot`` field 

2613 on the ``request`` instance; if ``request`` is provided, this 

2614 should not be set. 

2615 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2616 should be retried. 

2617 timeout (float): The timeout for this request. 

2618 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2619 sent along with the request as metadata. Normally, each value must be of type `str`, 

2620 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2621 be of type `bytes`. 

2622 """ 

2623 # Create or coerce a protobuf request object. 

2624 # - Quick check: If we got a request object, we should *not* have 

2625 # gotten any keyword arguments that map to the request. 

2626 flattened_params = [snapshot] 

2627 has_flattened_params = ( 

2628 len([param for param in flattened_params if param is not None]) > 0 

2629 ) 

2630 if request is not None and has_flattened_params: 

2631 raise ValueError( 

2632 "If the `request` argument is set, then none of " 

2633 "the individual field arguments should be set." 

2634 ) 

2635 

2636 # - Use the request object if provided (there's no risk of modifying the input as 

2637 # there are no flattened fields), or create one. 

2638 if not isinstance(request, pubsub.DeleteSnapshotRequest): 

2639 request = pubsub.DeleteSnapshotRequest(request) 

2640 # If we have keyword arguments corresponding to fields on the 

2641 # request, apply these. 

2642 if snapshot is not None: 

2643 request.snapshot = snapshot 

2644 

2645 # Wrap the RPC method; this adds retry and timeout information, 

2646 # and friendly error handling. 

2647 rpc = self._transport._wrapped_methods[self._transport.delete_snapshot] 

2648 

2649 # Certain fields should be provided within the metadata header; 

2650 # add these here. 

2651 metadata = tuple(metadata) + ( 

2652 gapic_v1.routing_header.to_grpc_metadata((("snapshot", request.snapshot),)), 

2653 ) 

2654 

2655 # Validate the universe domain. 

2656 self._validate_universe_domain() 

2657 

2658 # Send the request. 

2659 rpc( 

2660 request, 

2661 retry=retry, 

2662 timeout=timeout, 

2663 metadata=metadata, 

2664 ) 

2665 

2666 def seek( 

2667 self, 

2668 request: Optional[Union[pubsub.SeekRequest, dict]] = None, 

2669 *, 

2670 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2671 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2672 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2673 ) -> pubsub.SeekResponse: 

2674 r"""Seeks an existing subscription to a point in time or to a given 

2675 snapshot, whichever is provided in the request. Snapshots are 

2676 used in [Seek] 

2677 (https://cloud.google.com/pubsub/docs/replay-overview) 

2678 operations, which allow you to manage message acknowledgments in 

2679 bulk. That is, you can set the acknowledgment state of messages 

2680 in an existing subscription to the state captured by a snapshot. 

2681 Note that both the subscription and the snapshot must be on the 

2682 same topic. 

2683 

2684 .. code-block:: python 

2685 

2686 # This snippet has been automatically generated and should be regarded as a 

2687 # code template only. 

2688 # It will require modifications to work: 

2689 # - It may require correct/in-range values for request initialization. 

2690 # - It may require specifying regional endpoints when creating the service 

2691 # client as shown in: 

2692 # https://googleapis.dev/python/google-api-core/latest/client_options.html 

2693 from google import pubsub_v1 

2694 

2695 def sample_seek(): 

2696 # Create a client 

2697 client = pubsub_v1.SubscriberClient() 

2698 

2699 # Initialize request argument(s) 

2700 request = pubsub_v1.SeekRequest( 

2701 subscription="subscription_value", 

2702 ) 

2703 

2704 # Make the request 

2705 response = client.seek(request=request) 

2706 

2707 # Handle the response 

2708 print(response) 

2709 

2710 Args: 

2711 request (Union[google.pubsub_v1.types.SeekRequest, dict]): 

2712 The request object. Request for the ``Seek`` method. 

2713 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2714 should be retried. 

2715 timeout (float): The timeout for this request. 

2716 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2717 sent along with the request as metadata. Normally, each value must be of type `str`, 

2718 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2719 be of type `bytes`. 

2720 

2721 Returns: 

2722 google.pubsub_v1.types.SeekResponse: 

2723 Response for the Seek method (this response is empty). 

2724 """ 

2725 # Create or coerce a protobuf request object. 

2726 # - Use the request object if provided (there's no risk of modifying the input as 

2727 # there are no flattened fields), or create one. 

2728 if not isinstance(request, pubsub.SeekRequest): 

2729 request = pubsub.SeekRequest(request) 

2730 

2731 # Wrap the RPC method; this adds retry and timeout information, 

2732 # and friendly error handling. 

2733 rpc = self._transport._wrapped_methods[self._transport.seek] 

2734 

2735 # Certain fields should be provided within the metadata header; 

2736 # add these here. 

2737 metadata = tuple(metadata) + ( 

2738 gapic_v1.routing_header.to_grpc_metadata( 

2739 (("subscription", request.subscription),) 

2740 ), 

2741 ) 

2742 

2743 # Validate the universe domain. 

2744 self._validate_universe_domain() 

2745 

2746 # Send the request. 

2747 response = rpc( 

2748 request, 

2749 retry=retry, 

2750 timeout=timeout, 

2751 metadata=metadata, 

2752 ) 

2753 

2754 # Done; return the response. 

2755 return response 

2756 

2757 def __enter__(self) -> "SubscriberClient": 

2758 return self 

2759 

2760 def __exit__(self, type, value, traceback): 

2761 """Releases underlying transport's resources. 

2762 

2763 .. warning:: 

2764 ONLY use as a context manager if the transport is NOT shared 

2765 with other clients! Exiting the with block will CLOSE the transport 

2766 and may cause errors in other clients! 

2767 """ 

2768 self.transport.close() 

2769 

2770 def set_iam_policy( 

2771 self, 

2772 request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, 

2773 *, 

2774 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2775 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2776 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2777 ) -> policy_pb2.Policy: 

2778 r"""Sets the IAM access control policy on the specified function. 

2779 

2780 Replaces any existing policy. 

2781 

2782 Args: 

2783 request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): 

2784 The request object. Request message for `SetIamPolicy` 

2785 method. 

2786 retry (google.api_core.retry.Retry): Designation of what errors, if any, 

2787 should be retried. 

2788 timeout (float): The timeout for this request. 

2789 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2790 sent along with the request as metadata. Normally, each value must be of type `str`, 

2791 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2792 be of type `bytes`. 

2793 Returns: 

2794 ~.policy_pb2.Policy: 

2795 Defines an Identity and Access Management (IAM) policy. 

2796 It is used to specify access control policies for Cloud 

2797 Platform resources. 

2798 A ``Policy`` is a collection of ``bindings``. A 

2799 ``binding`` binds one or more ``members`` to a single 

2800 ``role``. Members can be user accounts, service 

2801 accounts, Google groups, and domains (such as G Suite). 

2802 A ``role`` is a named list of permissions (defined by 

2803 IAM or configured by users). A ``binding`` can 

2804 optionally specify a ``condition``, which is a logic 

2805 expression that further constrains the role binding 

2806 based on attributes about the request and/or target 

2807 resource. 

2808 

2809 **JSON Example** 

2810 

2811 :: 

2812 

2813 { 

2814 "bindings": [ 

2815 { 

2816 "role": "roles/resourcemanager.organizationAdmin", 

2817 "members": [ 

2818 "user:mike@example.com", 

2819 "group:admins@example.com", 

2820 "domain:google.com", 

2821 "serviceAccount:my-project-id@appspot.gserviceaccount.com" 

2822 ] 

2823 }, 

2824 { 

2825 "role": "roles/resourcemanager.organizationViewer", 

2826 "members": ["user:eve@example.com"], 

2827 "condition": { 

2828 "title": "expirable access", 

2829 "description": "Does not grant access after Sep 2020", 

2830 "expression": "request.time < 

2831 timestamp('2020-10-01T00:00:00.000Z')", 

2832 } 

2833 } 

2834 ] 

2835 } 

2836 

2837 **YAML Example** 

2838 

2839 :: 

2840 

2841 bindings: 

2842 - members: 

2843 - user:mike@example.com 

2844 - group:admins@example.com 

2845 - domain:google.com 

2846 - serviceAccount:my-project-id@appspot.gserviceaccount.com 

2847 role: roles/resourcemanager.organizationAdmin 

2848 - members: 

2849 - user:eve@example.com 

2850 role: roles/resourcemanager.organizationViewer 

2851 condition: 

2852 title: expirable access 

2853 description: Does not grant access after Sep 2020 

2854 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') 

2855 

2856 For a description of IAM and its features, see the `IAM 

2857 developer's 

2858 guide <https://cloud.google.com/iam/docs>`__. 

2859 """ 

2860 # Create or coerce a protobuf request object. 

2861 

2862 # The request isn't a proto-plus wrapped type, 

2863 # so it must be constructed via keyword expansion. 

2864 if isinstance(request, dict): 

2865 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

2866 

2867 # Wrap the RPC method; this adds retry and timeout information, 

2868 # and friendly error handling. 

2869 rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] 

2870 

2871 # Certain fields should be provided within the metadata header; 

2872 # add these here. 

2873 metadata = tuple(metadata) + ( 

2874 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

2875 ) 

2876 

2877 # Validate the universe domain. 

2878 self._validate_universe_domain() 

2879 

2880 try: 

2881 # Send the request. 

2882 response = rpc( 

2883 request, 

2884 retry=retry, 

2885 timeout=timeout, 

2886 metadata=metadata, 

2887 ) 

2888 

2889 # Done; return the response. 

2890 return response 

2891 except core_exceptions.GoogleAPICallError as e: 

2892 self._add_cred_info_for_auth_errors(e) 

2893 raise e 

2894 

2895 def get_iam_policy( 

2896 self, 

2897 request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, 

2898 *, 

2899 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2900 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

2901 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

2902 ) -> policy_pb2.Policy: 

2903 r"""Gets the IAM access control policy for a function. 

2904 

2905 Returns an empty policy if the function exists and does not have a 

2906 policy set. 

2907 

2908 Args: 

2909 request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): 

2910 The request object. Request message for `GetIamPolicy` 

2911 method. 

2912 retry (google.api_core.retry.Retry): Designation of what errors, if 

2913 any, should be retried. 

2914 timeout (float): The timeout for this request. 

2915 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

2916 sent along with the request as metadata. Normally, each value must be of type `str`, 

2917 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

2918 be of type `bytes`. 

2919 Returns: 

2920 ~.policy_pb2.Policy: 

2921 Defines an Identity and Access Management (IAM) policy. 

2922 It is used to specify access control policies for Cloud 

2923 Platform resources. 

2924 A ``Policy`` is a collection of ``bindings``. A 

2925 ``binding`` binds one or more ``members`` to a single 

2926 ``role``. Members can be user accounts, service 

2927 accounts, Google groups, and domains (such as G Suite). 

2928 A ``role`` is a named list of permissions (defined by 

2929 IAM or configured by users). A ``binding`` can 

2930 optionally specify a ``condition``, which is a logic 

2931 expression that further constrains the role binding 

2932 based on attributes about the request and/or target 

2933 resource. 

2934 

2935 **JSON Example** 

2936 

2937 :: 

2938 

2939 { 

2940 "bindings": [ 

2941 { 

2942 "role": "roles/resourcemanager.organizationAdmin", 

2943 "members": [ 

2944 "user:mike@example.com", 

2945 "group:admins@example.com", 

2946 "domain:google.com", 

2947 "serviceAccount:my-project-id@appspot.gserviceaccount.com" 

2948 ] 

2949 }, 

2950 { 

2951 "role": "roles/resourcemanager.organizationViewer", 

2952 "members": ["user:eve@example.com"], 

2953 "condition": { 

2954 "title": "expirable access", 

2955 "description": "Does not grant access after Sep 2020", 

2956 "expression": "request.time < 

2957 timestamp('2020-10-01T00:00:00.000Z')", 

2958 } 

2959 } 

2960 ] 

2961 } 

2962 

2963 **YAML Example** 

2964 

2965 :: 

2966 

2967 bindings: 

2968 - members: 

2969 - user:mike@example.com 

2970 - group:admins@example.com 

2971 - domain:google.com 

2972 - serviceAccount:my-project-id@appspot.gserviceaccount.com 

2973 role: roles/resourcemanager.organizationAdmin 

2974 - members: 

2975 - user:eve@example.com 

2976 role: roles/resourcemanager.organizationViewer 

2977 condition: 

2978 title: expirable access 

2979 description: Does not grant access after Sep 2020 

2980 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') 

2981 

2982 For a description of IAM and its features, see the `IAM 

2983 developer's 

2984 guide <https://cloud.google.com/iam/docs>`__. 

2985 """ 

2986 # Create or coerce a protobuf request object. 

2987 

2988 # The request isn't a proto-plus wrapped type, 

2989 # so it must be constructed via keyword expansion. 

2990 if isinstance(request, dict): 

2991 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

2992 

2993 # Wrap the RPC method; this adds retry and timeout information, 

2994 # and friendly error handling. 

2995 rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] 

2996 

2997 # Certain fields should be provided within the metadata header; 

2998 # add these here. 

2999 metadata = tuple(metadata) + ( 

3000 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

3001 ) 

3002 

3003 # Validate the universe domain. 

3004 self._validate_universe_domain() 

3005 

3006 try: 

3007 # Send the request. 

3008 response = rpc( 

3009 request, 

3010 retry=retry, 

3011 timeout=timeout, 

3012 metadata=metadata, 

3013 ) 

3014 

3015 # Done; return the response. 

3016 return response 

3017 except core_exceptions.GoogleAPICallError as e: 

3018 self._add_cred_info_for_auth_errors(e) 

3019 raise e 

3020 

3021 def test_iam_permissions( 

3022 self, 

3023 request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, 

3024 *, 

3025 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

3026 timeout: Union[float, object] = gapic_v1.method.DEFAULT, 

3027 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (), 

3028 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

3029 r"""Tests the specified IAM permissions against the IAM access control 

3030 policy for a function. 

3031 

3032 If the function does not exist, this will return an empty set 

3033 of permissions, not a NOT_FOUND error. 

3034 

3035 Args: 

3036 request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): 

3037 The request object. Request message for 

3038 `TestIamPermissions` method. 

3039 retry (google.api_core.retry.Retry): Designation of what errors, 

3040 if any, should be retried. 

3041 timeout (float): The timeout for this request. 

3042 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be 

3043 sent along with the request as metadata. Normally, each value must be of type `str`, 

3044 but for metadata keys ending with the suffix `-bin`, the corresponding values must 

3045 be of type `bytes`. 

3046 Returns: 

3047 ~.iam_policy_pb2.TestIamPermissionsResponse: 

3048 Response message for ``TestIamPermissions`` method. 

3049 """ 

3050 # Create or coerce a protobuf request object. 

3051 

3052 # The request isn't a proto-plus wrapped type, 

3053 # so it must be constructed via keyword expansion. 

3054 if isinstance(request, dict): 

3055 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

3056 

3057 # Wrap the RPC method; this adds retry and timeout information, 

3058 # and friendly error handling. 

3059 rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] 

3060 

3061 # Certain fields should be provided within the metadata header; 

3062 # add these here. 

3063 metadata = tuple(metadata) + ( 

3064 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

3065 ) 

3066 

3067 # Validate the universe domain. 

3068 self._validate_universe_domain() 

3069 

3070 try: 

3071 # Send the request. 

3072 response = rpc( 

3073 request, 

3074 retry=retry, 

3075 timeout=timeout, 

3076 metadata=metadata, 

3077 ) 

3078 

3079 # Done; return the response. 

3080 return response 

3081 except core_exceptions.GoogleAPICallError as e: 

3082 self._add_cred_info_for_auth_errors(e) 

3083 raise e 

3084 

3085 

3086DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

3087 client_library_version=package_version.__version__ 

3088) 

3089 

3090 

3091__all__ = ("SubscriberClient",)