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

405 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-06-07 06:03 +0000

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

2# Copyright 2022 Google LLC 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# 

8# http://www.apache.org/licenses/LICENSE-2.0 

9# 

10# Unless required by applicable law or agreed to in writing, software 

11# distributed under the License is distributed on an "AS IS" BASIS, 

12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

13# See the License for the specific language governing permissions and 

14# limitations under the License. 

15# 

16from collections import OrderedDict 

17import functools 

18import os 

19import re 

20from typing import ( 

21 Dict, 

22 Mapping, 

23 MutableMapping, 

24 MutableSequence, 

25 Optional, 

26 Iterable, 

27 Iterator, 

28 Sequence, 

29 Tuple, 

30 Type, 

31 Union, 

32 cast, 

33) 

34 

35import warnings 

36from google.pubsub_v1 import gapic_version as package_version 

37 

38from google.api_core import client_options as client_options_lib 

39from google.api_core import exceptions as core_exceptions 

40from google.api_core import gapic_v1 

41from google.api_core import retry as retries 

42from google.auth import credentials as ga_credentials # type: ignore 

43from google.auth.transport import mtls # type: ignore 

44from google.auth.transport.grpc import SslCredentials # type: ignore 

45from google.auth.exceptions import MutualTLSChannelError # type: ignore 

46from google.oauth2 import service_account # type: ignore 

47 

48try: 

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

50except AttributeError: # pragma: NO COVER 

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

52 

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

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

55from google.protobuf import duration_pb2 # type: ignore 

56from google.protobuf import field_mask_pb2 # type: ignore 

57from google.protobuf import timestamp_pb2 # type: ignore 

58from google.pubsub_v1.services.subscriber import pagers 

59from google.pubsub_v1.types import pubsub 

60 

61import grpc 

62from .transports.base import SubscriberTransport, DEFAULT_CLIENT_INFO 

63from .transports.grpc import SubscriberGrpcTransport 

64from .transports.grpc_asyncio import SubscriberGrpcAsyncIOTransport 

65from .transports.rest import SubscriberRestTransport 

66 

67 

68class SubscriberClientMeta(type): 

69 """Metaclass for the Subscriber client. 

70 

71 This provides class-level methods for building and retrieving 

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

73 objects. 

74 """ 

75 

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

77 _transport_registry["grpc"] = SubscriberGrpcTransport 

78 _transport_registry["grpc_asyncio"] = SubscriberGrpcAsyncIOTransport 

79 _transport_registry["rest"] = SubscriberRestTransport 

80 

81 def get_transport_class( 

82 cls, 

83 label: Optional[str] = None, 

84 ) -> Type[SubscriberTransport]: 

85 """Returns an appropriate transport class. 

86 

87 Args: 

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

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

90 

91 Returns: 

92 The transport class to use. 

93 """ 

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

95 if label: 

96 return cls._transport_registry[label] 

97 

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

99 # in the dictionary). 

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

101 

102 

103class SubscriberClient(metaclass=SubscriberClientMeta): 

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

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

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

107 method. 

108 """ 

109 

110 @staticmethod 

111 def _get_default_mtls_endpoint(api_endpoint): 

112 """Converts api endpoint to mTLS endpoint. 

113 

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

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

116 Args: 

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

118 Returns: 

119 str: converted mTLS api endpoint. 

120 """ 

121 if not api_endpoint: 

122 return api_endpoint 

123 

124 mtls_endpoint_re = re.compile( 

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

126 ) 

127 

128 m = mtls_endpoint_re.match(api_endpoint) 

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

130 if mtls or not googledomain: 

131 return api_endpoint 

132 

133 if sandbox: 

134 return api_endpoint.replace( 

135 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

136 ) 

137 

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

139 

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

141 # this service 

142 _DEFAULT_SCOPES = ( 

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

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

145 ) 

146 

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

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

149 

150 DEFAULT_ENDPOINT = "pubsub.googleapis.com" 

151 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

152 DEFAULT_ENDPOINT 

153 ) 

154 

155 @classmethod 

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

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

158 info. 

159 

160 Args: 

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

162 args: Additional arguments to pass to the constructor. 

163 kwargs: Additional arguments to pass to the constructor. 

164 

165 Returns: 

166 SubscriberClient: The constructed client. 

167 """ 

168 credentials = service_account.Credentials.from_service_account_info(info) 

169 kwargs["credentials"] = credentials 

170 return cls(*args, **kwargs) 

171 

172 @classmethod 

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

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

175 file. 

176 

177 Args: 

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

179 file. 

180 args: Additional arguments to pass to the constructor. 

181 kwargs: Additional arguments to pass to the constructor. 

182 

183 Returns: 

184 SubscriberClient: The constructed client. 

185 """ 

186 credentials = service_account.Credentials.from_service_account_file(filename) 

187 kwargs["credentials"] = credentials 

188 return cls(*args, **kwargs) 

189 

190 from_service_account_json = from_service_account_file 

191 

192 @property 

193 def transport(self) -> SubscriberTransport: 

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

195 

196 Returns: 

197 SubscriberTransport: The transport used by the client 

198 instance. 

199 """ 

200 return self._transport 

201 

202 @staticmethod 

203 def snapshot_path( 

204 project: str, 

205 snapshot: str, 

206 ) -> str: 

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

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

209 project=project, 

210 snapshot=snapshot, 

211 ) 

212 

213 @staticmethod 

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

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

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

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

218 

219 @staticmethod 

220 def subscription_path( 

221 project: str, 

222 subscription: str, 

223 ) -> str: 

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

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

226 project=project, 

227 subscription=subscription, 

228 ) 

229 

230 @staticmethod 

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

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

233 m = re.match( 

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

235 ) 

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

237 

238 @staticmethod 

239 def topic_path( 

240 project: str, 

241 topic: str, 

242 ) -> str: 

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

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

245 project=project, 

246 topic=topic, 

247 ) 

248 

249 @staticmethod 

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

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

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

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

254 

255 @staticmethod 

256 def common_billing_account_path( 

257 billing_account: str, 

258 ) -> str: 

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

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

261 billing_account=billing_account, 

262 ) 

263 

264 @staticmethod 

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

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

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

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

269 

270 @staticmethod 

271 def common_folder_path( 

272 folder: str, 

273 ) -> str: 

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

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

276 folder=folder, 

277 ) 

278 

279 @staticmethod 

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

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

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

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

284 

285 @staticmethod 

286 def common_organization_path( 

287 organization: str, 

288 ) -> str: 

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

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

291 organization=organization, 

292 ) 

293 

294 @staticmethod 

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

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

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

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

299 

300 @staticmethod 

301 def common_project_path( 

302 project: str, 

303 ) -> str: 

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

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

306 project=project, 

307 ) 

308 

309 @staticmethod 

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

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

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

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

314 

315 @staticmethod 

316 def common_location_path( 

317 project: str, 

318 location: str, 

319 ) -> str: 

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

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

322 project=project, 

323 location=location, 

324 ) 

325 

326 @staticmethod 

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

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

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

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

331 

332 @classmethod 

333 def get_mtls_endpoint_and_cert_source( 

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

335 ): 

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

337 

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

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

340 client cert source is None. 

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

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

343 source is None. 

344 

345 The API endpoint is determined in the following order: 

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

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

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

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

350 use the default API endpoint. 

351 

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

353 

354 Args: 

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

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

357 in this method. 

358 

359 Returns: 

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

361 client cert source to use. 

362 

363 Raises: 

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

365 """ 

366 if client_options is None: 

367 client_options = client_options_lib.ClientOptions() 

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

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

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

371 raise ValueError( 

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

373 ) 

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

375 raise MutualTLSChannelError( 

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

377 ) 

378 

379 # Figure out the client cert source to use. 

380 client_cert_source = None 

381 if use_client_cert == "true": 

382 if client_options.client_cert_source: 

383 client_cert_source = client_options.client_cert_source 

384 elif mtls.has_default_client_cert_source(): 

385 client_cert_source = mtls.default_client_cert_source() 

386 

387 # Figure out which api endpoint to use. 

388 if client_options.api_endpoint is not None: 

389 api_endpoint = client_options.api_endpoint 

390 elif use_mtls_endpoint == "always" or ( 

391 use_mtls_endpoint == "auto" and client_cert_source 

392 ): 

393 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

394 else: 

395 api_endpoint = cls.DEFAULT_ENDPOINT 

396 

397 return api_endpoint, client_cert_source 

398 

399 def __init__( 

400 self, 

401 *, 

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

403 transport: Optional[Union[str, SubscriberTransport]] = None, 

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

405 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

406 ) -> None: 

407 """Instantiates the subscriber client. 

408 

409 Args: 

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

411 authorization credentials to attach to requests. These 

412 credentials identify the application to the service; if none 

413 are specified, the client will attempt to ascertain the 

414 credentials from the environment. 

415 transport (Union[str, SubscriberTransport]): The 

416 transport to use. If set to None, a transport is chosen 

417 automatically. 

418 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]): Custom options for the 

419 client. It won't take effect if a ``transport`` instance is provided. 

420 (1) The ``api_endpoint`` property can be used to override the 

421 default endpoint provided by the client. GOOGLE_API_USE_MTLS_ENDPOINT 

422 environment variable can also be used to override the endpoint: 

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

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

425 default mTLS endpoint if client certificate is present, this is 

426 the default value). However, the ``api_endpoint`` property takes 

427 precedence if provided. 

428 (2) If GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

430 to provide client certificate for mutual TLS transport. If 

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

432 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

433 set, no client certificate will be used. 

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

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

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

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

438 your own client library. 

439 

440 Raises: 

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

442 creation failed for any reason. 

443 """ 

444 if isinstance(client_options, dict): 

445 client_options = client_options_lib.from_dict(client_options) 

446 if client_options is None: 

447 client_options = client_options_lib.ClientOptions() 

448 client_options = cast(client_options_lib.ClientOptions, client_options) 

449 

450 api_endpoint, client_cert_source_func = self.get_mtls_endpoint_and_cert_source( 

451 client_options 

452 ) 

453 

454 api_key_value = getattr(client_options, "api_key", None) 

455 if api_key_value and credentials: 

456 raise ValueError( 

457 "client_options.api_key and credentials are mutually exclusive" 

458 ) 

459 

460 # Save or instantiate the transport. 

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

462 # instance provides an extensibility point for unusual situations. 

463 if isinstance(transport, SubscriberTransport): 

464 # transport is a SubscriberTransport instance. 

465 if credentials or client_options.credentials_file or api_key_value: 

466 raise ValueError( 

467 "When providing a transport instance, " 

468 "provide its credentials directly." 

469 ) 

470 if client_options.scopes: 

471 raise ValueError( 

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

473 "directly." 

474 ) 

475 self._transport = transport 

476 else: 

477 import google.auth._default # type: ignore 

478 

479 if api_key_value and hasattr( 

480 google.auth._default, "get_api_key_credentials" 

481 ): 

482 credentials = google.auth._default.get_api_key_credentials( 

483 api_key_value 

484 ) 

485 

486 Transport = type(self).get_transport_class(transport) 

487 

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

489 if emulator_host: 

490 if issubclass(Transport, type(self)._transport_registry["grpc"]): 

491 channel = grpc.insecure_channel(target=emulator_host) 

492 else: 

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

494 Transport = functools.partial(Transport, channel=channel) 

495 

496 self._transport = Transport( 

497 credentials=credentials, 

498 credentials_file=client_options.credentials_file, 

499 host=api_endpoint, 

500 scopes=client_options.scopes, 

501 client_cert_source_for_mtls=client_cert_source_func, 

502 quota_project_id=client_options.quota_project_id, 

503 client_info=client_info, 

504 always_use_jwt_access=True, 

505 api_audience=client_options.api_audience, 

506 ) 

507 

508 def create_subscription( 

509 self, 

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

511 *, 

512 name: Optional[str] = None, 

513 topic: Optional[str] = None, 

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

515 ack_deadline_seconds: Optional[int] = None, 

516 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

518 metadata: Sequence[Tuple[str, str]] = (), 

519 ) -> pubsub.Subscription: 

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

521 rules] 

522 (https://cloud.google.com/pubsub/docs/admin#resource_names). If 

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

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

525 

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

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

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

529 (https://cloud.google.com/pubsub/docs/admin#resource_names). The 

530 generated name is populated in the returned Subscription object. 

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

532 request. 

533 

534 .. code-block:: python 

535 

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

537 # code template only. 

538 # It will require modifications to work: 

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

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

541 # client as shown in: 

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

543 from google import pubsub_v1 

544 

545 def sample_create_subscription(): 

546 # Create a client 

547 client = pubsub_v1.SubscriberClient() 

548 

549 # Initialize request argument(s) 

550 request = pubsub_v1.Subscription( 

551 name="name_value", 

552 topic="topic_value", 

553 ) 

554 

555 # Make the request 

556 response = client.create_subscription(request=request) 

557 

558 # Handle the response 

559 print(response) 

560 

561 Args: 

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

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

564 ``bigquery_config``, or ``cloud_storage_config`` is set, 

565 then the subscriber will pull and ack messages using API 

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

567 name (str): 

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

569 format 

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

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

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

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

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

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

576 not start with ``"goog"``. 

577 

578 This corresponds to the ``name`` field 

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

580 should not be set. 

581 topic (str): 

582 Required. The name of the topic from which this 

583 subscription is receiving messages. Format is 

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

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

586 deleted. 

587 

588 This corresponds to the ``topic`` field 

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

590 should not be set. 

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

592 If push delivery is used with this 

593 subscription, this field is used to 

594 configure it. 

595 

596 This corresponds to the ``push_config`` field 

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

598 should not be set. 

599 ack_deadline_seconds (int): 

600 The approximate amount of time (on a best-effort basis) 

601 Pub/Sub waits for the subscriber to acknowledge receipt 

602 before resending the message. In the interval after the 

603 message is delivered and before it is acknowledged, it 

604 is considered to be *outstanding*. During that time 

605 period, the message will not be redelivered (on a 

606 best-effort basis). 

607 

608 For pull subscriptions, this value is used as the 

609 initial value for the ack deadline. To override this 

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

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

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

613 ``StreamingModifyAckDeadlineRequest`` if using streaming 

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

615 seconds. The maximum custom deadline you can specify is 

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

617 default value of 10 seconds is used. 

618 

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

620 request timeout for the call to the push endpoint. 

621 

622 If the subscriber never acknowledges the message, the 

623 Pub/Sub system will eventually redeliver the message. 

624 

625 This corresponds to the ``ack_deadline_seconds`` field 

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

627 should not be set. 

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

629 should be retried. 

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

631 metadata (Sequence[Tuple[str, str]]): Strings which should be 

632 sent along with the request as metadata. 

633 

634 Returns: 

635 google.pubsub_v1.types.Subscription: 

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

637 cloud_storage_config is set, then the subscriber will 

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

639 of these fields may be set. 

640 

641 """ 

642 # Create or coerce a protobuf request object. 

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

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

645 has_flattened_params = any([name, topic, push_config, ack_deadline_seconds]) 

646 if request is not None and has_flattened_params: 

647 raise ValueError( 

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

649 "the individual field arguments should be set." 

650 ) 

651 

652 # Minor optimization to avoid making a copy if the user passes 

653 # in a pubsub.Subscription. 

654 # There's no risk of modifying the input as we've already verified 

655 # there are no flattened fields. 

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

657 request = pubsub.Subscription(request) 

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

659 # request, apply these. 

660 if name is not None: 

661 request.name = name 

662 if topic is not None: 

663 request.topic = topic 

664 if push_config is not None: 

665 request.push_config = push_config 

666 if ack_deadline_seconds is not None: 

667 request.ack_deadline_seconds = ack_deadline_seconds 

668 

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

670 # and friendly error handling. 

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

672 

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

674 # add these here. 

675 metadata = tuple(metadata) + ( 

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

677 ) 

678 

679 # Send the request. 

680 response = rpc( 

681 request, 

682 retry=retry, 

683 timeout=timeout, 

684 metadata=metadata, 

685 ) 

686 

687 # Done; return the response. 

688 return response 

689 

690 def get_subscription( 

691 self, 

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

693 *, 

694 subscription: Optional[str] = None, 

695 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

697 metadata: Sequence[Tuple[str, str]] = (), 

698 ) -> pubsub.Subscription: 

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

700 

701 .. code-block:: python 

702 

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

704 # code template only. 

705 # It will require modifications to work: 

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

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

708 # client as shown in: 

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

710 from google import pubsub_v1 

711 

712 def sample_get_subscription(): 

713 # Create a client 

714 client = pubsub_v1.SubscriberClient() 

715 

716 # Initialize request argument(s) 

717 request = pubsub_v1.GetSubscriptionRequest( 

718 subscription="subscription_value", 

719 ) 

720 

721 # Make the request 

722 response = client.get_subscription(request=request) 

723 

724 # Handle the response 

725 print(response) 

726 

727 Args: 

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

729 The request object. Request for the GetSubscription 

730 method. 

731 subscription (str): 

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

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

734 

735 This corresponds to the ``subscription`` field 

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

737 should not be set. 

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

739 should be retried. 

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

741 metadata (Sequence[Tuple[str, str]]): Strings which should be 

742 sent along with the request as metadata. 

743 

744 Returns: 

745 google.pubsub_v1.types.Subscription: 

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

747 cloud_storage_config is set, then the subscriber will 

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

749 of these fields may be set. 

750 

751 """ 

752 # Create or coerce a protobuf request object. 

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

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

755 has_flattened_params = any([subscription]) 

756 if request is not None and has_flattened_params: 

757 raise ValueError( 

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

759 "the individual field arguments should be set." 

760 ) 

761 

762 # Minor optimization to avoid making a copy if the user passes 

763 # in a pubsub.GetSubscriptionRequest. 

764 # There's no risk of modifying the input as we've already verified 

765 # there are no flattened fields. 

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

767 request = pubsub.GetSubscriptionRequest(request) 

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

769 # request, apply these. 

770 if subscription is not None: 

771 request.subscription = subscription 

772 

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

774 # and friendly error handling. 

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

776 

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

778 # add these here. 

779 metadata = tuple(metadata) + ( 

780 gapic_v1.routing_header.to_grpc_metadata( 

781 (("subscription", request.subscription),) 

782 ), 

783 ) 

784 

785 # Send the request. 

786 response = rpc( 

787 request, 

788 retry=retry, 

789 timeout=timeout, 

790 metadata=metadata, 

791 ) 

792 

793 # Done; return the response. 

794 return response 

795 

796 def update_subscription( 

797 self, 

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

799 *, 

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

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

802 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

804 metadata: Sequence[Tuple[str, str]] = (), 

805 ) -> pubsub.Subscription: 

806 r"""Updates an existing subscription. Note that certain 

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

808 modifiable. 

809 

810 .. code-block:: python 

811 

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

813 # code template only. 

814 # It will require modifications to work: 

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

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

817 # client as shown in: 

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

819 from google import pubsub_v1 

820 

821 def sample_update_subscription(): 

822 # Create a client 

823 client = pubsub_v1.SubscriberClient() 

824 

825 # Initialize request argument(s) 

826 subscription = pubsub_v1.Subscription() 

827 subscription.name = "name_value" 

828 subscription.topic = "topic_value" 

829 

830 request = pubsub_v1.UpdateSubscriptionRequest( 

831 subscription=subscription, 

832 ) 

833 

834 # Make the request 

835 response = client.update_subscription(request=request) 

836 

837 # Handle the response 

838 print(response) 

839 

840 Args: 

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

842 The request object. Request for the UpdateSubscription 

843 method. 

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

845 Required. The updated subscription 

846 object. 

847 

848 This corresponds to the ``subscription`` field 

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

850 should not be set. 

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

852 Required. Indicates which fields in 

853 the provided subscription to update. 

854 Must be specified and non-empty. 

855 

856 This corresponds to the ``update_mask`` field 

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

858 should not be set. 

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

860 should be retried. 

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

862 metadata (Sequence[Tuple[str, str]]): Strings which should be 

863 sent along with the request as metadata. 

864 

865 Returns: 

866 google.pubsub_v1.types.Subscription: 

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

868 cloud_storage_config is set, then the subscriber will 

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

870 of these fields may be set. 

871 

872 """ 

873 # Create or coerce a protobuf request object. 

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

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

876 has_flattened_params = any([subscription, update_mask]) 

877 if request is not None and has_flattened_params: 

878 raise ValueError( 

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

880 "the individual field arguments should be set." 

881 ) 

882 

883 # Minor optimization to avoid making a copy if the user passes 

884 # in a pubsub.UpdateSubscriptionRequest. 

885 # There's no risk of modifying the input as we've already verified 

886 # there are no flattened fields. 

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

888 request = pubsub.UpdateSubscriptionRequest(request) 

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

890 # request, apply these. 

891 if subscription is not None: 

892 request.subscription = subscription 

893 if update_mask is not None: 

894 request.update_mask = update_mask 

895 

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

897 # and friendly error handling. 

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

899 

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

901 # add these here. 

902 metadata = tuple(metadata) + ( 

903 gapic_v1.routing_header.to_grpc_metadata( 

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

905 ), 

906 ) 

907 

908 # Send the request. 

909 response = rpc( 

910 request, 

911 retry=retry, 

912 timeout=timeout, 

913 metadata=metadata, 

914 ) 

915 

916 # Done; return the response. 

917 return response 

918 

919 def list_subscriptions( 

920 self, 

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

922 *, 

923 project: Optional[str] = None, 

924 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

926 metadata: Sequence[Tuple[str, str]] = (), 

927 ) -> pagers.ListSubscriptionsPager: 

928 r"""Lists matching subscriptions. 

929 

930 .. code-block:: python 

931 

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

933 # code template only. 

934 # It will require modifications to work: 

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

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

937 # client as shown in: 

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

939 from google import pubsub_v1 

940 

941 def sample_list_subscriptions(): 

942 # Create a client 

943 client = pubsub_v1.SubscriberClient() 

944 

945 # Initialize request argument(s) 

946 request = pubsub_v1.ListSubscriptionsRequest( 

947 project="project_value", 

948 ) 

949 

950 # Make the request 

951 page_result = client.list_subscriptions(request=request) 

952 

953 # Handle the response 

954 for response in page_result: 

955 print(response) 

956 

957 Args: 

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

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

960 project (str): 

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

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

963 

964 This corresponds to the ``project`` field 

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

966 should not be set. 

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

968 should be retried. 

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

970 metadata (Sequence[Tuple[str, str]]): Strings which should be 

971 sent along with the request as metadata. 

972 

973 Returns: 

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

975 Response for the ListSubscriptions method. 

976 

977 Iterating over this object will yield results and 

978 resolve additional pages automatically. 

979 

980 """ 

981 # Create or coerce a protobuf request object. 

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

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

984 has_flattened_params = any([project]) 

985 if request is not None and has_flattened_params: 

986 raise ValueError( 

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

988 "the individual field arguments should be set." 

989 ) 

990 

991 # Minor optimization to avoid making a copy if the user passes 

992 # in a pubsub.ListSubscriptionsRequest. 

993 # There's no risk of modifying the input as we've already verified 

994 # there are no flattened fields. 

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

996 request = pubsub.ListSubscriptionsRequest(request) 

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

998 # request, apply these. 

999 if project is not None: 

1000 request.project = project 

1001 

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

1003 # and friendly error handling. 

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

1005 

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

1007 # add these here. 

1008 metadata = tuple(metadata) + ( 

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

1010 ) 

1011 

1012 # Send the request. 

1013 response = rpc( 

1014 request, 

1015 retry=retry, 

1016 timeout=timeout, 

1017 metadata=metadata, 

1018 ) 

1019 

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

1021 # an `__iter__` convenience method. 

1022 response = pagers.ListSubscriptionsPager( 

1023 method=rpc, 

1024 request=request, 

1025 response=response, 

1026 metadata=metadata, 

1027 ) 

1028 

1029 # Done; return the response. 

1030 return response 

1031 

1032 def delete_subscription( 

1033 self, 

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

1035 *, 

1036 subscription: Optional[str] = None, 

1037 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1039 metadata: Sequence[Tuple[str, str]] = (), 

1040 ) -> None: 

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

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

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

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

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

1046 topic unless the same topic is specified. 

1047 

1048 .. code-block:: python 

1049 

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

1051 # code template only. 

1052 # It will require modifications to work: 

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

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

1055 # client as shown in: 

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

1057 from google import pubsub_v1 

1058 

1059 def sample_delete_subscription(): 

1060 # Create a client 

1061 client = pubsub_v1.SubscriberClient() 

1062 

1063 # Initialize request argument(s) 

1064 request = pubsub_v1.DeleteSubscriptionRequest( 

1065 subscription="subscription_value", 

1066 ) 

1067 

1068 # Make the request 

1069 client.delete_subscription(request=request) 

1070 

1071 Args: 

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

1073 The request object. Request for the DeleteSubscription 

1074 method. 

1075 subscription (str): 

1076 Required. The subscription to delete. Format is 

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

1078 

1079 This corresponds to the ``subscription`` field 

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

1081 should not be set. 

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

1083 should be retried. 

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

1085 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1086 sent along with the request as metadata. 

1087 """ 

1088 # Create or coerce a protobuf request object. 

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

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

1091 has_flattened_params = any([subscription]) 

1092 if request is not None and has_flattened_params: 

1093 raise ValueError( 

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

1095 "the individual field arguments should be set." 

1096 ) 

1097 

1098 # Minor optimization to avoid making a copy if the user passes 

1099 # in a pubsub.DeleteSubscriptionRequest. 

1100 # There's no risk of modifying the input as we've already verified 

1101 # there are no flattened fields. 

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

1103 request = pubsub.DeleteSubscriptionRequest(request) 

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

1105 # request, apply these. 

1106 if subscription is not None: 

1107 request.subscription = subscription 

1108 

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

1110 # and friendly error handling. 

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

1112 

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

1114 # add these here. 

1115 metadata = tuple(metadata) + ( 

1116 gapic_v1.routing_header.to_grpc_metadata( 

1117 (("subscription", request.subscription),) 

1118 ), 

1119 ) 

1120 

1121 # Send the request. 

1122 rpc( 

1123 request, 

1124 retry=retry, 

1125 timeout=timeout, 

1126 metadata=metadata, 

1127 ) 

1128 

1129 def modify_ack_deadline( 

1130 self, 

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

1132 *, 

1133 subscription: Optional[str] = None, 

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

1135 ack_deadline_seconds: Optional[int] = None, 

1136 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1138 metadata: Sequence[Tuple[str, str]] = (), 

1139 ) -> None: 

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

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

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

1143 redelivery if the processing was interrupted. Note that this 

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

1145 used for subsequent messages. 

1146 

1147 .. code-block:: python 

1148 

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

1150 # code template only. 

1151 # It will require modifications to work: 

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

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

1154 # client as shown in: 

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

1156 from google import pubsub_v1 

1157 

1158 def sample_modify_ack_deadline(): 

1159 # Create a client 

1160 client = pubsub_v1.SubscriberClient() 

1161 

1162 # Initialize request argument(s) 

1163 request = pubsub_v1.ModifyAckDeadlineRequest( 

1164 subscription="subscription_value", 

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

1166 ack_deadline_seconds=2066, 

1167 ) 

1168 

1169 # Make the request 

1170 client.modify_ack_deadline(request=request) 

1171 

1172 Args: 

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

1174 The request object. Request for the ModifyAckDeadline 

1175 method. 

1176 subscription (str): 

1177 Required. The name of the subscription. Format is 

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

1179 

1180 This corresponds to the ``subscription`` field 

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

1182 should not be set. 

1183 ack_ids (MutableSequence[str]): 

1184 Required. List of acknowledgment IDs. 

1185 This corresponds to the ``ack_ids`` field 

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

1187 should not be set. 

1188 ack_deadline_seconds (int): 

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

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

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

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

1193 was made. Specifying zero might immediately make the 

1194 message available for delivery to another subscriber 

1195 client. This typically results in an increase in the 

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

1197 minimum deadline you can specify is 0 seconds. The 

1198 maximum deadline you can specify is 600 seconds (10 

1199 minutes). 

1200 

1201 This corresponds to the ``ack_deadline_seconds`` field 

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

1203 should not be set. 

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

1205 should be retried. 

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

1207 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1208 sent along with the request as metadata. 

1209 """ 

1210 # Create or coerce a protobuf request object. 

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

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

1213 has_flattened_params = any([subscription, ack_ids, ack_deadline_seconds]) 

1214 if request is not None and has_flattened_params: 

1215 raise ValueError( 

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

1217 "the individual field arguments should be set." 

1218 ) 

1219 

1220 # Minor optimization to avoid making a copy if the user passes 

1221 # in a pubsub.ModifyAckDeadlineRequest. 

1222 # There's no risk of modifying the input as we've already verified 

1223 # there are no flattened fields. 

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

1225 request = pubsub.ModifyAckDeadlineRequest(request) 

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

1227 # request, apply these. 

1228 if subscription is not None: 

1229 request.subscription = subscription 

1230 if ack_ids is not None: 

1231 request.ack_ids = ack_ids 

1232 if ack_deadline_seconds is not None: 

1233 request.ack_deadline_seconds = ack_deadline_seconds 

1234 

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

1236 # and friendly error handling. 

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

1238 

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

1240 # add these here. 

1241 metadata = tuple(metadata) + ( 

1242 gapic_v1.routing_header.to_grpc_metadata( 

1243 (("subscription", request.subscription),) 

1244 ), 

1245 ) 

1246 

1247 # Send the request. 

1248 rpc( 

1249 request, 

1250 retry=retry, 

1251 timeout=timeout, 

1252 metadata=metadata, 

1253 ) 

1254 

1255 def acknowledge( 

1256 self, 

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

1258 *, 

1259 subscription: Optional[str] = None, 

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

1261 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1263 metadata: Sequence[Tuple[str, str]] = (), 

1264 ) -> None: 

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

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

1267 relevant messages from the subscription. 

1268 

1269 Acknowledging a message whose ack deadline has expired may 

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

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

1272 error. 

1273 

1274 .. code-block:: python 

1275 

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

1277 # code template only. 

1278 # It will require modifications to work: 

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

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

1281 # client as shown in: 

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

1283 from google import pubsub_v1 

1284 

1285 def sample_acknowledge(): 

1286 # Create a client 

1287 client = pubsub_v1.SubscriberClient() 

1288 

1289 # Initialize request argument(s) 

1290 request = pubsub_v1.AcknowledgeRequest( 

1291 subscription="subscription_value", 

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

1293 ) 

1294 

1295 # Make the request 

1296 client.acknowledge(request=request) 

1297 

1298 Args: 

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

1300 The request object. Request for the Acknowledge method. 

1301 subscription (str): 

1302 Required. The subscription whose message is being 

1303 acknowledged. Format is 

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

1305 

1306 This corresponds to the ``subscription`` field 

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

1308 should not be set. 

1309 ack_ids (MutableSequence[str]): 

1310 Required. The acknowledgment ID for the messages being 

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

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

1313 

1314 This corresponds to the ``ack_ids`` field 

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

1316 should not be set. 

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

1318 should be retried. 

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

1320 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1321 sent along with the request as metadata. 

1322 """ 

1323 # Create or coerce a protobuf request object. 

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

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

1326 has_flattened_params = any([subscription, ack_ids]) 

1327 if request is not None and has_flattened_params: 

1328 raise ValueError( 

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

1330 "the individual field arguments should be set." 

1331 ) 

1332 

1333 # Minor optimization to avoid making a copy if the user passes 

1334 # in a pubsub.AcknowledgeRequest. 

1335 # There's no risk of modifying the input as we've already verified 

1336 # there are no flattened fields. 

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

1338 request = pubsub.AcknowledgeRequest(request) 

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

1340 # request, apply these. 

1341 if subscription is not None: 

1342 request.subscription = subscription 

1343 if ack_ids is not None: 

1344 request.ack_ids = ack_ids 

1345 

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

1347 # and friendly error handling. 

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

1349 

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

1351 # add these here. 

1352 metadata = tuple(metadata) + ( 

1353 gapic_v1.routing_header.to_grpc_metadata( 

1354 (("subscription", request.subscription),) 

1355 ), 

1356 ) 

1357 

1358 # Send the request. 

1359 rpc( 

1360 request, 

1361 retry=retry, 

1362 timeout=timeout, 

1363 metadata=metadata, 

1364 ) 

1365 

1366 def pull( 

1367 self, 

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

1369 *, 

1370 subscription: Optional[str] = None, 

1371 return_immediately: Optional[bool] = None, 

1372 max_messages: Optional[int] = None, 

1373 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1375 metadata: Sequence[Tuple[str, str]] = (), 

1376 ) -> pubsub.PullResponse: 

1377 r"""Pulls messages from the server. 

1378 

1379 .. code-block:: python 

1380 

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

1382 # code template only. 

1383 # It will require modifications to work: 

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

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

1386 # client as shown in: 

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

1388 from google import pubsub_v1 

1389 

1390 def sample_pull(): 

1391 # Create a client 

1392 client = pubsub_v1.SubscriberClient() 

1393 

1394 # Initialize request argument(s) 

1395 request = pubsub_v1.PullRequest( 

1396 subscription="subscription_value", 

1397 max_messages=1277, 

1398 ) 

1399 

1400 # Make the request 

1401 response = client.pull(request=request) 

1402 

1403 # Handle the response 

1404 print(response) 

1405 

1406 Args: 

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

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

1409 subscription (str): 

1410 Required. The subscription from which messages should be 

1411 pulled. Format is 

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

1413 

1414 This corresponds to the ``subscription`` field 

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

1416 should not be set. 

1417 return_immediately (bool): 

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

1419 respond immediately even if it there are no messages 

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

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

1422 at least one message is available, rather than returning 

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

1424 discouraged because it adversely impacts the performance 

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

1426 set this field. 

1427 

1428 This corresponds to the ``return_immediately`` field 

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

1430 should not be set. 

1431 max_messages (int): 

1432 Required. The maximum number of 

1433 messages to return for this request. 

1434 Must be a positive integer. The Pub/Sub 

1435 system may return fewer than the number 

1436 specified. 

1437 

1438 This corresponds to the ``max_messages`` field 

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

1440 should not be set. 

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

1442 should be retried. 

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

1444 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1445 sent along with the request as metadata. 

1446 

1447 Returns: 

1448 google.pubsub_v1.types.PullResponse: 

1449 Response for the Pull method. 

1450 """ 

1451 # Create or coerce a protobuf request object. 

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

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

1454 has_flattened_params = any([subscription, return_immediately, max_messages]) 

1455 if request is not None and has_flattened_params: 

1456 raise ValueError( 

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

1458 "the individual field arguments should be set." 

1459 ) 

1460 

1461 # Minor optimization to avoid making a copy if the user passes 

1462 # in a pubsub.PullRequest. 

1463 # There's no risk of modifying the input as we've already verified 

1464 # there are no flattened fields. 

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

1466 request = pubsub.PullRequest(request) 

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

1468 # request, apply these. 

1469 if subscription is not None: 

1470 request.subscription = subscription 

1471 if return_immediately is not None: 

1472 request.return_immediately = return_immediately 

1473 if max_messages is not None: 

1474 request.max_messages = max_messages 

1475 

1476 if request.return_immediately: 

1477 warnings.warn( 

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

1479 category=DeprecationWarning, 

1480 ) 

1481 

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

1483 # and friendly error handling. 

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

1485 

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

1487 # add these here. 

1488 metadata = tuple(metadata) + ( 

1489 gapic_v1.routing_header.to_grpc_metadata( 

1490 (("subscription", request.subscription),) 

1491 ), 

1492 ) 

1493 

1494 # Send the request. 

1495 response = rpc( 

1496 request, 

1497 retry=retry, 

1498 timeout=timeout, 

1499 metadata=metadata, 

1500 ) 

1501 

1502 # Done; return the response. 

1503 return response 

1504 

1505 def streaming_pull( 

1506 self, 

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

1508 *, 

1509 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1511 metadata: Sequence[Tuple[str, str]] = (), 

1512 ) -> Iterable[pubsub.StreamingPullResponse]: 

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

1514 to the client. The client streams acknowledgements and ack 

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

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

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

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

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

1520 configuring the underlying RPC channel. 

1521 

1522 .. code-block:: python 

1523 

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

1525 # code template only. 

1526 # It will require modifications to work: 

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

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

1529 # client as shown in: 

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

1531 from google import pubsub_v1 

1532 

1533 def sample_streaming_pull(): 

1534 # Create a client 

1535 client = pubsub_v1.SubscriberClient() 

1536 

1537 # Initialize request argument(s) 

1538 request = pubsub_v1.StreamingPullRequest( 

1539 subscription="subscription_value", 

1540 stream_ack_deadline_seconds=2813, 

1541 ) 

1542 

1543 # This method expects an iterator which contains 

1544 # 'pubsub_v1.StreamingPullRequest' objects 

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

1546 # demonstrative purposes. 

1547 requests = [request] 

1548 

1549 def request_generator(): 

1550 for request in requests: 

1551 yield request 

1552 

1553 # Make the request 

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

1555 

1556 # Handle the response 

1557 for response in stream: 

1558 print(response) 

1559 

1560 Args: 

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

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

1563 This request is used to establish the initial stream as 

1564 well as to stream acknowledgements and ack deadline 

1565 modifications from the client to the server. 

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

1567 should be retried. 

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

1569 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1570 sent along with the request as metadata. 

1571 

1572 Returns: 

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

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

1575 messages from the server to the client. 

1576 

1577 """ 

1578 

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

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

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

1582 self._transport.streaming_pull._prefetch_first_result_ = False 

1583 

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

1585 # and friendly error handling. 

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

1587 

1588 # Send the request. 

1589 response = rpc( 

1590 requests, 

1591 retry=retry, 

1592 timeout=timeout, 

1593 metadata=metadata, 

1594 ) 

1595 

1596 # Done; return the response. 

1597 return response 

1598 

1599 def modify_push_config( 

1600 self, 

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

1602 *, 

1603 subscription: Optional[str] = None, 

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

1605 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1607 metadata: Sequence[Tuple[str, str]] = (), 

1608 ) -> None: 

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

1610 

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

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

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

1614 Messages will accumulate for delivery continuously through the 

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

1616 

1617 .. code-block:: python 

1618 

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

1620 # code template only. 

1621 # It will require modifications to work: 

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

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

1624 # client as shown in: 

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

1626 from google import pubsub_v1 

1627 

1628 def sample_modify_push_config(): 

1629 # Create a client 

1630 client = pubsub_v1.SubscriberClient() 

1631 

1632 # Initialize request argument(s) 

1633 request = pubsub_v1.ModifyPushConfigRequest( 

1634 subscription="subscription_value", 

1635 ) 

1636 

1637 # Make the request 

1638 client.modify_push_config(request=request) 

1639 

1640 Args: 

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

1642 The request object. Request for the ModifyPushConfig 

1643 method. 

1644 subscription (str): 

1645 Required. The name of the subscription. Format is 

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

1647 

1648 This corresponds to the ``subscription`` field 

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

1650 should not be set. 

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

1652 Required. The push configuration for future deliveries. 

1653 

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

1655 system should stop pushing messages from the given 

1656 subscription and allow messages to be pulled and 

1657 acknowledged - effectively pausing the subscription if 

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

1659 

1660 This corresponds to the ``push_config`` field 

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

1662 should not be set. 

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

1664 should be retried. 

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

1666 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1667 sent along with the request as metadata. 

1668 """ 

1669 # Create or coerce a protobuf request object. 

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

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

1672 has_flattened_params = any([subscription, push_config]) 

1673 if request is not None and has_flattened_params: 

1674 raise ValueError( 

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

1676 "the individual field arguments should be set." 

1677 ) 

1678 

1679 # Minor optimization to avoid making a copy if the user passes 

1680 # in a pubsub.ModifyPushConfigRequest. 

1681 # There's no risk of modifying the input as we've already verified 

1682 # there are no flattened fields. 

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

1684 request = pubsub.ModifyPushConfigRequest(request) 

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

1686 # request, apply these. 

1687 if subscription is not None: 

1688 request.subscription = subscription 

1689 if push_config is not None: 

1690 request.push_config = push_config 

1691 

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

1693 # and friendly error handling. 

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

1695 

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

1697 # add these here. 

1698 metadata = tuple(metadata) + ( 

1699 gapic_v1.routing_header.to_grpc_metadata( 

1700 (("subscription", request.subscription),) 

1701 ), 

1702 ) 

1703 

1704 # Send the request. 

1705 rpc( 

1706 request, 

1707 retry=retry, 

1708 timeout=timeout, 

1709 metadata=metadata, 

1710 ) 

1711 

1712 def get_snapshot( 

1713 self, 

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

1715 *, 

1716 snapshot: Optional[str] = None, 

1717 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1719 metadata: Sequence[Tuple[str, str]] = (), 

1720 ) -> pubsub.Snapshot: 

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

1722 in 

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

1724 operations, which allow you to manage message acknowledgments in 

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

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

1727 

1728 .. code-block:: python 

1729 

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

1731 # code template only. 

1732 # It will require modifications to work: 

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

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

1735 # client as shown in: 

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

1737 from google import pubsub_v1 

1738 

1739 def sample_get_snapshot(): 

1740 # Create a client 

1741 client = pubsub_v1.SubscriberClient() 

1742 

1743 # Initialize request argument(s) 

1744 request = pubsub_v1.GetSnapshotRequest( 

1745 snapshot="snapshot_value", 

1746 ) 

1747 

1748 # Make the request 

1749 response = client.get_snapshot(request=request) 

1750 

1751 # Handle the response 

1752 print(response) 

1753 

1754 Args: 

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

1756 The request object. Request for the GetSnapshot method. 

1757 snapshot (str): 

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

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

1760 

1761 This corresponds to the ``snapshot`` field 

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

1763 should not be set. 

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

1765 should be retried. 

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

1767 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1768 sent along with the request as metadata. 

1769 

1770 Returns: 

1771 google.pubsub_v1.types.Snapshot: 

1772 A snapshot resource. Snapshots are used in 

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

1774 operations, which allow you to manage message 

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

1776 acknowledgment state of messages in an existing 

1777 subscription to the state captured by a snapshot. 

1778 

1779 """ 

1780 # Create or coerce a protobuf request object. 

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

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

1783 has_flattened_params = any([snapshot]) 

1784 if request is not None and has_flattened_params: 

1785 raise ValueError( 

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

1787 "the individual field arguments should be set." 

1788 ) 

1789 

1790 # Minor optimization to avoid making a copy if the user passes 

1791 # in a pubsub.GetSnapshotRequest. 

1792 # There's no risk of modifying the input as we've already verified 

1793 # there are no flattened fields. 

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

1795 request = pubsub.GetSnapshotRequest(request) 

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

1797 # request, apply these. 

1798 if snapshot is not None: 

1799 request.snapshot = snapshot 

1800 

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

1802 # and friendly error handling. 

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

1804 

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

1806 # add these here. 

1807 metadata = tuple(metadata) + ( 

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

1809 ) 

1810 

1811 # Send the request. 

1812 response = rpc( 

1813 request, 

1814 retry=retry, 

1815 timeout=timeout, 

1816 metadata=metadata, 

1817 ) 

1818 

1819 # Done; return the response. 

1820 return response 

1821 

1822 def list_snapshots( 

1823 self, 

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

1825 *, 

1826 project: Optional[str] = None, 

1827 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1829 metadata: Sequence[Tuple[str, str]] = (), 

1830 ) -> pagers.ListSnapshotsPager: 

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

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

1833 operations, which allow you to manage message acknowledgments in 

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

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

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_list_snapshots(): 

1849 # Create a client 

1850 client = pubsub_v1.SubscriberClient() 

1851 

1852 # Initialize request argument(s) 

1853 request = pubsub_v1.ListSnapshotsRequest( 

1854 project="project_value", 

1855 ) 

1856 

1857 # Make the request 

1858 page_result = client.list_snapshots(request=request) 

1859 

1860 # Handle the response 

1861 for response in page_result: 

1862 print(response) 

1863 

1864 Args: 

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

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

1867 project (str): 

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

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

1870 

1871 This corresponds to the ``project`` field 

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

1873 should not be set. 

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

1875 should be retried. 

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

1877 metadata (Sequence[Tuple[str, str]]): Strings which should be 

1878 sent along with the request as metadata. 

1879 

1880 Returns: 

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

1882 Response for the ListSnapshots method. 

1883 

1884 Iterating over this object will yield results and 

1885 resolve additional pages automatically. 

1886 

1887 """ 

1888 # Create or coerce a protobuf request object. 

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

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

1891 has_flattened_params = any([project]) 

1892 if request is not None and has_flattened_params: 

1893 raise ValueError( 

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

1895 "the individual field arguments should be set." 

1896 ) 

1897 

1898 # Minor optimization to avoid making a copy if the user passes 

1899 # in a pubsub.ListSnapshotsRequest. 

1900 # There's no risk of modifying the input as we've already verified 

1901 # there are no flattened fields. 

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

1903 request = pubsub.ListSnapshotsRequest(request) 

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

1905 # request, apply these. 

1906 if project is not None: 

1907 request.project = project 

1908 

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

1910 # and friendly error handling. 

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

1912 

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

1914 # add these here. 

1915 metadata = tuple(metadata) + ( 

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

1917 ) 

1918 

1919 # Send the request. 

1920 response = rpc( 

1921 request, 

1922 retry=retry, 

1923 timeout=timeout, 

1924 metadata=metadata, 

1925 ) 

1926 

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

1928 # an `__iter__` convenience method. 

1929 response = pagers.ListSnapshotsPager( 

1930 method=rpc, 

1931 request=request, 

1932 response=response, 

1933 metadata=metadata, 

1934 ) 

1935 

1936 # Done; return the response. 

1937 return response 

1938 

1939 def create_snapshot( 

1940 self, 

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

1942 *, 

1943 name: Optional[str] = None, 

1944 subscription: Optional[str] = None, 

1945 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

1947 metadata: Sequence[Tuple[str, str]] = (), 

1948 ) -> pubsub.Snapshot: 

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

1950 are used in 

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

1952 operations, which allow you to manage message acknowledgments in 

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

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

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

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

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

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

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

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

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

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

1963 the [resource name format] 

1964 (https://cloud.google.com/pubsub/docs/admin#resource_names). The 

1965 generated name is populated in the returned Snapshot object. 

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

1967 request. 

1968 

1969 .. code-block:: python 

1970 

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

1972 # code template only. 

1973 # It will require modifications to work: 

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

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

1976 # client as shown in: 

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

1978 from google import pubsub_v1 

1979 

1980 def sample_create_snapshot(): 

1981 # Create a client 

1982 client = pubsub_v1.SubscriberClient() 

1983 

1984 # Initialize request argument(s) 

1985 request = pubsub_v1.CreateSnapshotRequest( 

1986 name="name_value", 

1987 subscription="subscription_value", 

1988 ) 

1989 

1990 # Make the request 

1991 response = client.create_snapshot(request=request) 

1992 

1993 # Handle the response 

1994 print(response) 

1995 

1996 Args: 

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

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

1999 name (str): 

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

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

2002 assign a random name for this snapshot on the same 

2003 project as the subscription. Note that for REST API 

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

2005 name 

2006 rules <https://cloud.google.com/pubsub/docs/admin#resource_names>`__. 

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

2008 

2009 This corresponds to the ``name`` field 

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

2011 should not be set. 

2012 subscription (str): 

2013 Required. The subscription whose backlog the snapshot 

2014 retains. Specifically, the created snapshot is 

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

2016 subscription. More precisely, this is defined as the 

2017 messages in the subscription's backlog that are 

2018 unacknowledged upon the successful completion of the 

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

2020 published to the subscription's topic following the 

2021 successful completion of the CreateSnapshot request. 

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

2023 

2024 This corresponds to the ``subscription`` field 

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

2026 should not be set. 

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

2028 should be retried. 

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

2030 metadata (Sequence[Tuple[str, str]]): Strings which should be 

2031 sent along with the request as metadata. 

2032 

2033 Returns: 

2034 google.pubsub_v1.types.Snapshot: 

2035 A snapshot resource. Snapshots are used in 

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

2037 operations, which allow you to manage message 

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

2039 acknowledgment state of messages in an existing 

2040 subscription to the state captured by a snapshot. 

2041 

2042 """ 

2043 # Create or coerce a protobuf request object. 

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

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

2046 has_flattened_params = any([name, subscription]) 

2047 if request is not None and has_flattened_params: 

2048 raise ValueError( 

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

2050 "the individual field arguments should be set." 

2051 ) 

2052 

2053 # Minor optimization to avoid making a copy if the user passes 

2054 # in a pubsub.CreateSnapshotRequest. 

2055 # There's no risk of modifying the input as we've already verified 

2056 # there are no flattened fields. 

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

2058 request = pubsub.CreateSnapshotRequest(request) 

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

2060 # request, apply these. 

2061 if name is not None: 

2062 request.name = name 

2063 if subscription is not None: 

2064 request.subscription = subscription 

2065 

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

2067 # and friendly error handling. 

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

2069 

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

2071 # add these here. 

2072 metadata = tuple(metadata) + ( 

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

2074 ) 

2075 

2076 # Send the request. 

2077 response = rpc( 

2078 request, 

2079 retry=retry, 

2080 timeout=timeout, 

2081 metadata=metadata, 

2082 ) 

2083 

2084 # Done; return the response. 

2085 return response 

2086 

2087 def update_snapshot( 

2088 self, 

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

2090 *, 

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

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

2093 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

2095 metadata: Sequence[Tuple[str, str]] = (), 

2096 ) -> pubsub.Snapshot: 

2097 r"""Updates an existing snapshot. Snapshots are used in 

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

2099 operations, which allow you to manage message acknowledgments in 

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

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

2102 

2103 .. code-block:: python 

2104 

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

2106 # code template only. 

2107 # It will require modifications to work: 

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

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

2110 # client as shown in: 

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

2112 from google import pubsub_v1 

2113 

2114 def sample_update_snapshot(): 

2115 # Create a client 

2116 client = pubsub_v1.SubscriberClient() 

2117 

2118 # Initialize request argument(s) 

2119 request = pubsub_v1.UpdateSnapshotRequest( 

2120 ) 

2121 

2122 # Make the request 

2123 response = client.update_snapshot(request=request) 

2124 

2125 # Handle the response 

2126 print(response) 

2127 

2128 Args: 

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

2130 The request object. Request for the UpdateSnapshot 

2131 method. 

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

2133 Required. The updated snapshot 

2134 object. 

2135 

2136 This corresponds to the ``snapshot`` field 

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

2138 should not be set. 

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

2140 Required. Indicates which fields in 

2141 the provided snapshot to update. Must be 

2142 specified and non-empty. 

2143 

2144 This corresponds to the ``update_mask`` field 

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

2146 should not be set. 

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

2148 should be retried. 

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

2150 metadata (Sequence[Tuple[str, str]]): Strings which should be 

2151 sent along with the request as metadata. 

2152 

2153 Returns: 

2154 google.pubsub_v1.types.Snapshot: 

2155 A snapshot resource. Snapshots are used in 

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

2157 operations, which allow you to manage message 

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

2159 acknowledgment state of messages in an existing 

2160 subscription to the state captured by a snapshot. 

2161 

2162 """ 

2163 # Create or coerce a protobuf request object. 

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

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

2166 has_flattened_params = any([snapshot, update_mask]) 

2167 if request is not None and has_flattened_params: 

2168 raise ValueError( 

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

2170 "the individual field arguments should be set." 

2171 ) 

2172 

2173 # Minor optimization to avoid making a copy if the user passes 

2174 # in a pubsub.UpdateSnapshotRequest. 

2175 # There's no risk of modifying the input as we've already verified 

2176 # there are no flattened fields. 

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

2178 request = pubsub.UpdateSnapshotRequest(request) 

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

2180 # request, apply these. 

2181 if snapshot is not None: 

2182 request.snapshot = snapshot 

2183 if update_mask is not None: 

2184 request.update_mask = update_mask 

2185 

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

2187 # and friendly error handling. 

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

2189 

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

2191 # add these here. 

2192 metadata = tuple(metadata) + ( 

2193 gapic_v1.routing_header.to_grpc_metadata( 

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

2195 ), 

2196 ) 

2197 

2198 # Send the request. 

2199 response = rpc( 

2200 request, 

2201 retry=retry, 

2202 timeout=timeout, 

2203 metadata=metadata, 

2204 ) 

2205 

2206 # Done; return the response. 

2207 return response 

2208 

2209 def delete_snapshot( 

2210 self, 

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

2212 *, 

2213 snapshot: Optional[str] = None, 

2214 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

2216 metadata: Sequence[Tuple[str, str]] = (), 

2217 ) -> None: 

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

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

2220 operations, which allow you to manage message acknowledgments in 

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

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

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

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

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

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

2227 the same subscription is specified. 

2228 

2229 .. code-block:: python 

2230 

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

2232 # code template only. 

2233 # It will require modifications to work: 

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

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

2236 # client as shown in: 

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

2238 from google import pubsub_v1 

2239 

2240 def sample_delete_snapshot(): 

2241 # Create a client 

2242 client = pubsub_v1.SubscriberClient() 

2243 

2244 # Initialize request argument(s) 

2245 request = pubsub_v1.DeleteSnapshotRequest( 

2246 snapshot="snapshot_value", 

2247 ) 

2248 

2249 # Make the request 

2250 client.delete_snapshot(request=request) 

2251 

2252 Args: 

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

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

2255 snapshot (str): 

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

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

2258 

2259 This corresponds to the ``snapshot`` field 

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

2261 should not be set. 

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

2263 should be retried. 

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

2265 metadata (Sequence[Tuple[str, str]]): Strings which should be 

2266 sent along with the request as metadata. 

2267 """ 

2268 # Create or coerce a protobuf request object. 

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

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

2271 has_flattened_params = any([snapshot]) 

2272 if request is not None and has_flattened_params: 

2273 raise ValueError( 

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

2275 "the individual field arguments should be set." 

2276 ) 

2277 

2278 # Minor optimization to avoid making a copy if the user passes 

2279 # in a pubsub.DeleteSnapshotRequest. 

2280 # There's no risk of modifying the input as we've already verified 

2281 # there are no flattened fields. 

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

2283 request = pubsub.DeleteSnapshotRequest(request) 

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

2285 # request, apply these. 

2286 if snapshot is not None: 

2287 request.snapshot = snapshot 

2288 

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

2290 # and friendly error handling. 

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

2292 

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

2294 # add these here. 

2295 metadata = tuple(metadata) + ( 

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

2297 ) 

2298 

2299 # Send the request. 

2300 rpc( 

2301 request, 

2302 retry=retry, 

2303 timeout=timeout, 

2304 metadata=metadata, 

2305 ) 

2306 

2307 def seek( 

2308 self, 

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

2310 *, 

2311 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

2313 metadata: Sequence[Tuple[str, str]] = (), 

2314 ) -> pubsub.SeekResponse: 

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

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

2317 used in [Seek] 

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

2319 operations, which allow you to manage message acknowledgments in 

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

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

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

2323 same topic. 

2324 

2325 .. code-block:: python 

2326 

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

2328 # code template only. 

2329 # It will require modifications to work: 

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

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

2332 # client as shown in: 

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

2334 from google import pubsub_v1 

2335 

2336 def sample_seek(): 

2337 # Create a client 

2338 client = pubsub_v1.SubscriberClient() 

2339 

2340 # Initialize request argument(s) 

2341 request = pubsub_v1.SeekRequest( 

2342 subscription="subscription_value", 

2343 ) 

2344 

2345 # Make the request 

2346 response = client.seek(request=request) 

2347 

2348 # Handle the response 

2349 print(response) 

2350 

2351 Args: 

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

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

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

2355 should be retried. 

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

2357 metadata (Sequence[Tuple[str, str]]): Strings which should be 

2358 sent along with the request as metadata. 

2359 

2360 Returns: 

2361 google.pubsub_v1.types.SeekResponse: 

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

2363 """ 

2364 # Create or coerce a protobuf request object. 

2365 # Minor optimization to avoid making a copy if the user passes 

2366 # in a pubsub.SeekRequest. 

2367 # There's no risk of modifying the input as we've already verified 

2368 # there are no flattened fields. 

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

2370 request = pubsub.SeekRequest(request) 

2371 

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

2373 # and friendly error handling. 

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

2375 

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

2377 # add these here. 

2378 metadata = tuple(metadata) + ( 

2379 gapic_v1.routing_header.to_grpc_metadata( 

2380 (("subscription", request.subscription),) 

2381 ), 

2382 ) 

2383 

2384 # Send the request. 

2385 response = rpc( 

2386 request, 

2387 retry=retry, 

2388 timeout=timeout, 

2389 metadata=metadata, 

2390 ) 

2391 

2392 # Done; return the response. 

2393 return response 

2394 

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

2396 return self 

2397 

2398 def __exit__(self, type, value, traceback): 

2399 """Releases underlying transport's resources. 

2400 

2401 .. warning:: 

2402 ONLY use as a context manager if the transport is NOT shared 

2403 with other clients! Exiting the with block will CLOSE the transport 

2404 and may cause errors in other clients! 

2405 """ 

2406 self.transport.close() 

2407 

2408 def set_iam_policy( 

2409 self, 

2410 request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None, 

2411 *, 

2412 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

2414 metadata: Sequence[Tuple[str, str]] = (), 

2415 ) -> policy_pb2.Policy: 

2416 r"""Sets the IAM access control policy on the specified function. 

2417 

2418 Replaces any existing policy. 

2419 

2420 Args: 

2421 request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`): 

2422 The request object. Request message for `SetIamPolicy` 

2423 method. 

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

2425 should be retried. 

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

2427 metadata (Sequence[Tuple[str, str]]): Strings which should be 

2428 sent along with the request as metadata. 

2429 Returns: 

2430 ~.policy_pb2.Policy: 

2431 Defines an Identity and Access Management (IAM) policy. 

2432 It is used to specify access control policies for Cloud 

2433 Platform resources. 

2434 A ``Policy`` is a collection of ``bindings``. A 

2435 ``binding`` binds one or more ``members`` to a single 

2436 ``role``. Members can be user accounts, service 

2437 accounts, Google groups, and domains (such as G Suite). 

2438 A ``role`` is a named list of permissions (defined by 

2439 IAM or configured by users). A ``binding`` can 

2440 optionally specify a ``condition``, which is a logic 

2441 expression that further constrains the role binding 

2442 based on attributes about the request and/or target 

2443 resource. 

2444 

2445 **JSON Example** 

2446 

2447 :: 

2448 

2449 { 

2450 "bindings": [ 

2451 { 

2452 "role": "roles/resourcemanager.organizationAdmin", 

2453 "members": [ 

2454 "user:mike@example.com", 

2455 "group:admins@example.com", 

2456 "domain:google.com", 

2457 "serviceAccount:my-project-id@appspot.gserviceaccount.com" 

2458 ] 

2459 }, 

2460 { 

2461 "role": "roles/resourcemanager.organizationViewer", 

2462 "members": ["user:eve@example.com"], 

2463 "condition": { 

2464 "title": "expirable access", 

2465 "description": "Does not grant access after Sep 2020", 

2466 "expression": "request.time < 

2467 timestamp('2020-10-01T00:00:00.000Z')", 

2468 } 

2469 } 

2470 ] 

2471 } 

2472 

2473 **YAML Example** 

2474 

2475 :: 

2476 

2477 bindings: 

2478 - members: 

2479 - user:mike@example.com 

2480 - group:admins@example.com 

2481 - domain:google.com 

2482 - serviceAccount:my-project-id@appspot.gserviceaccount.com 

2483 role: roles/resourcemanager.organizationAdmin 

2484 - members: 

2485 - user:eve@example.com 

2486 role: roles/resourcemanager.organizationViewer 

2487 condition: 

2488 title: expirable access 

2489 description: Does not grant access after Sep 2020 

2490 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') 

2491 

2492 For a description of IAM and its features, see the `IAM 

2493 developer's 

2494 guide <https://cloud.google.com/iam/docs>`__. 

2495 """ 

2496 # Create or coerce a protobuf request object. 

2497 

2498 # The request isn't a proto-plus wrapped type, 

2499 # so it must be constructed via keyword expansion. 

2500 if isinstance(request, dict): 

2501 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

2502 

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

2504 # and friendly error handling. 

2505 rpc = gapic_v1.method.wrap_method( 

2506 self._transport.set_iam_policy, 

2507 default_timeout=None, 

2508 client_info=DEFAULT_CLIENT_INFO, 

2509 ) 

2510 

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

2512 # add these here. 

2513 metadata = tuple(metadata) + ( 

2514 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

2515 ) 

2516 

2517 # Send the request. 

2518 response = rpc( 

2519 request, 

2520 retry=retry, 

2521 timeout=timeout, 

2522 metadata=metadata, 

2523 ) 

2524 

2525 # Done; return the response. 

2526 return response 

2527 

2528 def get_iam_policy( 

2529 self, 

2530 request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None, 

2531 *, 

2532 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

2534 metadata: Sequence[Tuple[str, str]] = (), 

2535 ) -> policy_pb2.Policy: 

2536 r"""Gets the IAM access control policy for a function. 

2537 

2538 Returns an empty policy if the function exists and does not have a 

2539 policy set. 

2540 

2541 Args: 

2542 request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`): 

2543 The request object. Request message for `GetIamPolicy` 

2544 method. 

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

2546 any, should be retried. 

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

2548 metadata (Sequence[Tuple[str, str]]): Strings which should be 

2549 sent along with the request as metadata. 

2550 Returns: 

2551 ~.policy_pb2.Policy: 

2552 Defines an Identity and Access Management (IAM) policy. 

2553 It is used to specify access control policies for Cloud 

2554 Platform resources. 

2555 A ``Policy`` is a collection of ``bindings``. A 

2556 ``binding`` binds one or more ``members`` to a single 

2557 ``role``. Members can be user accounts, service 

2558 accounts, Google groups, and domains (such as G Suite). 

2559 A ``role`` is a named list of permissions (defined by 

2560 IAM or configured by users). A ``binding`` can 

2561 optionally specify a ``condition``, which is a logic 

2562 expression that further constrains the role binding 

2563 based on attributes about the request and/or target 

2564 resource. 

2565 

2566 **JSON Example** 

2567 

2568 :: 

2569 

2570 { 

2571 "bindings": [ 

2572 { 

2573 "role": "roles/resourcemanager.organizationAdmin", 

2574 "members": [ 

2575 "user:mike@example.com", 

2576 "group:admins@example.com", 

2577 "domain:google.com", 

2578 "serviceAccount:my-project-id@appspot.gserviceaccount.com" 

2579 ] 

2580 }, 

2581 { 

2582 "role": "roles/resourcemanager.organizationViewer", 

2583 "members": ["user:eve@example.com"], 

2584 "condition": { 

2585 "title": "expirable access", 

2586 "description": "Does not grant access after Sep 2020", 

2587 "expression": "request.time < 

2588 timestamp('2020-10-01T00:00:00.000Z')", 

2589 } 

2590 } 

2591 ] 

2592 } 

2593 

2594 **YAML Example** 

2595 

2596 :: 

2597 

2598 bindings: 

2599 - members: 

2600 - user:mike@example.com 

2601 - group:admins@example.com 

2602 - domain:google.com 

2603 - serviceAccount:my-project-id@appspot.gserviceaccount.com 

2604 role: roles/resourcemanager.organizationAdmin 

2605 - members: 

2606 - user:eve@example.com 

2607 role: roles/resourcemanager.organizationViewer 

2608 condition: 

2609 title: expirable access 

2610 description: Does not grant access after Sep 2020 

2611 expression: request.time < timestamp('2020-10-01T00:00:00.000Z') 

2612 

2613 For a description of IAM and its features, see the `IAM 

2614 developer's 

2615 guide <https://cloud.google.com/iam/docs>`__. 

2616 """ 

2617 # Create or coerce a protobuf request object. 

2618 

2619 # The request isn't a proto-plus wrapped type, 

2620 # so it must be constructed via keyword expansion. 

2621 if isinstance(request, dict): 

2622 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

2623 

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

2625 # and friendly error handling. 

2626 rpc = gapic_v1.method.wrap_method( 

2627 self._transport.get_iam_policy, 

2628 default_timeout=None, 

2629 client_info=DEFAULT_CLIENT_INFO, 

2630 ) 

2631 

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

2633 # add these here. 

2634 metadata = tuple(metadata) + ( 

2635 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

2636 ) 

2637 

2638 # Send the request. 

2639 response = rpc( 

2640 request, 

2641 retry=retry, 

2642 timeout=timeout, 

2643 metadata=metadata, 

2644 ) 

2645 

2646 # Done; return the response. 

2647 return response 

2648 

2649 def test_iam_permissions( 

2650 self, 

2651 request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None, 

2652 *, 

2653 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

2655 metadata: Sequence[Tuple[str, str]] = (), 

2656 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

2657 r"""Tests the specified IAM permissions against the IAM access control 

2658 policy for a function. 

2659 

2660 If the function does not exist, this will return an empty set 

2661 of permissions, not a NOT_FOUND error. 

2662 

2663 Args: 

2664 request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`): 

2665 The request object. Request message for 

2666 `TestIamPermissions` method. 

2667 retry (google.api_core.retry.Retry): Designation of what errors, 

2668 if any, should be retried. 

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

2670 metadata (Sequence[Tuple[str, str]]): Strings which should be 

2671 sent along with the request as metadata. 

2672 Returns: 

2673 ~.iam_policy_pb2.TestIamPermissionsResponse: 

2674 Response message for ``TestIamPermissions`` method. 

2675 """ 

2676 # Create or coerce a protobuf request object. 

2677 

2678 # The request isn't a proto-plus wrapped type, 

2679 # so it must be constructed via keyword expansion. 

2680 if isinstance(request, dict): 

2681 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

2682 

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

2684 # and friendly error handling. 

2685 rpc = gapic_v1.method.wrap_method( 

2686 self._transport.test_iam_permissions, 

2687 default_timeout=None, 

2688 client_info=DEFAULT_CLIENT_INFO, 

2689 ) 

2690 

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

2692 # add these here. 

2693 metadata = tuple(metadata) + ( 

2694 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)), 

2695 ) 

2696 

2697 # Send the request. 

2698 response = rpc( 

2699 request, 

2700 retry=retry, 

2701 timeout=timeout, 

2702 metadata=metadata, 

2703 ) 

2704 

2705 # Done; return the response. 

2706 return response 

2707 

2708 

2709DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

2710 client_library_version=package_version.__version__ 

2711) 

2712 

2713 

2714__all__ = ("SubscriberClient",)