Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/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

424 statements  

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

2# Copyright 2025 Google LLC 

3# 

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

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

6# You may obtain a copy of the License at 

7# 

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

9# 

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

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

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

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

14# limitations under the License. 

15# 

16from collections import OrderedDict 

17from http import HTTPStatus 

18import json 

19import logging as std_logging 

20import functools 

21import os 

22import re 

23from typing import ( 

24 Dict, 

25 Callable, 

26 Mapping, 

27 MutableMapping, 

28 MutableSequence, 

29 Optional, 

30 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 

50import google.protobuf 

51 

52try: 

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

54except AttributeError: # pragma: NO COVER 

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

56 

57try: 

58 from google.api_core import client_logging # type: ignore 

59 

60 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

61except ImportError: # pragma: NO COVER 

62 CLIENT_LOGGING_SUPPORTED = False 

63 

64_LOGGER = std_logging.getLogger(__name__) 

65 

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

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

68from google.protobuf import duration_pb2 # type: ignore 

69from google.protobuf import field_mask_pb2 # type: ignore 

70from google.pubsub_v1.services.publisher import pagers 

71from google.pubsub_v1.types import pubsub 

72from google.pubsub_v1.types import TimeoutType 

73 

74import grpc 

75from .transports.base import PublisherTransport, DEFAULT_CLIENT_INFO 

76from .transports.grpc import PublisherGrpcTransport 

77from .transports.grpc_asyncio import PublisherGrpcAsyncIOTransport 

78from .transports.rest import PublisherRestTransport 

79 

80 

81class PublisherClientMeta(type): 

82 """Metaclass for the Publisher client. 

83 

84 This provides class-level methods for building and retrieving 

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

86 objects. 

87 """ 

88 

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

90 _transport_registry["grpc"] = PublisherGrpcTransport 

91 _transport_registry["grpc_asyncio"] = PublisherGrpcAsyncIOTransport 

92 _transport_registry["rest"] = PublisherRestTransport 

93 

94 def get_transport_class( 

95 cls, 

96 label: Optional[str] = None, 

97 ) -> Type[PublisherTransport]: 

98 """Returns an appropriate transport class. 

99 

100 Args: 

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

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

103 

104 Returns: 

105 The transport class to use. 

106 """ 

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

108 if label: 

109 return cls._transport_registry[label] 

110 

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

112 # in the dictionary). 

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

114 

115 

116class PublisherClient(metaclass=PublisherClientMeta): 

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

118 and to send messages to a topic. 

119 """ 

120 

121 @staticmethod 

122 def _get_default_mtls_endpoint(api_endpoint): 

123 """Converts api endpoint to mTLS endpoint. 

124 

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

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

127 Args: 

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

129 Returns: 

130 str: converted mTLS api endpoint. 

131 """ 

132 if not api_endpoint: 

133 return api_endpoint 

134 

135 mtls_endpoint_re = re.compile( 

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

137 ) 

138 

139 m = mtls_endpoint_re.match(api_endpoint) 

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

141 if mtls or not googledomain: 

142 return api_endpoint 

143 

144 if sandbox: 

145 return api_endpoint.replace( 

146 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

147 ) 

148 

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

150 

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

152 

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

154 # this service 

155 _DEFAULT_SCOPES = ( 

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

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

158 ) 

159 

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

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

162 

163 DEFAULT_ENDPOINT = "pubsub.googleapis.com" 

164 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

165 DEFAULT_ENDPOINT 

166 ) 

167 

168 _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}" 

169 _DEFAULT_UNIVERSE = "googleapis.com" 

170 

171 @classmethod 

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

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

174 info. 

175 

176 Args: 

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

178 args: Additional arguments to pass to the constructor. 

179 kwargs: Additional arguments to pass to the constructor. 

180 

181 Returns: 

182 PublisherClient: The constructed client. 

183 """ 

184 credentials = service_account.Credentials.from_service_account_info(info) 

185 kwargs["credentials"] = credentials 

186 return cls(*args, **kwargs) 

187 

188 @classmethod 

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

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

191 file. 

192 

193 Args: 

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

195 file. 

196 args: Additional arguments to pass to the constructor. 

197 kwargs: Additional arguments to pass to the constructor. 

198 

199 Returns: 

200 PublisherClient: The constructed client. 

201 """ 

202 credentials = service_account.Credentials.from_service_account_file(filename) 

203 kwargs["credentials"] = credentials 

204 return cls(*args, **kwargs) 

205 

206 from_service_account_json = from_service_account_file 

207 

208 @property 

209 def transport(self) -> PublisherTransport: 

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

211 

212 Returns: 

213 PublisherTransport: The transport used by the client 

214 instance. 

215 """ 

216 return self._transport 

217 

218 @staticmethod 

219 def schema_path( 

220 project: str, 

221 schema: str, 

222 ) -> str: 

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

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

225 project=project, 

226 schema=schema, 

227 ) 

228 

229 @staticmethod 

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

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

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

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

234 

235 @staticmethod 

236 def subscription_path( 

237 project: str, 

238 subscription: str, 

239 ) -> str: 

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

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

242 project=project, 

243 subscription=subscription, 

244 ) 

245 

246 @staticmethod 

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

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

249 m = re.match( 

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

251 ) 

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

253 

254 @staticmethod 

255 def topic_path( 

256 project: str, 

257 topic: str, 

258 ) -> str: 

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

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

261 project=project, 

262 topic=topic, 

263 ) 

264 

265 @staticmethod 

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

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

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

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

270 

271 @staticmethod 

272 def common_billing_account_path( 

273 billing_account: str, 

274 ) -> str: 

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

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

277 billing_account=billing_account, 

278 ) 

279 

280 @staticmethod 

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

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

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

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

285 

286 @staticmethod 

287 def common_folder_path( 

288 folder: str, 

289 ) -> str: 

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

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

292 folder=folder, 

293 ) 

294 

295 @staticmethod 

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

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

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

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

300 

301 @staticmethod 

302 def common_organization_path( 

303 organization: str, 

304 ) -> str: 

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

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

307 organization=organization, 

308 ) 

309 

310 @staticmethod 

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

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

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

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

315 

316 @staticmethod 

317 def common_project_path( 

318 project: str, 

319 ) -> str: 

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

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

322 project=project, 

323 ) 

324 

325 @staticmethod 

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

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

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

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

330 

331 @staticmethod 

332 def common_location_path( 

333 project: str, 

334 location: str, 

335 ) -> str: 

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

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

338 project=project, 

339 location=location, 

340 ) 

341 

342 @staticmethod 

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

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

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

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

347 

348 @classmethod 

349 def get_mtls_endpoint_and_cert_source( 

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

351 ): 

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

353 

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

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

356 client cert source is None. 

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

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

359 source is None. 

360 

361 The API endpoint is determined in the following order: 

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

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

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

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

366 use the default API endpoint. 

367 

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

369 

370 Args: 

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

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

373 in this method. 

374 

375 Returns: 

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

377 client cert source to use. 

378 

379 Raises: 

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

381 """ 

382 

383 warnings.warn( 

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

385 DeprecationWarning, 

386 ) 

387 if client_options is None: 

388 client_options = client_options_lib.ClientOptions() 

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

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

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

392 raise ValueError( 

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

394 ) 

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

396 raise MutualTLSChannelError( 

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

398 ) 

399 

400 # Figure out the client cert source to use. 

401 client_cert_source = None 

402 if use_client_cert == "true": 

403 if client_options.client_cert_source: 

404 client_cert_source = client_options.client_cert_source 

405 elif mtls.has_default_client_cert_source(): 

406 client_cert_source = mtls.default_client_cert_source() 

407 

408 # Figure out which api endpoint to use. 

409 if client_options.api_endpoint is not None: 

410 api_endpoint = client_options.api_endpoint 

411 elif use_mtls_endpoint == "always" or ( 

412 use_mtls_endpoint == "auto" and client_cert_source 

413 ): 

414 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

415 else: 

416 api_endpoint = cls.DEFAULT_ENDPOINT 

417 

418 return api_endpoint, client_cert_source 

419 

420 @staticmethod 

421 def _read_environment_variables(): 

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

423 

424 Returns: 

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

426 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. 

427 

428 Raises: 

429 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not 

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

431 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT 

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

433 """ 

434 use_client_cert = os.getenv( 

435 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" 

436 ).lower() 

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

438 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") 

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

440 raise ValueError( 

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

442 ) 

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

444 raise MutualTLSChannelError( 

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

446 ) 

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

448 

449 @staticmethod 

450 def _get_client_cert_source(provided_cert_source, use_cert_flag): 

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

452 

453 Args: 

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

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

456 

457 Returns: 

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

459 """ 

460 client_cert_source = None 

461 if use_cert_flag: 

462 if provided_cert_source: 

463 client_cert_source = provided_cert_source 

464 elif mtls.has_default_client_cert_source(): 

465 client_cert_source = mtls.default_client_cert_source() 

466 return client_cert_source 

467 

468 @staticmethod 

469 def _get_api_endpoint( 

470 api_override, client_cert_source, universe_domain, use_mtls_endpoint 

471 ): 

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

473 

474 Args: 

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

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

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

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

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

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

481 

482 Returns: 

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

484 """ 

485 if api_override is not None: 

486 api_endpoint = api_override 

487 elif use_mtls_endpoint == "always" or ( 

488 use_mtls_endpoint == "auto" and client_cert_source 

489 ): 

490 _default_universe = PublisherClient._DEFAULT_UNIVERSE 

491 if universe_domain != _default_universe: 

492 raise MutualTLSChannelError( 

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

494 ) 

495 api_endpoint = PublisherClient.DEFAULT_MTLS_ENDPOINT 

496 else: 

497 api_endpoint = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE.format( 

498 UNIVERSE_DOMAIN=universe_domain 

499 ) 

500 return api_endpoint 

501 

502 @staticmethod 

503 def _get_universe_domain( 

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

505 ) -> str: 

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

507 

508 Args: 

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

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

511 

512 Returns: 

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

514 

515 Raises: 

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

517 """ 

518 universe_domain = PublisherClient._DEFAULT_UNIVERSE 

519 if client_universe_domain is not None: 

520 universe_domain = client_universe_domain 

521 elif universe_domain_env is not None: 

522 universe_domain = universe_domain_env 

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

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

525 return universe_domain 

526 

527 def _validate_universe_domain(self): 

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

529 

530 Returns: 

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

532 

533 Raises: 

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

535 """ 

536 

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

538 return True 

539 

540 def _add_cred_info_for_auth_errors( 

541 self, error: core_exceptions.GoogleAPICallError 

542 ) -> None: 

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

544 

545 Args: 

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

547 """ 

548 if error.code not in [ 

549 HTTPStatus.UNAUTHORIZED, 

550 HTTPStatus.FORBIDDEN, 

551 HTTPStatus.NOT_FOUND, 

552 ]: 

553 return 

554 

555 cred = self._transport._credentials 

556 

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

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

559 return 

560 

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

562 # is not available 

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

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

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

566 

567 @property 

568 def api_endpoint(self): 

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

570 

571 Returns: 

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

573 """ 

574 return self._api_endpoint 

575 

576 @property 

577 def universe_domain(self) -> str: 

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

579 

580 Returns: 

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

582 """ 

583 return self._universe_domain 

584 

585 def __init__( 

586 self, 

587 *, 

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

589 transport: Optional[ 

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

591 ] = None, 

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

593 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

594 ) -> None: 

595 """Instantiates the publisher client. 

596 

597 Args: 

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

599 authorization credentials to attach to requests. These 

600 credentials identify the application to the service; if none 

601 are specified, the client will attempt to ascertain the 

602 credentials from the environment. 

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

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

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

606 arguments as used in the PublisherTransport constructor. 

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

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

609 Custom options for the client. 

610 

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

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

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

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

615 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

616 variable, which have one of the following values: 

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

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

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

620 the default value). 

621 

622 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

624 to provide a client certificate for mTLS transport. If 

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

626 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

627 set, no client certificate will be used. 

628 

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

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

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

632 currently not supported for mTLS. 

633 

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

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

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

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

638 your own client library. 

639 

640 Raises: 

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

642 creation failed for any reason. 

643 """ 

644 self._client_options = client_options 

645 if isinstance(self._client_options, dict): 

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

647 if self._client_options is None: 

648 self._client_options = client_options_lib.ClientOptions() 

649 self._client_options = cast( 

650 client_options_lib.ClientOptions, self._client_options 

651 ) 

652 

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

654 

655 ( 

656 self._use_client_cert, 

657 self._use_mtls_endpoint, 

658 self._universe_domain_env, 

659 ) = PublisherClient._read_environment_variables() 

660 self._client_cert_source = PublisherClient._get_client_cert_source( 

661 self._client_options.client_cert_source, self._use_client_cert 

662 ) 

663 self._universe_domain = PublisherClient._get_universe_domain( 

664 universe_domain_opt, self._universe_domain_env 

665 ) 

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

667 

668 # Initialize the universe domain validation. 

669 self._is_universe_domain_valid = False 

670 

671 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER 

672 # Setup logging. 

673 client_logging.initialize_logging() 

674 

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

676 if api_key_value and credentials: 

677 raise ValueError( 

678 "client_options.api_key and credentials are mutually exclusive" 

679 ) 

680 

681 # Save or instantiate the transport. 

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

683 # instance provides an extensibility point for unusual situations. 

684 transport_provided = isinstance(transport, PublisherTransport) 

685 if transport_provided: 

686 # transport is a PublisherTransport instance. 

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

688 raise ValueError( 

689 "When providing a transport instance, " 

690 "provide its credentials directly." 

691 ) 

692 if self._client_options.scopes: 

693 raise ValueError( 

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

695 "directly." 

696 ) 

697 self._transport = cast(PublisherTransport, transport) 

698 self._api_endpoint = self._transport.host 

699 

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

701 self._client_options.api_endpoint, 

702 self._client_cert_source, 

703 self._universe_domain, 

704 self._use_mtls_endpoint, 

705 ) 

706 

707 if not transport_provided: 

708 import google.auth._default # type: ignore 

709 

710 if api_key_value and hasattr( 

711 google.auth._default, "get_api_key_credentials" 

712 ): 

713 credentials = google.auth._default.get_api_key_credentials( 

714 api_key_value 

715 ) 

716 

717 transport_init: Union[ 

718 Type[PublisherTransport], Callable[..., PublisherTransport] 

719 ] = ( 

720 PublisherClient.get_transport_class(transport) 

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

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

723 ) 

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

725 

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

727 if emulator_host: 

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

729 channel = grpc.insecure_channel(target=emulator_host) 

730 else: 

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

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

733 

734 self._transport = transport_init( 

735 credentials=credentials, 

736 credentials_file=self._client_options.credentials_file, 

737 host=self._api_endpoint, 

738 scopes=self._client_options.scopes, 

739 client_cert_source_for_mtls=self._client_cert_source, 

740 quota_project_id=self._client_options.quota_project_id, 

741 client_info=client_info, 

742 always_use_jwt_access=True, 

743 api_audience=self._client_options.api_audience, 

744 ) 

745 

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

747 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

748 std_logging.DEBUG 

749 ): # pragma: NO COVER 

750 _LOGGER.debug( 

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

752 extra={ 

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

754 "universeDomain": getattr( 

755 self._transport._credentials, "universe_domain", "" 

756 ), 

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

758 "credentialsInfo": getattr( 

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

760 )(), 

761 } 

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

763 else { 

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

765 "credentialsType": None, 

766 }, 

767 ) 

768 

769 def create_topic( 

770 self, 

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

772 *, 

773 name: Optional[str] = None, 

774 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

775 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

777 ) -> pubsub.Topic: 

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

779 name rules] 

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

781 

782 .. code-block:: python 

783 

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

785 # code template only. 

786 # It will require modifications to work: 

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

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

789 # client as shown in: 

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

791 from google import pubsub_v1 

792 

793 def sample_create_topic(): 

794 # Create a client 

795 client = pubsub_v1.PublisherClient() 

796 

797 # Initialize request argument(s) 

798 request = pubsub_v1.Topic( 

799 name="name_value", 

800 ) 

801 

802 # Make the request 

803 response = client.create_topic(request=request) 

804 

805 # Handle the response 

806 print(response) 

807 

808 Args: 

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

810 The request object. A topic resource. 

811 name (str): 

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

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

814 must start with a letter, and contain only letters 

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

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

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

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

819 start with ``"goog"``. 

820 

821 This corresponds to the ``name`` field 

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

823 should not be set. 

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

825 should be retried. 

826 timeout (TimeoutType): 

827 The timeout for this request. 

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

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

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

831 be of type `bytes`. 

832 

833 Returns: 

834 google.pubsub_v1.types.Topic: 

835 A topic resource. 

836 """ 

837 # Create or coerce a protobuf request object. 

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

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

840 flattened_params = [name] 

841 has_flattened_params = ( 

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

843 ) 

844 if request is not None and has_flattened_params: 

845 raise ValueError( 

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

847 "the individual field arguments should be set." 

848 ) 

849 

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

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

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

853 request = pubsub.Topic(request) 

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

855 # request, apply these. 

856 if name is not None: 

857 request.name = name 

858 

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

860 # and friendly error handling. 

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

862 

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

864 # add these here. 

865 metadata = tuple(metadata) + ( 

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

867 ) 

868 

869 # Validate the universe domain. 

870 self._validate_universe_domain() 

871 

872 # Send the request. 

873 response = rpc( 

874 request, 

875 retry=retry, 

876 timeout=timeout, 

877 metadata=metadata, 

878 ) 

879 

880 # Done; return the response. 

881 return response 

882 

883 def update_topic( 

884 self, 

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

886 *, 

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

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

889 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

890 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

892 ) -> pubsub.Topic: 

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

894 specified in the update mask. Note that certain 

895 properties of a topic are not modifiable. 

896 

897 .. code-block:: python 

898 

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

900 # code template only. 

901 # It will require modifications to work: 

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

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

904 # client as shown in: 

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

906 from google import pubsub_v1 

907 

908 def sample_update_topic(): 

909 # Create a client 

910 client = pubsub_v1.PublisherClient() 

911 

912 # Initialize request argument(s) 

913 topic = pubsub_v1.Topic() 

914 topic.name = "name_value" 

915 

916 request = pubsub_v1.UpdateTopicRequest( 

917 topic=topic, 

918 ) 

919 

920 # Make the request 

921 response = client.update_topic(request=request) 

922 

923 # Handle the response 

924 print(response) 

925 

926 Args: 

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

928 The request object. Request for the UpdateTopic method. 

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

930 Required. The updated topic object. 

931 This corresponds to the ``topic`` field 

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

933 should not be set. 

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

935 Required. Indicates which fields in the provided topic 

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

937 ``update_mask`` contains "message_storage_policy" but 

938 the ``message_storage_policy`` is not set in the 

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

940 determined by the policy configured at the project or 

941 organization level. 

942 

943 This corresponds to the ``update_mask`` field 

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

945 should not be set. 

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

947 should be retried. 

948 timeout (TimeoutType): 

949 The timeout for this request. 

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

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

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

953 be of type `bytes`. 

954 

955 Returns: 

956 google.pubsub_v1.types.Topic: 

957 A topic resource. 

958 """ 

959 # Create or coerce a protobuf request object. 

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

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

962 flattened_params = [topic, update_mask] 

963 has_flattened_params = ( 

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

965 ) 

966 if request is not None and has_flattened_params: 

967 raise ValueError( 

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

969 "the individual field arguments should be set." 

970 ) 

971 

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

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

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

975 request = pubsub.UpdateTopicRequest(request) 

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

977 # request, apply these. 

978 if topic is not None: 

979 request.topic = topic 

980 if update_mask is not None: 

981 request.update_mask = update_mask 

982 

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

984 # and friendly error handling. 

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

986 

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

988 # add these here. 

989 metadata = tuple(metadata) + ( 

990 gapic_v1.routing_header.to_grpc_metadata( 

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

992 ), 

993 ) 

994 

995 # Validate the universe domain. 

996 self._validate_universe_domain() 

997 

998 # Send the request. 

999 response = rpc( 

1000 request, 

1001 retry=retry, 

1002 timeout=timeout, 

1003 metadata=metadata, 

1004 ) 

1005 

1006 # Done; return the response. 

1007 return response 

1008 

1009 def publish( 

1010 self, 

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

1012 *, 

1013 topic: Optional[str] = None, 

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

1015 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1016 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1018 ) -> pubsub.PublishResponse: 

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

1020 the topic does not exist. 

1021 

1022 .. code-block:: python 

1023 

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

1025 # code template only. 

1026 # It will require modifications to work: 

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

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

1029 # client as shown in: 

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

1031 from google import pubsub_v1 

1032 

1033 def sample_publish(): 

1034 # Create a client 

1035 client = pubsub_v1.PublisherClient() 

1036 

1037 # Initialize request argument(s) 

1038 request = pubsub_v1.PublishRequest( 

1039 topic="topic_value", 

1040 ) 

1041 

1042 # Make the request 

1043 response = client.publish(request=request) 

1044 

1045 # Handle the response 

1046 print(response) 

1047 

1048 Args: 

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

1050 The request object. Request for the Publish method. 

1051 topic (str): 

1052 Required. The messages in the request will be published 

1053 on this topic. Format is 

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

1055 

1056 This corresponds to the ``topic`` field 

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

1058 should not be set. 

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

1060 Required. The messages to publish. 

1061 This corresponds to the ``messages`` field 

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

1063 should not be set. 

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

1065 should be retried. 

1066 timeout (TimeoutType): 

1067 The timeout for this request. 

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

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

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

1071 be of type `bytes`. 

1072 

1073 Returns: 

1074 google.pubsub_v1.types.PublishResponse: 

1075 Response for the Publish method. 

1076 """ 

1077 # Create or coerce a protobuf request object. 

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

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

1080 flattened_params = [topic, messages] 

1081 has_flattened_params = ( 

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

1083 ) 

1084 if request is not None and has_flattened_params: 

1085 raise ValueError( 

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

1087 "the individual field arguments should be set." 

1088 ) 

1089 

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

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

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

1093 request = pubsub.PublishRequest(request) 

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

1095 # request, apply these. 

1096 if topic is not None: 

1097 request.topic = topic 

1098 if messages is not None: 

1099 request.messages = messages 

1100 

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

1102 # and friendly error handling. 

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

1104 

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

1106 # add these here. 

1107 metadata = tuple(metadata) + ( 

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

1109 ) 

1110 

1111 # Validate the universe domain. 

1112 self._validate_universe_domain() 

1113 

1114 # Send the request. 

1115 response = rpc( 

1116 request, 

1117 retry=retry, 

1118 timeout=timeout, 

1119 metadata=metadata, 

1120 ) 

1121 

1122 # Done; return the response. 

1123 return response 

1124 

1125 def get_topic( 

1126 self, 

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

1128 *, 

1129 topic: Optional[str] = None, 

1130 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1131 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1133 ) -> pubsub.Topic: 

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

1135 

1136 .. code-block:: python 

1137 

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

1139 # code template only. 

1140 # It will require modifications to work: 

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

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

1143 # client as shown in: 

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

1145 from google import pubsub_v1 

1146 

1147 def sample_get_topic(): 

1148 # Create a client 

1149 client = pubsub_v1.PublisherClient() 

1150 

1151 # Initialize request argument(s) 

1152 request = pubsub_v1.GetTopicRequest( 

1153 topic="topic_value", 

1154 ) 

1155 

1156 # Make the request 

1157 response = client.get_topic(request=request) 

1158 

1159 # Handle the response 

1160 print(response) 

1161 

1162 Args: 

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

1164 The request object. Request for the GetTopic method. 

1165 topic (str): 

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

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

1168 

1169 This corresponds to the ``topic`` field 

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

1171 should not be set. 

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

1173 should be retried. 

1174 timeout (TimeoutType): 

1175 The timeout for this request. 

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

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

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

1179 be of type `bytes`. 

1180 

1181 Returns: 

1182 google.pubsub_v1.types.Topic: 

1183 A topic resource. 

1184 """ 

1185 # Create or coerce a protobuf request object. 

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

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

1188 flattened_params = [topic] 

1189 has_flattened_params = ( 

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

1191 ) 

1192 if request is not None and has_flattened_params: 

1193 raise ValueError( 

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

1195 "the individual field arguments should be set." 

1196 ) 

1197 

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

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

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

1201 request = pubsub.GetTopicRequest(request) 

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

1203 # request, apply these. 

1204 if topic is not None: 

1205 request.topic = topic 

1206 

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

1208 # and friendly error handling. 

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

1210 

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

1212 # add these here. 

1213 metadata = tuple(metadata) + ( 

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

1215 ) 

1216 

1217 # Validate the universe domain. 

1218 self._validate_universe_domain() 

1219 

1220 # Send the request. 

1221 response = rpc( 

1222 request, 

1223 retry=retry, 

1224 timeout=timeout, 

1225 metadata=metadata, 

1226 ) 

1227 

1228 # Done; return the response. 

1229 return response 

1230 

1231 def list_topics( 

1232 self, 

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

1234 *, 

1235 project: Optional[str] = None, 

1236 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1237 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1239 ) -> pagers.ListTopicsPager: 

1240 r"""Lists matching topics. 

1241 

1242 .. code-block:: python 

1243 

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

1245 # code template only. 

1246 # It will require modifications to work: 

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

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

1249 # client as shown in: 

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

1251 from google import pubsub_v1 

1252 

1253 def sample_list_topics(): 

1254 # Create a client 

1255 client = pubsub_v1.PublisherClient() 

1256 

1257 # Initialize request argument(s) 

1258 request = pubsub_v1.ListTopicsRequest( 

1259 project="project_value", 

1260 ) 

1261 

1262 # Make the request 

1263 page_result = client.list_topics(request=request) 

1264 

1265 # Handle the response 

1266 for response in page_result: 

1267 print(response) 

1268 

1269 Args: 

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

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

1272 project (str): 

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

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

1275 

1276 This corresponds to the ``project`` field 

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

1278 should not be set. 

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

1280 should be retried. 

1281 timeout (TimeoutType): 

1282 The timeout for this request. 

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

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

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

1286 be of type `bytes`. 

1287 

1288 Returns: 

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

1290 Response for the ListTopics method. 

1291 

1292 Iterating over this object will yield results and 

1293 resolve additional pages automatically. 

1294 

1295 """ 

1296 # Create or coerce a protobuf request object. 

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

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

1299 flattened_params = [project] 

1300 has_flattened_params = ( 

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

1302 ) 

1303 if request is not None and has_flattened_params: 

1304 raise ValueError( 

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

1306 "the individual field arguments should be set." 

1307 ) 

1308 

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

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

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

1312 request = pubsub.ListTopicsRequest(request) 

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

1314 # request, apply these. 

1315 if project is not None: 

1316 request.project = project 

1317 

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

1319 # and friendly error handling. 

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

1321 

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

1323 # add these here. 

1324 metadata = tuple(metadata) + ( 

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

1326 ) 

1327 

1328 # Validate the universe domain. 

1329 self._validate_universe_domain() 

1330 

1331 # Send the request. 

1332 response = rpc( 

1333 request, 

1334 retry=retry, 

1335 timeout=timeout, 

1336 metadata=metadata, 

1337 ) 

1338 

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

1340 # an `__iter__` convenience method. 

1341 response = pagers.ListTopicsPager( 

1342 method=rpc, 

1343 request=request, 

1344 response=response, 

1345 retry=retry, 

1346 timeout=timeout, 

1347 metadata=metadata, 

1348 ) 

1349 

1350 # Done; return the response. 

1351 return response 

1352 

1353 def list_topic_subscriptions( 

1354 self, 

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

1356 *, 

1357 topic: Optional[str] = None, 

1358 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1359 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1361 ) -> pagers.ListTopicSubscriptionsPager: 

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

1363 topic. 

1364 

1365 .. code-block:: python 

1366 

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

1368 # code template only. 

1369 # It will require modifications to work: 

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

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

1372 # client as shown in: 

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

1374 from google import pubsub_v1 

1375 

1376 def sample_list_topic_subscriptions(): 

1377 # Create a client 

1378 client = pubsub_v1.PublisherClient() 

1379 

1380 # Initialize request argument(s) 

1381 request = pubsub_v1.ListTopicSubscriptionsRequest( 

1382 topic="topic_value", 

1383 ) 

1384 

1385 # Make the request 

1386 page_result = client.list_topic_subscriptions(request=request) 

1387 

1388 # Handle the response 

1389 for response in page_result: 

1390 print(response) 

1391 

1392 Args: 

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

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

1395 topic (str): 

1396 Required. The name of the topic that subscriptions are 

1397 attached to. Format is 

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

1399 

1400 This corresponds to the ``topic`` field 

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

1402 should not be set. 

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

1404 should be retried. 

1405 timeout (TimeoutType): 

1406 The timeout for this request. 

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

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

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

1410 be of type `bytes`. 

1411 

1412 Returns: 

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

1414 Response for the ListTopicSubscriptions method. 

1415 

1416 Iterating over this object will yield results and 

1417 resolve additional pages automatically. 

1418 

1419 """ 

1420 # Create or coerce a protobuf request object. 

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

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

1423 flattened_params = [topic] 

1424 has_flattened_params = ( 

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

1426 ) 

1427 if request is not None and has_flattened_params: 

1428 raise ValueError( 

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

1430 "the individual field arguments should be set." 

1431 ) 

1432 

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

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

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

1436 request = pubsub.ListTopicSubscriptionsRequest(request) 

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

1438 # request, apply these. 

1439 if topic is not None: 

1440 request.topic = topic 

1441 

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

1443 # and friendly error handling. 

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

1445 

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

1447 # add these here. 

1448 metadata = tuple(metadata) + ( 

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

1450 ) 

1451 

1452 # Validate the universe domain. 

1453 self._validate_universe_domain() 

1454 

1455 # Send the request. 

1456 response = rpc( 

1457 request, 

1458 retry=retry, 

1459 timeout=timeout, 

1460 metadata=metadata, 

1461 ) 

1462 

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

1464 # an `__iter__` convenience method. 

1465 response = pagers.ListTopicSubscriptionsPager( 

1466 method=rpc, 

1467 request=request, 

1468 response=response, 

1469 retry=retry, 

1470 timeout=timeout, 

1471 metadata=metadata, 

1472 ) 

1473 

1474 # Done; return the response. 

1475 return response 

1476 

1477 def list_topic_snapshots( 

1478 self, 

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

1480 *, 

1481 topic: Optional[str] = None, 

1482 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1483 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1485 ) -> pagers.ListTopicSnapshotsPager: 

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

1487 used in 

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

1489 operations, which allow you to manage message acknowledgments in 

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

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

1492 

1493 .. code-block:: python 

1494 

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

1496 # code template only. 

1497 # It will require modifications to work: 

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

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

1500 # client as shown in: 

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

1502 from google import pubsub_v1 

1503 

1504 def sample_list_topic_snapshots(): 

1505 # Create a client 

1506 client = pubsub_v1.PublisherClient() 

1507 

1508 # Initialize request argument(s) 

1509 request = pubsub_v1.ListTopicSnapshotsRequest( 

1510 topic="topic_value", 

1511 ) 

1512 

1513 # Make the request 

1514 page_result = client.list_topic_snapshots(request=request) 

1515 

1516 # Handle the response 

1517 for response in page_result: 

1518 print(response) 

1519 

1520 Args: 

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

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

1523 topic (str): 

1524 Required. The name of the topic that snapshots are 

1525 attached to. Format is 

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

1527 

1528 This corresponds to the ``topic`` field 

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

1530 should not be set. 

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

1532 should be retried. 

1533 timeout (TimeoutType): 

1534 The timeout for this request. 

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

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

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

1538 be of type `bytes`. 

1539 

1540 Returns: 

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

1542 Response for the ListTopicSnapshots method. 

1543 

1544 Iterating over this object will yield results and 

1545 resolve additional pages automatically. 

1546 

1547 """ 

1548 # Create or coerce a protobuf request object. 

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

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

1551 flattened_params = [topic] 

1552 has_flattened_params = ( 

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

1554 ) 

1555 if request is not None and has_flattened_params: 

1556 raise ValueError( 

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

1558 "the individual field arguments should be set." 

1559 ) 

1560 

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

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

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

1564 request = pubsub.ListTopicSnapshotsRequest(request) 

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

1566 # request, apply these. 

1567 if topic is not None: 

1568 request.topic = topic 

1569 

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

1571 # and friendly error handling. 

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

1573 

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

1575 # add these here. 

1576 metadata = tuple(metadata) + ( 

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

1578 ) 

1579 

1580 # Validate the universe domain. 

1581 self._validate_universe_domain() 

1582 

1583 # Send the request. 

1584 response = rpc( 

1585 request, 

1586 retry=retry, 

1587 timeout=timeout, 

1588 metadata=metadata, 

1589 ) 

1590 

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

1592 # an `__iter__` convenience method. 

1593 response = pagers.ListTopicSnapshotsPager( 

1594 method=rpc, 

1595 request=request, 

1596 response=response, 

1597 retry=retry, 

1598 timeout=timeout, 

1599 metadata=metadata, 

1600 ) 

1601 

1602 # Done; return the response. 

1603 return response 

1604 

1605 def delete_topic( 

1606 self, 

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

1608 *, 

1609 topic: Optional[str] = None, 

1610 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1611 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1613 ) -> None: 

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

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

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

1617 with none of the old configuration or subscriptions. Existing 

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

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

1620 

1621 .. code-block:: python 

1622 

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

1624 # code template only. 

1625 # It will require modifications to work: 

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

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

1628 # client as shown in: 

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

1630 from google import pubsub_v1 

1631 

1632 def sample_delete_topic(): 

1633 # Create a client 

1634 client = pubsub_v1.PublisherClient() 

1635 

1636 # Initialize request argument(s) 

1637 request = pubsub_v1.DeleteTopicRequest( 

1638 topic="topic_value", 

1639 ) 

1640 

1641 # Make the request 

1642 client.delete_topic(request=request) 

1643 

1644 Args: 

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

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

1647 topic (str): 

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

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

1650 

1651 This corresponds to the ``topic`` field 

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

1653 should not be set. 

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

1655 should be retried. 

1656 timeout (TimeoutType): 

1657 The timeout for this request. 

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

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

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

1661 be of type `bytes`. 

1662 """ 

1663 # Create or coerce a protobuf request object. 

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

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

1666 flattened_params = [topic] 

1667 has_flattened_params = ( 

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

1669 ) 

1670 if request is not None and has_flattened_params: 

1671 raise ValueError( 

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

1673 "the individual field arguments should be set." 

1674 ) 

1675 

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

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

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

1679 request = pubsub.DeleteTopicRequest(request) 

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

1681 # request, apply these. 

1682 if topic is not None: 

1683 request.topic = topic 

1684 

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

1686 # and friendly error handling. 

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

1688 

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

1690 # add these here. 

1691 metadata = tuple(metadata) + ( 

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

1693 ) 

1694 

1695 # Validate the universe domain. 

1696 self._validate_universe_domain() 

1697 

1698 # Send the request. 

1699 rpc( 

1700 request, 

1701 retry=retry, 

1702 timeout=timeout, 

1703 metadata=metadata, 

1704 ) 

1705 

1706 def detach_subscription( 

1707 self, 

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

1709 *, 

1710 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1711 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1713 ) -> pubsub.DetachSubscriptionResponse: 

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

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

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

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

1718 will stop. 

1719 

1720 .. code-block:: python 

1721 

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

1723 # code template only. 

1724 # It will require modifications to work: 

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

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

1727 # client as shown in: 

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

1729 from google import pubsub_v1 

1730 

1731 def sample_detach_subscription(): 

1732 # Create a client 

1733 client = pubsub_v1.PublisherClient() 

1734 

1735 # Initialize request argument(s) 

1736 request = pubsub_v1.DetachSubscriptionRequest( 

1737 subscription="subscription_value", 

1738 ) 

1739 

1740 # Make the request 

1741 response = client.detach_subscription(request=request) 

1742 

1743 # Handle the response 

1744 print(response) 

1745 

1746 Args: 

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

1748 The request object. Request for the DetachSubscription 

1749 method. 

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

1751 should be retried. 

1752 timeout (TimeoutType): 

1753 The timeout for this request. 

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

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

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

1757 be of type `bytes`. 

1758 

1759 Returns: 

1760 google.pubsub_v1.types.DetachSubscriptionResponse: 

1761 Response for the DetachSubscription 

1762 method. Reserved for future use. 

1763 

1764 """ 

1765 # Create or coerce a protobuf request object. 

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

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

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

1769 request = pubsub.DetachSubscriptionRequest(request) 

1770 

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

1772 # and friendly error handling. 

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

1774 

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

1776 # add these here. 

1777 metadata = tuple(metadata) + ( 

1778 gapic_v1.routing_header.to_grpc_metadata( 

1779 (("subscription", request.subscription),) 

1780 ), 

1781 ) 

1782 

1783 # Validate the universe domain. 

1784 self._validate_universe_domain() 

1785 

1786 # Send the request. 

1787 response = rpc( 

1788 request, 

1789 retry=retry, 

1790 timeout=timeout, 

1791 metadata=metadata, 

1792 ) 

1793 

1794 # Done; return the response. 

1795 return response 

1796 

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

1798 return self 

1799 

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

1801 """Releases underlying transport's resources. 

1802 

1803 .. warning:: 

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

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

1806 and may cause errors in other clients! 

1807 """ 

1808 self.transport.close() 

1809 

1810 def set_iam_policy( 

1811 self, 

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

1813 *, 

1814 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1815 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1817 ) -> policy_pb2.Policy: 

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

1819 

1820 Replaces any existing policy. 

1821 

1822 Args: 

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

1824 The request object. Request message for `SetIamPolicy` 

1825 method. 

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

1827 should be retried. 

1828 timeout (TimeoutType): 

1829 The timeout for this request. 

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

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

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

1833 be of type `bytes`. 

1834 Returns: 

1835 ~.policy_pb2.Policy: 

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

1837 It is used to specify access control policies for Cloud 

1838 Platform resources. 

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

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

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

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

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

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

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

1846 expression that further constrains the role binding 

1847 based on attributes about the request and/or target 

1848 resource. 

1849 

1850 **JSON Example** 

1851 

1852 :: 

1853 

1854 { 

1855 "bindings": [ 

1856 { 

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

1858 "members": [ 

1859 "user:mike@example.com", 

1860 "group:admins@example.com", 

1861 "domain:google.com", 

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

1863 ] 

1864 }, 

1865 { 

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

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

1868 "condition": { 

1869 "title": "expirable access", 

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

1871 "expression": "request.time < 

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

1873 } 

1874 } 

1875 ] 

1876 } 

1877 

1878 **YAML Example** 

1879 

1880 :: 

1881 

1882 bindings: 

1883 - members: 

1884 - user:mike@example.com 

1885 - group:admins@example.com 

1886 - domain:google.com 

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

1888 role: roles/resourcemanager.organizationAdmin 

1889 - members: 

1890 - user:eve@example.com 

1891 role: roles/resourcemanager.organizationViewer 

1892 condition: 

1893 title: expirable access 

1894 description: Does not grant access after Sep 2020 

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

1896 

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

1898 developer's 

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

1900 """ 

1901 # Create or coerce a protobuf request object. 

1902 

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

1904 # so it must be constructed via keyword expansion. 

1905 if isinstance(request, dict): 

1906 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

1907 

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

1909 # and friendly error handling. 

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

1911 

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

1913 # add these here. 

1914 metadata = tuple(metadata) + ( 

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

1916 ) 

1917 

1918 # Validate the universe domain. 

1919 self._validate_universe_domain() 

1920 

1921 try: 

1922 # Send the request. 

1923 response = rpc( 

1924 request, 

1925 retry=retry, 

1926 timeout=timeout, 

1927 metadata=metadata, 

1928 ) 

1929 

1930 # Done; return the response. 

1931 return response 

1932 except core_exceptions.GoogleAPICallError as e: 

1933 self._add_cred_info_for_auth_errors(e) 

1934 raise e 

1935 

1936 def get_iam_policy( 

1937 self, 

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

1939 *, 

1940 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1941 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1943 ) -> policy_pb2.Policy: 

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

1945 

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

1947 policy set. 

1948 

1949 Args: 

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

1951 The request object. Request message for `GetIamPolicy` 

1952 method. 

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

1954 any, should be retried. 

1955 timeout (TimeoutType): 

1956 The timeout for this request. 

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

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

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

1960 be of type `bytes`. 

1961 Returns: 

1962 ~.policy_pb2.Policy: 

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

1964 It is used to specify access control policies for Cloud 

1965 Platform resources. 

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

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

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

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

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

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

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

1973 expression that further constrains the role binding 

1974 based on attributes about the request and/or target 

1975 resource. 

1976 

1977 **JSON Example** 

1978 

1979 :: 

1980 

1981 { 

1982 "bindings": [ 

1983 { 

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

1985 "members": [ 

1986 "user:mike@example.com", 

1987 "group:admins@example.com", 

1988 "domain:google.com", 

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

1990 ] 

1991 }, 

1992 { 

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

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

1995 "condition": { 

1996 "title": "expirable access", 

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

1998 "expression": "request.time < 

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

2000 } 

2001 } 

2002 ] 

2003 } 

2004 

2005 **YAML Example** 

2006 

2007 :: 

2008 

2009 bindings: 

2010 - members: 

2011 - user:mike@example.com 

2012 - group:admins@example.com 

2013 - domain:google.com 

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

2015 role: roles/resourcemanager.organizationAdmin 

2016 - members: 

2017 - user:eve@example.com 

2018 role: roles/resourcemanager.organizationViewer 

2019 condition: 

2020 title: expirable access 

2021 description: Does not grant access after Sep 2020 

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

2023 

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

2025 developer's 

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

2027 """ 

2028 # Create or coerce a protobuf request object. 

2029 

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

2031 # so it must be constructed via keyword expansion. 

2032 if isinstance(request, dict): 

2033 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

2034 

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

2036 # and friendly error handling. 

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

2038 

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

2040 # add these here. 

2041 metadata = tuple(metadata) + ( 

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

2043 ) 

2044 

2045 # Validate the universe domain. 

2046 self._validate_universe_domain() 

2047 

2048 try: 

2049 # Send the request. 

2050 response = rpc( 

2051 request, 

2052 retry=retry, 

2053 timeout=timeout, 

2054 metadata=metadata, 

2055 ) 

2056 

2057 # Done; return the response. 

2058 return response 

2059 except core_exceptions.GoogleAPICallError as e: 

2060 self._add_cred_info_for_auth_errors(e) 

2061 raise e 

2062 

2063 def test_iam_permissions( 

2064 self, 

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

2066 *, 

2067 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2068 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

2070 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

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

2072 policy for a function. 

2073 

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

2075 of permissions, not a NOT_FOUND error. 

2076 

2077 Args: 

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

2079 The request object. Request message for 

2080 `TestIamPermissions` method. 

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

2082 if any, should be retried. 

2083 timeout (TimeoutType): 

2084 The timeout for this request. 

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

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

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

2088 be of type `bytes`. 

2089 Returns: 

2090 ~.iam_policy_pb2.TestIamPermissionsResponse: 

2091 Response message for ``TestIamPermissions`` method. 

2092 """ 

2093 # Create or coerce a protobuf request object. 

2094 

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

2096 # so it must be constructed via keyword expansion. 

2097 if isinstance(request, dict): 

2098 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

2099 

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

2101 # and friendly error handling. 

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

2103 

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

2105 # add these here. 

2106 metadata = tuple(metadata) + ( 

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

2108 ) 

2109 

2110 # Validate the universe domain. 

2111 self._validate_universe_domain() 

2112 

2113 try: 

2114 # Send the request. 

2115 response = rpc( 

2116 request, 

2117 retry=retry, 

2118 timeout=timeout, 

2119 metadata=metadata, 

2120 ) 

2121 

2122 # Done; return the response. 

2123 return response 

2124 except core_exceptions.GoogleAPICallError as e: 

2125 self._add_cred_info_for_auth_errors(e) 

2126 raise e 

2127 

2128 

2129DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

2130 client_library_version=package_version.__version__ 

2131) 

2132 

2133if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER 

2134 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

2135 

2136__all__ = ("PublisherClient",)