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

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

422 statements  

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

2# Copyright 2024 Google LLC 

3# 

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

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

6# You may obtain a copy of the License at 

7# 

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

9# 

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

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

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

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

14# limitations under the License. 

15# 

16from collections import OrderedDict 

17from http import HTTPStatus 

18import json 

19import logging as std_logging 

20import functools 

21import os 

22import re 

23from typing import ( 

24 Dict, 

25 Callable, 

26 Mapping, 

27 MutableMapping, 

28 MutableSequence, 

29 Optional, 

30 Sequence, 

31 Tuple, 

32 Type, 

33 Union, 

34 cast, 

35) 

36import warnings 

37 

38from google.pubsub_v1 import gapic_version as package_version 

39 

40from google.api_core import client_options as client_options_lib 

41from google.api_core import exceptions as core_exceptions 

42from google.api_core import gapic_v1 

43from google.api_core import retry as retries 

44from google.api_core import timeout as timeouts # type: ignore 

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

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

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

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

49from google.oauth2 import service_account # type: ignore 

50 

51try: 

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

53except AttributeError: # pragma: NO COVER 

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

55 

56try: 

57 from google.api_core import client_logging # type: ignore 

58 

59 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

60except ImportError: # pragma: NO COVER 

61 CLIENT_LOGGING_SUPPORTED = False 

62 

63_LOGGER = std_logging.getLogger(__name__) 

64 

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

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

67from google.protobuf import duration_pb2 # type: ignore 

68from google.protobuf import field_mask_pb2 # type: ignore 

69from google.pubsub_v1.services.publisher import pagers 

70from google.pubsub_v1.types import pubsub 

71from google.pubsub_v1.types import TimeoutType 

72 

73import grpc 

74from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO 

75from .transports.grpc import PublisherGrpcTransport 

76from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport 

77from .transports.rest import PublisherRestTransport 

78 

79 

80class PublisherClientMeta(type): 

81 """Metaclass for the Publisher client. 

82 

83 This provides class-level methods for building and retrieving 

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

85 objects. 

86 """ 

87 

88 _transport_registry = OrderedDict() # type: Dict[str, Type[PublisherTransport]] 

89 _transport_registry["grpc"] = PublisherGrpcTransport 

90 _transport_registry["grpc_asyncio"] = PublisherGrpcAsyncIOTransport 

91 _transport_registry["rest"] = PublisherRestTransport 

92 

93 def get_transport_class( 

94 cls, 

95 label: Optional[str] = None, 

96 ) -> Type[PublisherTransport]: 

97 """Returns an appropriate transport class. 

98 

99 Args: 

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

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

102 

103 Returns: 

104 The transport class to use. 

105 """ 

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

107 if label: 

108 return cls._transport_registry[label] 

109 

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

111 # in the dictionary). 

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

113 

114 

115class PublisherClient(metaclass=PublisherClientMeta): 

116 """The service that an application uses to manipulate topics, 

117 and to send messages to a topic. 

118 """ 

119 

120 @staticmethod 

121 def _get_default_mtls_endpoint(api_endpoint): 

122 """Converts api endpoint to mTLS endpoint. 

123 

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

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

126 Args: 

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

128 Returns: 

129 str: converted mTLS api endpoint. 

130 """ 

131 if not api_endpoint: 

132 return api_endpoint 

133 

134 mtls_endpoint_re = re.compile( 

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

136 ) 

137 

138 m = mtls_endpoint_re.match(api_endpoint) 

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

140 if mtls or not googledomain: 

141 return api_endpoint 

142 

143 if sandbox: 

144 return api_endpoint.replace( 

145 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

146 ) 

147 

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

149 

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

151 

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

153 # this service 

154 _DEFAULT_SCOPES = ( 

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

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

157 ) 

158 

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

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

161 

162 DEFAULT_ENDPOINT = "pubsub.googleapis.com" 

163 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

164 DEFAULT_ENDPOINT 

165 ) 

166 

167 _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}" 

168 _DEFAULT_UNIVERSE = "googleapis.com" 

169 

170 @classmethod 

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

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

173 info. 

174 

175 Args: 

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

177 args: Additional arguments to pass to the constructor. 

178 kwargs: Additional arguments to pass to the constructor. 

179 

180 Returns: 

181 PublisherClient: The constructed client. 

182 """ 

183 credentials = service_account.Credentials.from_service_account_info(info) 

184 kwargs["credentials"] = credentials 

185 return cls(*args, **kwargs) 

186 

187 @classmethod 

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

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

190 file. 

191 

192 Args: 

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

194 file. 

195 args: Additional arguments to pass to the constructor. 

196 kwargs: Additional arguments to pass to the constructor. 

197 

198 Returns: 

199 PublisherClient: The constructed client. 

200 """ 

201 credentials = service_account.Credentials.from_service_account_file(filename) 

202 kwargs["credentials"] = credentials 

203 return cls(*args, **kwargs) 

204 

205 from_service_account_json = from_service_account_file 

206 

207 @property 

208 def transport(self) -> PublisherTransport: 

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

210 

211 Returns: 

212 PublisherTransport: The transport used by the client 

213 instance. 

214 """ 

215 return self._transport 

216 

217 @staticmethod 

218 def schema_path( 

219 project: str, 

220 schema: str, 

221 ) -> str: 

222 """Returns a fully-qualified schema string.""" 

223 return "projects/{project}/schemas/{schema}".format( 

224 project=project, 

225 schema=schema, 

226 ) 

227 

228 @staticmethod 

229 def parse_schema_path(path: str) -> Dict[str, str]: 

230 """Parses a schema path into its component segments.""" 

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

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

233 

234 @staticmethod 

235 def subscription_path( 

236 project: str, 

237 subscription: str, 

238 ) -> str: 

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

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

241 project=project, 

242 subscription=subscription, 

243 ) 

244 

245 @staticmethod 

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

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

248 m = re.match( 

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

250 ) 

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

252 

253 @staticmethod 

254 def topic_path( 

255 project: str, 

256 topic: str, 

257 ) -> str: 

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

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

260 project=project, 

261 topic=topic, 

262 ) 

263 

264 @staticmethod 

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

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

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

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

269 

270 @staticmethod 

271 def common_billing_account_path( 

272 billing_account: str, 

273 ) -> str: 

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

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

276 billing_account=billing_account, 

277 ) 

278 

279 @staticmethod 

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

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

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

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

284 

285 @staticmethod 

286 def common_folder_path( 

287 folder: str, 

288 ) -> str: 

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

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

291 folder=folder, 

292 ) 

293 

294 @staticmethod 

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

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

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

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

299 

300 @staticmethod 

301 def common_organization_path( 

302 organization: str, 

303 ) -> str: 

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

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

306 organization=organization, 

307 ) 

308 

309 @staticmethod 

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

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

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

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

314 

315 @staticmethod 

316 def common_project_path( 

317 project: str, 

318 ) -> str: 

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

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

321 project=project, 

322 ) 

323 

324 @staticmethod 

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

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

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

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

329 

330 @staticmethod 

331 def common_location_path( 

332 project: str, 

333 location: str, 

334 ) -> str: 

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

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

337 project=project, 

338 location=location, 

339 ) 

340 

341 @staticmethod 

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

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

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

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

346 

347 @classmethod 

348 def get_mtls_endpoint_and_cert_source( 

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

350 ): 

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

352 

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

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

355 client cert source is None. 

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

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

358 source is None. 

359 

360 The API endpoint is determined in the following order: 

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

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

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

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

365 use the default API endpoint. 

366 

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

368 

369 Args: 

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

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

372 in this method. 

373 

374 Returns: 

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

376 client cert source to use. 

377 

378 Raises: 

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

380 """ 

381 

382 warnings.warn( 

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

384 DeprecationWarning, 

385 ) 

386 if client_options is None: 

387 client_options = client_options_lib.ClientOptions() 

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

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

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

391 raise ValueError( 

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

393 ) 

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

395 raise MutualTLSChannelError( 

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

397 ) 

398 

399 # Figure out the client cert source to use. 

400 client_cert_source = None 

401 if use_client_cert == "true": 

402 if client_options.client_cert_source: 

403 client_cert_source = client_options.client_cert_source 

404 elif mtls.has_default_client_cert_source(): 

405 client_cert_source = mtls.default_client_cert_source() 

406 

407 # Figure out which api endpoint to use. 

408 if client_options.api_endpoint is not None: 

409 api_endpoint = client_options.api_endpoint 

410 elif use_mtls_endpoint == "always" or ( 

411 use_mtls_endpoint == "auto" and client_cert_source 

412 ): 

413 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

414 else: 

415 api_endpoint = cls.DEFAULT_ENDPOINT 

416 

417 return api_endpoint, client_cert_source 

418 

419 @staticmethod 

420 def _read_environment_variables(): 

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

422 

423 Returns: 

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

425 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. 

426 

427 Raises: 

428 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not 

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

430 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT 

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

432 """ 

433 use_client_cert = os.getenv( 

434 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" 

435 ).lower() 

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

437 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") 

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

439 raise ValueError( 

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

441 ) 

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

443 raise MutualTLSChannelError( 

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

445 ) 

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

447 

448 @staticmethod 

449 def _get_client_cert_source(provided_cert_source, use_cert_flag): 

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

451 

452 Args: 

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

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

455 

456 Returns: 

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

458 """ 

459 client_cert_source = None 

460 if use_cert_flag: 

461 if provided_cert_source: 

462 client_cert_source = provided_cert_source 

463 elif mtls.has_default_client_cert_source(): 

464 client_cert_source = mtls.default_client_cert_source() 

465 return client_cert_source 

466 

467 @staticmethod 

468 def _get_api_endpoint( 

469 api_override, client_cert_source, universe_domain, use_mtls_endpoint 

470 ): 

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

472 

473 Args: 

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

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

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

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

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

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

480 

481 Returns: 

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

483 """ 

484 if api_override is not None: 

485 api_endpoint = api_override 

486 elif use_mtls_endpoint == "always" or ( 

487 use_mtls_endpoint == "auto" and client_cert_source 

488 ): 

489 _default_universe = PublisherClient._DEFAULT_UNIVERSE 

490 if universe_domain != _default_universe: 

491 raise MutualTLSChannelError( 

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

493 ) 

494 api_endpoint = PublisherClient.DEFAULT_MTLS_ENDPOINT 

495 else: 

496 api_endpoint = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE.format( 

497 UNIVERSE_DOMAIN=universe_domain 

498 ) 

499 return api_endpoint 

500 

501 @staticmethod 

502 def _get_universe_domain( 

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

504 ) -> str: 

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

506 

507 Args: 

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

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

510 

511 Returns: 

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

513 

514 Raises: 

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

516 """ 

517 universe_domain = PublisherClient._DEFAULT_UNIVERSE 

518 if client_universe_domain is not None: 

519 universe_domain = client_universe_domain 

520 elif universe_domain_env is not None: 

521 universe_domain = universe_domain_env 

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

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

524 return universe_domain 

525 

526 def _validate_universe_domain(self): 

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

528 

529 Returns: 

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

531 

532 Raises: 

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

534 """ 

535 

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

537 return True 

538 

539 def _add_cred_info_for_auth_errors( 

540 self, error: core_exceptions.GoogleAPICallError 

541 ) -> None: 

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

543 

544 Args: 

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

546 """ 

547 if error.code not in [ 

548 HTTPStatus.UNAUTHORIZED, 

549 HTTPStatus.FORBIDDEN, 

550 HTTPStatus.NOT_FOUND, 

551 ]: 

552 return 

553 

554 cred = self._transport._credentials 

555 

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

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

558 return 

559 

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

561 # is not available 

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

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

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

565 

566 @property 

567 def api_endpoint(self): 

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

569 

570 Returns: 

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

572 """ 

573 return self._api_endpoint 

574 

575 @property 

576 def universe_domain(self) -> str: 

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

578 

579 Returns: 

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

581 """ 

582 return self._universe_domain 

583 

584 def __init__( 

585 self, 

586 *, 

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

588 transport: Optional[ 

589 Union[str, PublisherTransport, Callable[..., PublisherTransport]] 

590 ] = None, 

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

592 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

593 ) -> None: 

594 """Instantiates the publisher client. 

595 

596 Args: 

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

598 authorization credentials to attach to requests. These 

599 credentials identify the application to the service; if none 

600 are specified, the client will attempt to ascertain the 

601 credentials from the environment. 

602 transport (Optional[Union[str,PublisherTransport,Callable[..., PublisherTransport]]]): 

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

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

605 arguments as used in the PublisherTransport constructor. 

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

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

608 Custom options for the client. 

609 

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

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

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

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

614 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

615 variable, which have one of the following values: 

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

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

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

619 the default value). 

620 

621 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

623 to provide a client certificate for mTLS transport. If 

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

625 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

626 set, no client certificate will be used. 

627 

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

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

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

631 currently not supported for mTLS. 

632 

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

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

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

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

637 your own client library. 

638 

639 Raises: 

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

641 creation failed for any reason. 

642 """ 

643 self._client_options = client_options 

644 if isinstance(self._client_options, dict): 

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

646 if self._client_options is None: 

647 self._client_options = client_options_lib.ClientOptions() 

648 self._client_options = cast( 

649 client_options_lib.ClientOptions, self._client_options 

650 ) 

651 

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

653 

654 ( 

655 self._use_client_cert, 

656 self._use_mtls_endpoint, 

657 self._universe_domain_env, 

658 ) = PublisherClient._read_environment_variables() 

659 self._client_cert_source = PublisherClient._get_client_cert_source( 

660 self._client_options.client_cert_source, self._use_client_cert 

661 ) 

662 self._universe_domain = PublisherClient._get_universe_domain( 

663 universe_domain_opt, self._universe_domain_env 

664 ) 

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

666 

667 # Initialize the universe domain validation. 

668 self._is_universe_domain_valid = False 

669 

670 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER 

671 # Setup logging. 

672 client_logging.initialize_logging() 

673 

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

675 if api_key_value and credentials: 

676 raise ValueError( 

677 "client_options.api_key and credentials are mutually exclusive" 

678 ) 

679 

680 # Save or instantiate the transport. 

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

682 # instance provides an extensibility point for unusual situations. 

683 transport_provided = isinstance(transport, PublisherTransport) 

684 if transport_provided: 

685 # transport is a PublisherTransport instance. 

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

687 raise ValueError( 

688 "When providing a transport instance, " 

689 "provide its credentials directly." 

690 ) 

691 if self._client_options.scopes: 

692 raise ValueError( 

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

694 "directly." 

695 ) 

696 self._transport = cast(PublisherTransport, transport) 

697 self._api_endpoint = self._transport.host 

698 

699 self._api_endpoint = self._api_endpoint or PublisherClient._get_api_endpoint( 

700 self._client_options.api_endpoint, 

701 self._client_cert_source, 

702 self._universe_domain, 

703 self._use_mtls_endpoint, 

704 ) 

705 

706 if not transport_provided: 

707 import google.auth._default # type: ignore 

708 

709 if api_key_value and hasattr( 

710 google.auth._default, "get_api_key_credentials" 

711 ): 

712 credentials = google.auth._default.get_api_key_credentials( 

713 api_key_value 

714 ) 

715 

716 transport_init: Union[ 

717 Type[PublisherTransport], Callable[..., PublisherTransport] 

718 ] = ( 

719 PublisherClient.get_transport_class(transport) 

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

721 else cast(Callable[..., PublisherTransport], transport) 

722 ) 

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

724 

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

726 if emulator_host: 

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

728 channel = grpc.insecure_channel(target=emulator_host) 

729 else: 

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

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

732 

733 self._transport = transport_init( 

734 credentials=credentials, 

735 credentials_file=self._client_options.credentials_file, 

736 host=self._api_endpoint, 

737 scopes=self._client_options.scopes, 

738 client_cert_source_for_mtls=self._client_cert_source, 

739 quota_project_id=self._client_options.quota_project_id, 

740 client_info=client_info, 

741 always_use_jwt_access=True, 

742 api_audience=self._client_options.api_audience, 

743 ) 

744 

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

746 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

747 std_logging.DEBUG 

748 ): # pragma: NO COVER 

749 _LOGGER.debug( 

750 "Created client `google.pubsub_v1.PublisherClient`.", 

751 extra={ 

752 "serviceName": "google.pubsub.v1.Publisher", 

753 "universeDomain": getattr( 

754 self._transport._credentials, "universe_domain", "" 

755 ), 

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

757 "credentialsInfo": getattr( 

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

759 )(), 

760 } 

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

762 else { 

763 "serviceName": "google.pubsub.v1.Publisher", 

764 "credentialsType": None, 

765 }, 

766 ) 

767 

768 def create_topic( 

769 self, 

770 request: Optional[Union[pubsub.Topic, dict]] = None, 

771 *, 

772 name: Optional[str] = None, 

773 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

774 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

776 ) -> pubsub.Topic: 

777 r"""Creates the given topic with the given name. See the [resource 

778 name rules] 

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

780 

781 .. code-block:: python 

782 

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

784 # code template only. 

785 # It will require modifications to work: 

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

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

788 # client as shown in: 

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

790 from google import pubsub_v1 

791 

792 def sample_create_topic(): 

793 # Create a client 

794 client = pubsub_v1.PublisherClient() 

795 

796 # Initialize request argument(s) 

797 request = pubsub_v1.Topic( 

798 name="name_value", 

799 ) 

800 

801 # Make the request 

802 response = client.create_topic(request=request) 

803 

804 # Handle the response 

805 print(response) 

806 

807 Args: 

808 request (Union[google.pubsub_v1.types.Topic, dict]): 

809 The request object. A topic resource. 

810 name (str): 

811 Required. The name of the topic. It must have the format 

812 ``"projects/{project}/topics/{topic}"``. ``{topic}`` 

813 must start with a letter, and contain only letters 

814 (``[A-Za-z]``), numbers (``[0-9]``), dashes (``-``), 

815 underscores (``_``), periods (``.``), tildes (``~``), 

816 plus (``+``) or percent signs (``%``). It must be 

817 between 3 and 255 characters in length, and it must not 

818 start with ``"goog"``. 

819 

820 This corresponds to the ``name`` field 

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

822 should not be set. 

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

824 should be retried. 

825 timeout (TimeoutType): 

826 The timeout for this request. 

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

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

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

830 be of type `bytes`. 

831 

832 Returns: 

833 google.pubsub_v1.types.Topic: 

834 A topic resource. 

835 """ 

836 # Create or coerce a protobuf request object. 

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

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

839 flattened_params = [name] 

840 has_flattened_params = ( 

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

842 ) 

843 if request is not None and has_flattened_params: 

844 raise ValueError( 

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

846 "the individual field arguments should be set." 

847 ) 

848 

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

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

851 if not isinstance(request, pubsub.Topic): 

852 request = pubsub.Topic(request) 

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

854 # request, apply these. 

855 if name is not None: 

856 request.name = name 

857 

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

859 # and friendly error handling. 

860 rpc = self._transport._wrapped_methods[self._transport.create_topic] 

861 

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

863 # add these here. 

864 metadata = tuple(metadata) + ( 

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

866 ) 

867 

868 # Validate the universe domain. 

869 self._validate_universe_domain() 

870 

871 # Send the request. 

872 response = rpc( 

873 request, 

874 retry=retry, 

875 timeout=timeout, 

876 metadata=metadata, 

877 ) 

878 

879 # Done; return the response. 

880 return response 

881 

882 def update_topic( 

883 self, 

884 request: Optional[Union[pubsub.UpdateTopicRequest, dict]] = None, 

885 *, 

886 topic: Optional[pubsub.Topic] = None, 

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

888 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

889 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

891 ) -> pubsub.Topic: 

892 r"""Updates an existing topic by updating the fields 

893 specified in the update mask. Note that certain 

894 properties of a topic are not modifiable. 

895 

896 .. code-block:: python 

897 

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

899 # code template only. 

900 # It will require modifications to work: 

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

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

903 # client as shown in: 

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

905 from google import pubsub_v1 

906 

907 def sample_update_topic(): 

908 # Create a client 

909 client = pubsub_v1.PublisherClient() 

910 

911 # Initialize request argument(s) 

912 topic = pubsub_v1.Topic() 

913 topic.name = "name_value" 

914 

915 request = pubsub_v1.UpdateTopicRequest( 

916 topic=topic, 

917 ) 

918 

919 # Make the request 

920 response = client.update_topic(request=request) 

921 

922 # Handle the response 

923 print(response) 

924 

925 Args: 

926 request (Union[google.pubsub_v1.types.UpdateTopicRequest, dict]): 

927 The request object. Request for the UpdateTopic method. 

928 topic (google.pubsub_v1.types.Topic): 

929 Required. The updated topic object. 

930 This corresponds to the ``topic`` field 

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

932 should not be set. 

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

934 Required. Indicates which fields in the provided topic 

935 to update. Must be specified and non-empty. Note that if 

936 ``update_mask`` contains "message_storage_policy" but 

937 the ``message_storage_policy`` is not set in the 

938 ``topic`` provided above, then the updated value is 

939 determined by the policy configured at the project or 

940 organization level. 

941 

942 This corresponds to the ``update_mask`` field 

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

944 should not be set. 

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

946 should be retried. 

947 timeout (TimeoutType): 

948 The timeout for this request. 

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

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

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

952 be of type `bytes`. 

953 

954 Returns: 

955 google.pubsub_v1.types.Topic: 

956 A topic resource. 

957 """ 

958 # Create or coerce a protobuf request object. 

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

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

961 flattened_params = [topic, update_mask] 

962 has_flattened_params = ( 

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

964 ) 

965 if request is not None and has_flattened_params: 

966 raise ValueError( 

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

968 "the individual field arguments should be set." 

969 ) 

970 

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

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

973 if not isinstance(request, pubsub.UpdateTopicRequest): 

974 request = pubsub.UpdateTopicRequest(request) 

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

976 # request, apply these. 

977 if topic is not None: 

978 request.topic = topic 

979 if update_mask is not None: 

980 request.update_mask = update_mask 

981 

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

983 # and friendly error handling. 

984 rpc = self._transport._wrapped_methods[self._transport.update_topic] 

985 

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

987 # add these here. 

988 metadata = tuple(metadata) + ( 

989 gapic_v1.routing_header.to_grpc_metadata( 

990 (("topic.name", request.topic.name),) 

991 ), 

992 ) 

993 

994 # Validate the universe domain. 

995 self._validate_universe_domain() 

996 

997 # Send the request. 

998 response = rpc( 

999 request, 

1000 retry=retry, 

1001 timeout=timeout, 

1002 metadata=metadata, 

1003 ) 

1004 

1005 # Done; return the response. 

1006 return response 

1007 

1008 def publish( 

1009 self, 

1010 request: Optional[Union[pubsub.PublishRequest, dict]] = None, 

1011 *, 

1012 topic: Optional[str] = None, 

1013 messages: Optional[MutableSequence[pubsub.PubsubMessage]] = None, 

1014 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1015 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1017 ) -> pubsub.PublishResponse: 

1018 r"""Adds one or more messages to the topic. Returns ``NOT_FOUND`` if 

1019 the topic does not exist. 

1020 

1021 .. code-block:: python 

1022 

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

1024 # code template only. 

1025 # It will require modifications to work: 

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

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

1028 # client as shown in: 

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

1030 from google import pubsub_v1 

1031 

1032 def sample_publish(): 

1033 # Create a client 

1034 client = pubsub_v1.PublisherClient() 

1035 

1036 # Initialize request argument(s) 

1037 request = pubsub_v1.PublishRequest( 

1038 topic="topic_value", 

1039 ) 

1040 

1041 # Make the request 

1042 response = client.publish(request=request) 

1043 

1044 # Handle the response 

1045 print(response) 

1046 

1047 Args: 

1048 request (Union[google.pubsub_v1.types.PublishRequest, dict]): 

1049 The request object. Request for the Publish method. 

1050 topic (str): 

1051 Required. The messages in the request will be published 

1052 on this topic. Format is 

1053 ``projects/{project}/topics/{topic}``. 

1054 

1055 This corresponds to the ``topic`` field 

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

1057 should not be set. 

1058 messages (MutableSequence[google.pubsub_v1.types.PubsubMessage]): 

1059 Required. The messages to publish. 

1060 This corresponds to the ``messages`` field 

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

1062 should not be set. 

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

1064 should be retried. 

1065 timeout (TimeoutType): 

1066 The timeout for this request. 

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

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

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

1070 be of type `bytes`. 

1071 

1072 Returns: 

1073 google.pubsub_v1.types.PublishResponse: 

1074 Response for the Publish method. 

1075 """ 

1076 # Create or coerce a protobuf request object. 

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

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

1079 flattened_params = [topic, messages] 

1080 has_flattened_params = ( 

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

1082 ) 

1083 if request is not None and has_flattened_params: 

1084 raise ValueError( 

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

1086 "the individual field arguments should be set." 

1087 ) 

1088 

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

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

1091 if not isinstance(request, pubsub.PublishRequest): 

1092 request = pubsub.PublishRequest(request) 

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

1094 # request, apply these. 

1095 if topic is not None: 

1096 request.topic = topic 

1097 if messages is not None: 

1098 request.messages = messages 

1099 

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

1101 # and friendly error handling. 

1102 rpc = self._transport._wrapped_methods[self._transport.publish] 

1103 

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

1105 # add these here. 

1106 metadata = tuple(metadata) + ( 

1107 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

1108 ) 

1109 

1110 # Validate the universe domain. 

1111 self._validate_universe_domain() 

1112 

1113 # Send the request. 

1114 response = rpc( 

1115 request, 

1116 retry=retry, 

1117 timeout=timeout, 

1118 metadata=metadata, 

1119 ) 

1120 

1121 # Done; return the response. 

1122 return response 

1123 

1124 def get_topic( 

1125 self, 

1126 request: Optional[Union[pubsub.GetTopicRequest, dict]] = None, 

1127 *, 

1128 topic: Optional[str] = None, 

1129 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1130 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1132 ) -> pubsub.Topic: 

1133 r"""Gets the configuration of a topic. 

1134 

1135 .. code-block:: python 

1136 

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

1138 # code template only. 

1139 # It will require modifications to work: 

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

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

1142 # client as shown in: 

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

1144 from google import pubsub_v1 

1145 

1146 def sample_get_topic(): 

1147 # Create a client 

1148 client = pubsub_v1.PublisherClient() 

1149 

1150 # Initialize request argument(s) 

1151 request = pubsub_v1.GetTopicRequest( 

1152 topic="topic_value", 

1153 ) 

1154 

1155 # Make the request 

1156 response = client.get_topic(request=request) 

1157 

1158 # Handle the response 

1159 print(response) 

1160 

1161 Args: 

1162 request (Union[google.pubsub_v1.types.GetTopicRequest, dict]): 

1163 The request object. Request for the GetTopic method. 

1164 topic (str): 

1165 Required. The name of the topic to get. Format is 

1166 ``projects/{project}/topics/{topic}``. 

1167 

1168 This corresponds to the ``topic`` field 

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

1170 should not be set. 

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

1172 should be retried. 

1173 timeout (TimeoutType): 

1174 The timeout for this request. 

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

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

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

1178 be of type `bytes`. 

1179 

1180 Returns: 

1181 google.pubsub_v1.types.Topic: 

1182 A topic resource. 

1183 """ 

1184 # Create or coerce a protobuf request object. 

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

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

1187 flattened_params = [topic] 

1188 has_flattened_params = ( 

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

1190 ) 

1191 if request is not None and has_flattened_params: 

1192 raise ValueError( 

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

1194 "the individual field arguments should be set." 

1195 ) 

1196 

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

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

1199 if not isinstance(request, pubsub.GetTopicRequest): 

1200 request = pubsub.GetTopicRequest(request) 

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

1202 # request, apply these. 

1203 if topic is not None: 

1204 request.topic = topic 

1205 

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

1207 # and friendly error handling. 

1208 rpc = self._transport._wrapped_methods[self._transport.get_topic] 

1209 

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

1211 # add these here. 

1212 metadata = tuple(metadata) + ( 

1213 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

1214 ) 

1215 

1216 # Validate the universe domain. 

1217 self._validate_universe_domain() 

1218 

1219 # Send the request. 

1220 response = rpc( 

1221 request, 

1222 retry=retry, 

1223 timeout=timeout, 

1224 metadata=metadata, 

1225 ) 

1226 

1227 # Done; return the response. 

1228 return response 

1229 

1230 def list_topics( 

1231 self, 

1232 request: Optional[Union[pubsub.ListTopicsRequest, dict]] = None, 

1233 *, 

1234 project: Optional[str] = None, 

1235 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1236 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1238 ) -> pagers.ListTopicsPager: 

1239 r"""Lists matching topics. 

1240 

1241 .. code-block:: python 

1242 

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

1244 # code template only. 

1245 # It will require modifications to work: 

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

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

1248 # client as shown in: 

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

1250 from google import pubsub_v1 

1251 

1252 def sample_list_topics(): 

1253 # Create a client 

1254 client = pubsub_v1.PublisherClient() 

1255 

1256 # Initialize request argument(s) 

1257 request = pubsub_v1.ListTopicsRequest( 

1258 project="project_value", 

1259 ) 

1260 

1261 # Make the request 

1262 page_result = client.list_topics(request=request) 

1263 

1264 # Handle the response 

1265 for response in page_result: 

1266 print(response) 

1267 

1268 Args: 

1269 request (Union[google.pubsub_v1.types.ListTopicsRequest, dict]): 

1270 The request object. Request for the ``ListTopics`` method. 

1271 project (str): 

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

1273 topics. Format is ``projects/{project-id}``. 

1274 

1275 This corresponds to the ``project`` field 

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

1277 should not be set. 

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

1279 should be retried. 

1280 timeout (TimeoutType): 

1281 The timeout for this request. 

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

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

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

1285 be of type `bytes`. 

1286 

1287 Returns: 

1288 google.pubsub_v1.services.publisher.pagers.ListTopicsPager: 

1289 Response for the ListTopics method. 

1290 

1291 Iterating over this object will yield results and 

1292 resolve additional pages automatically. 

1293 

1294 """ 

1295 # Create or coerce a protobuf request object. 

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

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

1298 flattened_params = [project] 

1299 has_flattened_params = ( 

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

1301 ) 

1302 if request is not None and has_flattened_params: 

1303 raise ValueError( 

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

1305 "the individual field arguments should be set." 

1306 ) 

1307 

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

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

1310 if not isinstance(request, pubsub.ListTopicsRequest): 

1311 request = pubsub.ListTopicsRequest(request) 

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

1313 # request, apply these. 

1314 if project is not None: 

1315 request.project = project 

1316 

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

1318 # and friendly error handling. 

1319 rpc = self._transport._wrapped_methods[self._transport.list_topics] 

1320 

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

1322 # add these here. 

1323 metadata = tuple(metadata) + ( 

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

1325 ) 

1326 

1327 # Validate the universe domain. 

1328 self._validate_universe_domain() 

1329 

1330 # Send the request. 

1331 response = rpc( 

1332 request, 

1333 retry=retry, 

1334 timeout=timeout, 

1335 metadata=metadata, 

1336 ) 

1337 

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

1339 # an `__iter__` convenience method. 

1340 response = pagers.ListTopicsPager( 

1341 method=rpc, 

1342 request=request, 

1343 response=response, 

1344 retry=retry, 

1345 timeout=timeout, 

1346 metadata=metadata, 

1347 ) 

1348 

1349 # Done; return the response. 

1350 return response 

1351 

1352 def list_topic_subscriptions( 

1353 self, 

1354 request: Optional[Union[pubsub.ListTopicSubscriptionsRequest, dict]] = None, 

1355 *, 

1356 topic: Optional[str] = None, 

1357 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1358 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1360 ) -> pagers.ListTopicSubscriptionsPager: 

1361 r"""Lists the names of the attached subscriptions on this 

1362 topic. 

1363 

1364 .. code-block:: python 

1365 

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

1367 # code template only. 

1368 # It will require modifications to work: 

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

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

1371 # client as shown in: 

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

1373 from google import pubsub_v1 

1374 

1375 def sample_list_topic_subscriptions(): 

1376 # Create a client 

1377 client = pubsub_v1.PublisherClient() 

1378 

1379 # Initialize request argument(s) 

1380 request = pubsub_v1.ListTopicSubscriptionsRequest( 

1381 topic="topic_value", 

1382 ) 

1383 

1384 # Make the request 

1385 page_result = client.list_topic_subscriptions(request=request) 

1386 

1387 # Handle the response 

1388 for response in page_result: 

1389 print(response) 

1390 

1391 Args: 

1392 request (Union[google.pubsub_v1.types.ListTopicSubscriptionsRequest, dict]): 

1393 The request object. Request for the ``ListTopicSubscriptions`` method. 

1394 topic (str): 

1395 Required. The name of the topic that subscriptions are 

1396 attached to. Format is 

1397 ``projects/{project}/topics/{topic}``. 

1398 

1399 This corresponds to the ``topic`` field 

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

1401 should not be set. 

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

1403 should be retried. 

1404 timeout (TimeoutType): 

1405 The timeout for this request. 

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

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

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

1409 be of type `bytes`. 

1410 

1411 Returns: 

1412 google.pubsub_v1.services.publisher.pagers.ListTopicSubscriptionsPager: 

1413 Response for the ListTopicSubscriptions method. 

1414 

1415 Iterating over this object will yield results and 

1416 resolve additional pages automatically. 

1417 

1418 """ 

1419 # Create or coerce a protobuf request object. 

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

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

1422 flattened_params = [topic] 

1423 has_flattened_params = ( 

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

1425 ) 

1426 if request is not None and has_flattened_params: 

1427 raise ValueError( 

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

1429 "the individual field arguments should be set." 

1430 ) 

1431 

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

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

1434 if not isinstance(request, pubsub.ListTopicSubscriptionsRequest): 

1435 request = pubsub.ListTopicSubscriptionsRequest(request) 

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

1437 # request, apply these. 

1438 if topic is not None: 

1439 request.topic = topic 

1440 

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

1442 # and friendly error handling. 

1443 rpc = self._transport._wrapped_methods[self._transport.list_topic_subscriptions] 

1444 

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

1446 # add these here. 

1447 metadata = tuple(metadata) + ( 

1448 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

1449 ) 

1450 

1451 # Validate the universe domain. 

1452 self._validate_universe_domain() 

1453 

1454 # Send the request. 

1455 response = rpc( 

1456 request, 

1457 retry=retry, 

1458 timeout=timeout, 

1459 metadata=metadata, 

1460 ) 

1461 

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

1463 # an `__iter__` convenience method. 

1464 response = pagers.ListTopicSubscriptionsPager( 

1465 method=rpc, 

1466 request=request, 

1467 response=response, 

1468 retry=retry, 

1469 timeout=timeout, 

1470 metadata=metadata, 

1471 ) 

1472 

1473 # Done; return the response. 

1474 return response 

1475 

1476 def list_topic_snapshots( 

1477 self, 

1478 request: Optional[Union[pubsub.ListTopicSnapshotsRequest, dict]] = None, 

1479 *, 

1480 topic: Optional[str] = None, 

1481 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1482 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1484 ) -> pagers.ListTopicSnapshotsPager: 

1485 r"""Lists the names of the snapshots on this topic. Snapshots are 

1486 used in 

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

1488 operations, which allow you to manage message acknowledgments in 

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

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

1491 

1492 .. code-block:: python 

1493 

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

1495 # code template only. 

1496 # It will require modifications to work: 

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

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

1499 # client as shown in: 

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

1501 from google import pubsub_v1 

1502 

1503 def sample_list_topic_snapshots(): 

1504 # Create a client 

1505 client = pubsub_v1.PublisherClient() 

1506 

1507 # Initialize request argument(s) 

1508 request = pubsub_v1.ListTopicSnapshotsRequest( 

1509 topic="topic_value", 

1510 ) 

1511 

1512 # Make the request 

1513 page_result = client.list_topic_snapshots(request=request) 

1514 

1515 # Handle the response 

1516 for response in page_result: 

1517 print(response) 

1518 

1519 Args: 

1520 request (Union[google.pubsub_v1.types.ListTopicSnapshotsRequest, dict]): 

1521 The request object. Request for the ``ListTopicSnapshots`` method. 

1522 topic (str): 

1523 Required. The name of the topic that snapshots are 

1524 attached to. Format is 

1525 ``projects/{project}/topics/{topic}``. 

1526 

1527 This corresponds to the ``topic`` field 

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

1529 should not be set. 

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

1531 should be retried. 

1532 timeout (TimeoutType): 

1533 The timeout for this request. 

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

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

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

1537 be of type `bytes`. 

1538 

1539 Returns: 

1540 google.pubsub_v1.services.publisher.pagers.ListTopicSnapshotsPager: 

1541 Response for the ListTopicSnapshots method. 

1542 

1543 Iterating over this object will yield results and 

1544 resolve additional pages automatically. 

1545 

1546 """ 

1547 # Create or coerce a protobuf request object. 

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

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

1550 flattened_params = [topic] 

1551 has_flattened_params = ( 

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

1553 ) 

1554 if request is not None and has_flattened_params: 

1555 raise ValueError( 

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

1557 "the individual field arguments should be set." 

1558 ) 

1559 

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

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

1562 if not isinstance(request, pubsub.ListTopicSnapshotsRequest): 

1563 request = pubsub.ListTopicSnapshotsRequest(request) 

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

1565 # request, apply these. 

1566 if topic is not None: 

1567 request.topic = topic 

1568 

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

1570 # and friendly error handling. 

1571 rpc = self._transport._wrapped_methods[self._transport.list_topic_snapshots] 

1572 

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

1574 # add these here. 

1575 metadata = tuple(metadata) + ( 

1576 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

1577 ) 

1578 

1579 # Validate the universe domain. 

1580 self._validate_universe_domain() 

1581 

1582 # Send the request. 

1583 response = rpc( 

1584 request, 

1585 retry=retry, 

1586 timeout=timeout, 

1587 metadata=metadata, 

1588 ) 

1589 

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

1591 # an `__iter__` convenience method. 

1592 response = pagers.ListTopicSnapshotsPager( 

1593 method=rpc, 

1594 request=request, 

1595 response=response, 

1596 retry=retry, 

1597 timeout=timeout, 

1598 metadata=metadata, 

1599 ) 

1600 

1601 # Done; return the response. 

1602 return response 

1603 

1604 def delete_topic( 

1605 self, 

1606 request: Optional[Union[pubsub.DeleteTopicRequest, dict]] = None, 

1607 *, 

1608 topic: Optional[str] = None, 

1609 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1610 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1612 ) -> None: 

1613 r"""Deletes the topic with the given name. Returns ``NOT_FOUND`` if 

1614 the topic does not exist. After a topic is deleted, a new topic 

1615 may be created with the same name; this is an entirely new topic 

1616 with none of the old configuration or subscriptions. Existing 

1617 subscriptions to this topic are not deleted, but their ``topic`` 

1618 field is set to ``_deleted-topic_``. 

1619 

1620 .. code-block:: python 

1621 

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

1623 # code template only. 

1624 # It will require modifications to work: 

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

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

1627 # client as shown in: 

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

1629 from google import pubsub_v1 

1630 

1631 def sample_delete_topic(): 

1632 # Create a client 

1633 client = pubsub_v1.PublisherClient() 

1634 

1635 # Initialize request argument(s) 

1636 request = pubsub_v1.DeleteTopicRequest( 

1637 topic="topic_value", 

1638 ) 

1639 

1640 # Make the request 

1641 client.delete_topic(request=request) 

1642 

1643 Args: 

1644 request (Union[google.pubsub_v1.types.DeleteTopicRequest, dict]): 

1645 The request object. Request for the ``DeleteTopic`` method. 

1646 topic (str): 

1647 Required. Name of the topic to delete. Format is 

1648 ``projects/{project}/topics/{topic}``. 

1649 

1650 This corresponds to the ``topic`` field 

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

1652 should not be set. 

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

1654 should be retried. 

1655 timeout (TimeoutType): 

1656 The timeout for this request. 

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

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

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

1660 be of type `bytes`. 

1661 """ 

1662 # Create or coerce a protobuf request object. 

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

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

1665 flattened_params = [topic] 

1666 has_flattened_params = ( 

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

1668 ) 

1669 if request is not None and has_flattened_params: 

1670 raise ValueError( 

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

1672 "the individual field arguments should be set." 

1673 ) 

1674 

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

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

1677 if not isinstance(request, pubsub.DeleteTopicRequest): 

1678 request = pubsub.DeleteTopicRequest(request) 

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

1680 # request, apply these. 

1681 if topic is not None: 

1682 request.topic = topic 

1683 

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

1685 # and friendly error handling. 

1686 rpc = self._transport._wrapped_methods[self._transport.delete_topic] 

1687 

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

1689 # add these here. 

1690 metadata = tuple(metadata) + ( 

1691 gapic_v1.routing_header.to_grpc_metadata((("topic", request.topic),)), 

1692 ) 

1693 

1694 # Validate the universe domain. 

1695 self._validate_universe_domain() 

1696 

1697 # Send the request. 

1698 rpc( 

1699 request, 

1700 retry=retry, 

1701 timeout=timeout, 

1702 metadata=metadata, 

1703 ) 

1704 

1705 def detach_subscription( 

1706 self, 

1707 request: Optional[Union[pubsub.DetachSubscriptionRequest, dict]] = None, 

1708 *, 

1709 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1710 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1712 ) -> pubsub.DetachSubscriptionResponse: 

1713 r"""Detaches a subscription from this topic. All messages retained 

1714 in the subscription are dropped. Subsequent ``Pull`` and 

1715 ``StreamingPull`` requests will return FAILED_PRECONDITION. If 

1716 the subscription is a push subscription, pushes to the endpoint 

1717 will stop. 

1718 

1719 .. code-block:: python 

1720 

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

1722 # code template only. 

1723 # It will require modifications to work: 

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

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

1726 # client as shown in: 

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

1728 from google import pubsub_v1 

1729 

1730 def sample_detach_subscription(): 

1731 # Create a client 

1732 client = pubsub_v1.PublisherClient() 

1733 

1734 # Initialize request argument(s) 

1735 request = pubsub_v1.DetachSubscriptionRequest( 

1736 subscription="subscription_value", 

1737 ) 

1738 

1739 # Make the request 

1740 response = client.detach_subscription(request=request) 

1741 

1742 # Handle the response 

1743 print(response) 

1744 

1745 Args: 

1746 request (Union[google.pubsub_v1.types.DetachSubscriptionRequest, dict]): 

1747 The request object. Request for the DetachSubscription 

1748 method. 

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

1750 should be retried. 

1751 timeout (TimeoutType): 

1752 The timeout for this request. 

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

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

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

1756 be of type `bytes`. 

1757 

1758 Returns: 

1759 google.pubsub_v1.types.DetachSubscriptionResponse: 

1760 Response for the DetachSubscription 

1761 method. Reserved for future use. 

1762 

1763 """ 

1764 # Create or coerce a protobuf request object. 

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

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

1767 if not isinstance(request, pubsub.DetachSubscriptionRequest): 

1768 request = pubsub.DetachSubscriptionRequest(request) 

1769 

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

1771 # and friendly error handling. 

1772 rpc = self._transport._wrapped_methods[self._transport.detach_subscription] 

1773 

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

1775 # add these here. 

1776 metadata = tuple(metadata) + ( 

1777 gapic_v1.routing_header.to_grpc_metadata( 

1778 (("subscription", request.subscription),) 

1779 ), 

1780 ) 

1781 

1782 # Validate the universe domain. 

1783 self._validate_universe_domain() 

1784 

1785 # Send the request. 

1786 response = rpc( 

1787 request, 

1788 retry=retry, 

1789 timeout=timeout, 

1790 metadata=metadata, 

1791 ) 

1792 

1793 # Done; return the response. 

1794 return response 

1795 

1796 def __enter__(self) -> "PublisherClient": 

1797 return self 

1798 

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

1800 """Releases underlying transport's resources. 

1801 

1802 .. warning:: 

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

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

1805 and may cause errors in other clients! 

1806 """ 

1807 self.transport.close() 

1808 

1809 def set_iam_policy( 

1810 self, 

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

1812 *, 

1813 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1814 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1816 ) -> policy_pb2.Policy: 

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

1818 

1819 Replaces any existing policy. 

1820 

1821 Args: 

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

1823 The request object. Request message for `SetIamPolicy` 

1824 method. 

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

1826 should be retried. 

1827 timeout (TimeoutType): 

1828 The timeout for this request. 

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

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

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

1832 be of type `bytes`. 

1833 Returns: 

1834 ~.policy_pb2.Policy: 

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

1836 It is used to specify access control policies for Cloud 

1837 Platform resources. 

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

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

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

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

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

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

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

1845 expression that further constrains the role binding 

1846 based on attributes about the request and/or target 

1847 resource. 

1848 

1849 **JSON Example** 

1850 

1851 :: 

1852 

1853 { 

1854 "bindings": [ 

1855 { 

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

1857 "members": [ 

1858 "user:mike@example.com", 

1859 "group:admins@example.com", 

1860 "domain:google.com", 

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

1862 ] 

1863 }, 

1864 { 

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

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

1867 "condition": { 

1868 "title": "expirable access", 

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

1870 "expression": "request.time < 

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

1872 } 

1873 } 

1874 ] 

1875 } 

1876 

1877 **YAML Example** 

1878 

1879 :: 

1880 

1881 bindings: 

1882 - members: 

1883 - user:mike@example.com 

1884 - group:admins@example.com 

1885 - domain:google.com 

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

1887 role: roles/resourcemanager.organizationAdmin 

1888 - members: 

1889 - user:eve@example.com 

1890 role: roles/resourcemanager.organizationViewer 

1891 condition: 

1892 title: expirable access 

1893 description: Does not grant access after Sep 2020 

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

1895 

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

1897 developer's 

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

1899 """ 

1900 # Create or coerce a protobuf request object. 

1901 

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

1903 # so it must be constructed via keyword expansion. 

1904 if isinstance(request, dict): 

1905 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

1906 

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

1908 # and friendly error handling. 

1909 rpc = self._transport._wrapped_methods[self._transport.set_iam_policy] 

1910 

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

1912 # add these here. 

1913 metadata = tuple(metadata) + ( 

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

1915 ) 

1916 

1917 # Validate the universe domain. 

1918 self._validate_universe_domain() 

1919 

1920 try: 

1921 # Send the request. 

1922 response = rpc( 

1923 request, 

1924 retry=retry, 

1925 timeout=timeout, 

1926 metadata=metadata, 

1927 ) 

1928 

1929 # Done; return the response. 

1930 return response 

1931 except core_exceptions.GoogleAPICallError as e: 

1932 self._add_cred_info_for_auth_errors(e) 

1933 raise e 

1934 

1935 def get_iam_policy( 

1936 self, 

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

1938 *, 

1939 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1940 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1942 ) -> policy_pb2.Policy: 

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

1944 

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

1946 policy set. 

1947 

1948 Args: 

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

1950 The request object. Request message for `GetIamPolicy` 

1951 method. 

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

1953 any, should be retried. 

1954 timeout (TimeoutType): 

1955 The timeout for this request. 

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

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

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

1959 be of type `bytes`. 

1960 Returns: 

1961 ~.policy_pb2.Policy: 

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

1963 It is used to specify access control policies for Cloud 

1964 Platform resources. 

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

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

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

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

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

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

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

1972 expression that further constrains the role binding 

1973 based on attributes about the request and/or target 

1974 resource. 

1975 

1976 **JSON Example** 

1977 

1978 :: 

1979 

1980 { 

1981 "bindings": [ 

1982 { 

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

1984 "members": [ 

1985 "user:mike@example.com", 

1986 "group:admins@example.com", 

1987 "domain:google.com", 

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

1989 ] 

1990 }, 

1991 { 

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

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

1994 "condition": { 

1995 "title": "expirable access", 

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

1997 "expression": "request.time < 

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

1999 } 

2000 } 

2001 ] 

2002 } 

2003 

2004 **YAML Example** 

2005 

2006 :: 

2007 

2008 bindings: 

2009 - members: 

2010 - user:mike@example.com 

2011 - group:admins@example.com 

2012 - domain:google.com 

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

2014 role: roles/resourcemanager.organizationAdmin 

2015 - members: 

2016 - user:eve@example.com 

2017 role: roles/resourcemanager.organizationViewer 

2018 condition: 

2019 title: expirable access 

2020 description: Does not grant access after Sep 2020 

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

2022 

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

2024 developer's 

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

2026 """ 

2027 # Create or coerce a protobuf request object. 

2028 

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

2030 # so it must be constructed via keyword expansion. 

2031 if isinstance(request, dict): 

2032 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

2033 

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

2035 # and friendly error handling. 

2036 rpc = self._transport._wrapped_methods[self._transport.get_iam_policy] 

2037 

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

2039 # add these here. 

2040 metadata = tuple(metadata) + ( 

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

2042 ) 

2043 

2044 # Validate the universe domain. 

2045 self._validate_universe_domain() 

2046 

2047 try: 

2048 # Send the request. 

2049 response = rpc( 

2050 request, 

2051 retry=retry, 

2052 timeout=timeout, 

2053 metadata=metadata, 

2054 ) 

2055 

2056 # Done; return the response. 

2057 return response 

2058 except core_exceptions.GoogleAPICallError as e: 

2059 self._add_cred_info_for_auth_errors(e) 

2060 raise e 

2061 

2062 def test_iam_permissions( 

2063 self, 

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

2065 *, 

2066 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2067 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

2069 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

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

2071 policy for a function. 

2072 

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

2074 of permissions, not a NOT_FOUND error. 

2075 

2076 Args: 

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

2078 The request object. Request message for 

2079 `TestIamPermissions` method. 

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

2081 if any, should be retried. 

2082 timeout (TimeoutType): 

2083 The timeout for this request. 

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

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

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

2087 be of type `bytes`. 

2088 Returns: 

2089 ~.iam_policy_pb2.TestIamPermissionsResponse: 

2090 Response message for ``TestIamPermissions`` method. 

2091 """ 

2092 # Create or coerce a protobuf request object. 

2093 

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

2095 # so it must be constructed via keyword expansion. 

2096 if isinstance(request, dict): 

2097 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

2098 

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

2100 # and friendly error handling. 

2101 rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions] 

2102 

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

2104 # add these here. 

2105 metadata = tuple(metadata) + ( 

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

2107 ) 

2108 

2109 # Validate the universe domain. 

2110 self._validate_universe_domain() 

2111 

2112 try: 

2113 # Send the request. 

2114 response = rpc( 

2115 request, 

2116 retry=retry, 

2117 timeout=timeout, 

2118 metadata=metadata, 

2119 ) 

2120 

2121 # Done; return the response. 

2122 return response 

2123 except core_exceptions.GoogleAPICallError as e: 

2124 self._add_cred_info_for_auth_errors(e) 

2125 raise e 

2126 

2127 

2128DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

2129 client_library_version=package_version.__version__ 

2130) 

2131 

2132 

2133__all__ = ("PublisherClient",)