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

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

436 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 @staticmethod 

172 def _use_client_cert_effective(): 

173 """Returns whether client certificate should be used for mTLS if the 

174 google-auth version supports should_use_client_cert automatic mTLS enablement. 

175 

176 Alternatively, read from the GOOGLE_API_USE_CLIENT_CERTIFICATE env var. 

177 

178 Returns: 

179 bool: whether client certificate should be used for mTLS 

180 Raises: 

181 ValueError: (If using a version of google-auth without should_use_client_cert and 

182 GOOGLE_API_USE_CLIENT_CERTIFICATE is set to an unexpected value.) 

183 """ 

184 # check if google-auth version supports should_use_client_cert for automatic mTLS enablement 

185 if hasattr(mtls, "should_use_client_cert"): # pragma: NO COVER 

186 return mtls.should_use_client_cert() 

187 else: # pragma: NO COVER 

188 # if unsupported, fallback to reading from env var 

189 use_client_cert_str = os.getenv( 

190 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" 

191 ).lower() 

192 if use_client_cert_str not in ("true", "false"): 

193 raise ValueError( 

194 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be" 

195 " either `true` or `false`" 

196 ) 

197 return use_client_cert_str == "true" 

198 

199 @classmethod 

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

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

202 info. 

203 

204 Args: 

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

206 args: Additional arguments to pass to the constructor. 

207 kwargs: Additional arguments to pass to the constructor. 

208 

209 Returns: 

210 PublisherClient: The constructed client. 

211 """ 

212 credentials = service_account.Credentials.from_service_account_info(info) 

213 kwargs["credentials"] = credentials 

214 return cls(*args, **kwargs) 

215 

216 @classmethod 

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

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

219 file. 

220 

221 Args: 

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

223 file. 

224 args: Additional arguments to pass to the constructor. 

225 kwargs: Additional arguments to pass to the constructor. 

226 

227 Returns: 

228 PublisherClient: The constructed client. 

229 """ 

230 credentials = service_account.Credentials.from_service_account_file(filename) 

231 kwargs["credentials"] = credentials 

232 return cls(*args, **kwargs) 

233 

234 from_service_account_json = from_service_account_file 

235 

236 @property 

237 def transport(self) -> PublisherTransport: 

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

239 

240 Returns: 

241 PublisherTransport: The transport used by the client 

242 instance. 

243 """ 

244 return self._transport 

245 

246 @staticmethod 

247 def crypto_key_path( 

248 project: str, 

249 location: str, 

250 key_ring: str, 

251 crypto_key: str, 

252 ) -> str: 

253 """Returns a fully-qualified crypto_key string.""" 

254 return "projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}".format( 

255 project=project, 

256 location=location, 

257 key_ring=key_ring, 

258 crypto_key=crypto_key, 

259 ) 

260 

261 @staticmethod 

262 def parse_crypto_key_path(path: str) -> Dict[str, str]: 

263 """Parses a crypto_key path into its component segments.""" 

264 m = re.match( 

265 r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)/keyRings/(?P<key_ring>.+?)/cryptoKeys/(?P<crypto_key>.+?)$", 

266 path, 

267 ) 

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

269 

270 @staticmethod 

271 def schema_path( 

272 project: str, 

273 schema: str, 

274 ) -> str: 

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

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

277 project=project, 

278 schema=schema, 

279 ) 

280 

281 @staticmethod 

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

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

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

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

286 

287 @staticmethod 

288 def snapshot_path( 

289 project: str, 

290 snapshot: str, 

291 ) -> str: 

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

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

294 project=project, 

295 snapshot=snapshot, 

296 ) 

297 

298 @staticmethod 

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

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

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

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

303 

304 @staticmethod 

305 def subscription_path( 

306 project: str, 

307 subscription: str, 

308 ) -> str: 

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

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

311 project=project, 

312 subscription=subscription, 

313 ) 

314 

315 @staticmethod 

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

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

318 m = re.match( 

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

320 ) 

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

322 

323 @staticmethod 

324 def topic_path( 

325 project: str, 

326 topic: str, 

327 ) -> str: 

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

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

330 project=project, 

331 topic=topic, 

332 ) 

333 

334 @staticmethod 

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

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

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

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

339 

340 @staticmethod 

341 def common_billing_account_path( 

342 billing_account: str, 

343 ) -> str: 

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

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

346 billing_account=billing_account, 

347 ) 

348 

349 @staticmethod 

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

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

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

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

354 

355 @staticmethod 

356 def common_folder_path( 

357 folder: str, 

358 ) -> str: 

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

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

361 folder=folder, 

362 ) 

363 

364 @staticmethod 

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

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

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

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

369 

370 @staticmethod 

371 def common_organization_path( 

372 organization: str, 

373 ) -> str: 

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

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

376 organization=organization, 

377 ) 

378 

379 @staticmethod 

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

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

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

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

384 

385 @staticmethod 

386 def common_project_path( 

387 project: str, 

388 ) -> str: 

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

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

391 project=project, 

392 ) 

393 

394 @staticmethod 

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

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

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

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

399 

400 @staticmethod 

401 def common_location_path( 

402 project: str, 

403 location: str, 

404 ) -> str: 

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

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

407 project=project, 

408 location=location, 

409 ) 

410 

411 @staticmethod 

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

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

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

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

416 

417 @classmethod 

418 def get_mtls_endpoint_and_cert_source( 

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

420 ): 

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

422 

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

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

425 client cert source is None. 

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

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

428 source is None. 

429 

430 The API endpoint is determined in the following order: 

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

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

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

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

435 use the default API endpoint. 

436 

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

438 

439 Args: 

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

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

442 in this method. 

443 

444 Returns: 

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

446 client cert source to use. 

447 

448 Raises: 

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

450 """ 

451 

452 warnings.warn( 

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

454 DeprecationWarning, 

455 ) 

456 if client_options is None: 

457 client_options = client_options_lib.ClientOptions() 

458 use_client_cert = PublisherClient._use_client_cert_effective() 

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

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

461 raise MutualTLSChannelError( 

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

463 ) 

464 

465 # Figure out the client cert source to use. 

466 client_cert_source = None 

467 if use_client_cert: 

468 if client_options.client_cert_source: 

469 client_cert_source = client_options.client_cert_source 

470 elif mtls.has_default_client_cert_source(): 

471 client_cert_source = mtls.default_client_cert_source() 

472 

473 # Figure out which api endpoint to use. 

474 if client_options.api_endpoint is not None: 

475 api_endpoint = client_options.api_endpoint 

476 elif use_mtls_endpoint == "always" or ( 

477 use_mtls_endpoint == "auto" and client_cert_source 

478 ): 

479 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

480 else: 

481 api_endpoint = cls.DEFAULT_ENDPOINT 

482 

483 return api_endpoint, client_cert_source 

484 

485 @staticmethod 

486 def _read_environment_variables(): 

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

488 

489 Returns: 

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

491 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. 

492 

493 Raises: 

494 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not 

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

496 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT 

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

498 """ 

499 use_client_cert = PublisherClient._use_client_cert_effective() 

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

501 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") 

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

503 raise MutualTLSChannelError( 

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

505 ) 

506 return use_client_cert, use_mtls_endpoint, universe_domain_env 

507 

508 @staticmethod 

509 def _get_client_cert_source(provided_cert_source, use_cert_flag): 

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

511 

512 Args: 

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

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

515 

516 Returns: 

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

518 """ 

519 client_cert_source = None 

520 if use_cert_flag: 

521 if provided_cert_source: 

522 client_cert_source = provided_cert_source 

523 elif mtls.has_default_client_cert_source(): 

524 client_cert_source = mtls.default_client_cert_source() 

525 return client_cert_source 

526 

527 @staticmethod 

528 def _get_api_endpoint( 

529 api_override, client_cert_source, universe_domain, use_mtls_endpoint 

530 ): 

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

532 

533 Args: 

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

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

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

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

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

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

540 

541 Returns: 

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

543 """ 

544 if api_override is not None: 

545 api_endpoint = api_override 

546 elif use_mtls_endpoint == "always" or ( 

547 use_mtls_endpoint == "auto" and client_cert_source 

548 ): 

549 _default_universe = PublisherClient._DEFAULT_UNIVERSE 

550 if universe_domain != _default_universe: 

551 raise MutualTLSChannelError( 

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

553 ) 

554 api_endpoint = PublisherClient.DEFAULT_MTLS_ENDPOINT 

555 else: 

556 api_endpoint = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE.format( 

557 UNIVERSE_DOMAIN=universe_domain 

558 ) 

559 return api_endpoint 

560 

561 @staticmethod 

562 def _get_universe_domain( 

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

564 ) -> str: 

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

566 

567 Args: 

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

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

570 

571 Returns: 

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

573 

574 Raises: 

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

576 """ 

577 universe_domain = PublisherClient._DEFAULT_UNIVERSE 

578 if client_universe_domain is not None: 

579 universe_domain = client_universe_domain 

580 elif universe_domain_env is not None: 

581 universe_domain = universe_domain_env 

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

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

584 return universe_domain 

585 

586 def _validate_universe_domain(self): 

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

588 

589 Returns: 

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

591 

592 Raises: 

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

594 """ 

595 

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

597 return True 

598 

599 def _add_cred_info_for_auth_errors( 

600 self, error: core_exceptions.GoogleAPICallError 

601 ) -> None: 

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

603 

604 Args: 

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

606 """ 

607 if error.code not in [ 

608 HTTPStatus.UNAUTHORIZED, 

609 HTTPStatus.FORBIDDEN, 

610 HTTPStatus.NOT_FOUND, 

611 ]: 

612 return 

613 

614 cred = self._transport._credentials 

615 

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

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

618 return 

619 

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

621 # is not available 

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

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

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

625 

626 @property 

627 def api_endpoint(self): 

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

629 

630 Returns: 

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

632 """ 

633 return self._api_endpoint 

634 

635 @property 

636 def universe_domain(self) -> str: 

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

638 

639 Returns: 

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

641 """ 

642 return self._universe_domain 

643 

644 def __init__( 

645 self, 

646 *, 

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

648 transport: Optional[ 

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

650 ] = None, 

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

652 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

653 ) -> None: 

654 """Instantiates the publisher client. 

655 

656 Args: 

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

658 authorization credentials to attach to requests. These 

659 credentials identify the application to the service; if none 

660 are specified, the client will attempt to ascertain the 

661 credentials from the environment. 

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

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

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

665 arguments as used in the PublisherTransport constructor. 

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

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

668 Custom options for the client. 

669 

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

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

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

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

674 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

675 variable, which have one of the following values: 

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

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

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

679 the default value). 

680 

681 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

683 to provide a client certificate for mTLS transport. If 

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

685 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

686 set, no client certificate will be used. 

687 

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

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

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

691 currently not supported for mTLS. 

692 

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

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

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

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

697 your own client library. 

698 

699 Raises: 

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

701 creation failed for any reason. 

702 """ 

703 self._client_options = client_options 

704 if isinstance(self._client_options, dict): 

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

706 if self._client_options is None: 

707 self._client_options = client_options_lib.ClientOptions() 

708 self._client_options = cast( 

709 client_options_lib.ClientOptions, self._client_options 

710 ) 

711 

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

713 

714 ( 

715 self._use_client_cert, 

716 self._use_mtls_endpoint, 

717 self._universe_domain_env, 

718 ) = PublisherClient._read_environment_variables() 

719 self._client_cert_source = PublisherClient._get_client_cert_source( 

720 self._client_options.client_cert_source, self._use_client_cert 

721 ) 

722 self._universe_domain = PublisherClient._get_universe_domain( 

723 universe_domain_opt, self._universe_domain_env 

724 ) 

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

726 

727 # Initialize the universe domain validation. 

728 self._is_universe_domain_valid = False 

729 

730 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER 

731 # Setup logging. 

732 client_logging.initialize_logging() 

733 

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

735 if api_key_value and credentials: 

736 raise ValueError( 

737 "client_options.api_key and credentials are mutually exclusive" 

738 ) 

739 

740 # Save or instantiate the transport. 

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

742 # instance provides an extensibility point for unusual situations. 

743 transport_provided = isinstance(transport, PublisherTransport) 

744 if transport_provided: 

745 # transport is a PublisherTransport instance. 

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

747 raise ValueError( 

748 "When providing a transport instance, " 

749 "provide its credentials directly." 

750 ) 

751 if self._client_options.scopes: 

752 raise ValueError( 

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

754 "directly." 

755 ) 

756 self._transport = cast(PublisherTransport, transport) 

757 self._api_endpoint = self._transport.host 

758 

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

760 self._client_options.api_endpoint, 

761 self._client_cert_source, 

762 self._universe_domain, 

763 self._use_mtls_endpoint, 

764 ) 

765 

766 if not transport_provided: 

767 import google.auth._default # type: ignore 

768 

769 if api_key_value and hasattr( 

770 google.auth._default, "get_api_key_credentials" 

771 ): 

772 credentials = google.auth._default.get_api_key_credentials( 

773 api_key_value 

774 ) 

775 

776 transport_init: Union[ 

777 Type[PublisherTransport], Callable[..., PublisherTransport] 

778 ] = ( 

779 PublisherClient.get_transport_class(transport) 

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

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

782 ) 

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

784 

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

786 if emulator_host: 

787 if issubclass(transport_init, type(self)._transport_registry["grpc"]): # type: ignore 

788 channel = grpc.insecure_channel(target=emulator_host) 

789 else: 

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

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

792 

793 self._transport = transport_init( 

794 credentials=credentials, 

795 credentials_file=self._client_options.credentials_file, 

796 host=self._api_endpoint, 

797 scopes=self._client_options.scopes, 

798 client_cert_source_for_mtls=self._client_cert_source, 

799 quota_project_id=self._client_options.quota_project_id, 

800 client_info=client_info, 

801 always_use_jwt_access=True, 

802 api_audience=self._client_options.api_audience, 

803 ) 

804 

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

806 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

807 std_logging.DEBUG 

808 ): # pragma: NO COVER 

809 _LOGGER.debug( 

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

811 extra={ 

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

813 "universeDomain": getattr( 

814 self._transport._credentials, "universe_domain", "" 

815 ), 

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

817 "credentialsInfo": getattr( 

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

819 )(), 

820 } 

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

822 else { 

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

824 "credentialsType": None, 

825 }, 

826 ) 

827 

828 def create_topic( 

829 self, 

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

831 *, 

832 name: Optional[str] = None, 

833 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

834 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

836 ) -> pubsub.Topic: 

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

838 name rules] 

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

840 

841 .. code-block:: python 

842 

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

844 # code template only. 

845 # It will require modifications to work: 

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

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

848 # client as shown in: 

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

850 from google import pubsub_v1 

851 

852 def sample_create_topic(): 

853 # Create a client 

854 client = pubsub_v1.PublisherClient() 

855 

856 # Initialize request argument(s) 

857 request = pubsub_v1.Topic( 

858 name="name_value", 

859 ) 

860 

861 # Make the request 

862 response = client.create_topic(request=request) 

863 

864 # Handle the response 

865 print(response) 

866 

867 Args: 

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

869 The request object. A topic resource. 

870 name (str): 

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

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

873 must start with a letter, and contain only letters 

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

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

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

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

878 start with ``"goog"``. 

879 

880 This corresponds to the ``name`` field 

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

882 should not be set. 

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

884 should be retried. 

885 timeout (TimeoutType): 

886 The timeout for this request. 

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

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

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

890 be of type `bytes`. 

891 

892 Returns: 

893 google.pubsub_v1.types.Topic: 

894 A topic resource. 

895 """ 

896 # Create or coerce a protobuf request object. 

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

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

899 flattened_params = [name] 

900 has_flattened_params = ( 

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

902 ) 

903 if request is not None and has_flattened_params: 

904 raise ValueError( 

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

906 "the individual field arguments should be set." 

907 ) 

908 

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

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

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

912 request = pubsub.Topic(request) 

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

914 # request, apply these. 

915 if name is not None: 

916 request.name = name 

917 

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

919 # and friendly error handling. 

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

921 

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

923 # add these here. 

924 metadata = tuple(metadata) + ( 

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

926 ) 

927 

928 # Validate the universe domain. 

929 self._validate_universe_domain() 

930 

931 # Send the request. 

932 response = rpc( 

933 request, 

934 retry=retry, 

935 timeout=timeout, 

936 metadata=metadata, 

937 ) 

938 

939 # Done; return the response. 

940 return response 

941 

942 def update_topic( 

943 self, 

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

945 *, 

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

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

948 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

949 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

951 ) -> pubsub.Topic: 

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

953 specified in the update mask. Note that certain 

954 properties of a topic are not modifiable. 

955 

956 .. code-block:: python 

957 

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

959 # code template only. 

960 # It will require modifications to work: 

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

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

963 # client as shown in: 

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

965 from google import pubsub_v1 

966 

967 def sample_update_topic(): 

968 # Create a client 

969 client = pubsub_v1.PublisherClient() 

970 

971 # Initialize request argument(s) 

972 topic = pubsub_v1.Topic() 

973 topic.name = "name_value" 

974 

975 request = pubsub_v1.UpdateTopicRequest( 

976 topic=topic, 

977 ) 

978 

979 # Make the request 

980 response = client.update_topic(request=request) 

981 

982 # Handle the response 

983 print(response) 

984 

985 Args: 

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

987 The request object. Request for the UpdateTopic method. 

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

989 Required. The updated topic object. 

990 This corresponds to the ``topic`` field 

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

992 should not be set. 

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

994 Required. Indicates which fields in the provided topic 

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

996 ``update_mask`` contains "message_storage_policy" but 

997 the ``message_storage_policy`` is not set in the 

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

999 determined by the policy configured at the project or 

1000 organization level. 

1001 

1002 This corresponds to the ``update_mask`` field 

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

1004 should not be set. 

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

1006 should be retried. 

1007 timeout (TimeoutType): 

1008 The timeout for this request. 

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

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

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

1012 be of type `bytes`. 

1013 

1014 Returns: 

1015 google.pubsub_v1.types.Topic: 

1016 A topic resource. 

1017 """ 

1018 # Create or coerce a protobuf request object. 

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

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

1021 flattened_params = [topic, update_mask] 

1022 has_flattened_params = ( 

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

1024 ) 

1025 if request is not None and has_flattened_params: 

1026 raise ValueError( 

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

1028 "the individual field arguments should be set." 

1029 ) 

1030 

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

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

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

1034 request = pubsub.UpdateTopicRequest(request) 

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

1036 # request, apply these. 

1037 if topic is not None: 

1038 request.topic = topic 

1039 if update_mask is not None: 

1040 request.update_mask = update_mask 

1041 

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

1043 # and friendly error handling. 

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

1045 

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

1047 # add these here. 

1048 metadata = tuple(metadata) + ( 

1049 gapic_v1.routing_header.to_grpc_metadata( 

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

1051 ), 

1052 ) 

1053 

1054 # Validate the universe domain. 

1055 self._validate_universe_domain() 

1056 

1057 # Send the request. 

1058 response = rpc( 

1059 request, 

1060 retry=retry, 

1061 timeout=timeout, 

1062 metadata=metadata, 

1063 ) 

1064 

1065 # Done; return the response. 

1066 return response 

1067 

1068 def publish( 

1069 self, 

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

1071 *, 

1072 topic: Optional[str] = None, 

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

1074 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1075 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1077 ) -> pubsub.PublishResponse: 

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

1079 the topic does not exist. 

1080 

1081 .. code-block:: python 

1082 

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

1084 # code template only. 

1085 # It will require modifications to work: 

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

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

1088 # client as shown in: 

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

1090 from google import pubsub_v1 

1091 

1092 def sample_publish(): 

1093 # Create a client 

1094 client = pubsub_v1.PublisherClient() 

1095 

1096 # Initialize request argument(s) 

1097 request = pubsub_v1.PublishRequest( 

1098 topic="topic_value", 

1099 ) 

1100 

1101 # Make the request 

1102 response = client.publish(request=request) 

1103 

1104 # Handle the response 

1105 print(response) 

1106 

1107 Args: 

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

1109 The request object. Request for the Publish method. 

1110 topic (str): 

1111 Required. The messages in the request will be published 

1112 on this topic. Format is 

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

1114 

1115 This corresponds to the ``topic`` field 

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

1117 should not be set. 

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

1119 Required. The messages to publish. 

1120 This corresponds to the ``messages`` field 

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

1122 should not be set. 

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

1124 should be retried. 

1125 timeout (TimeoutType): 

1126 The timeout for this request. 

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

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

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

1130 be of type `bytes`. 

1131 

1132 Returns: 

1133 google.pubsub_v1.types.PublishResponse: 

1134 Response for the Publish method. 

1135 """ 

1136 # Create or coerce a protobuf request object. 

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

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

1139 flattened_params = [topic, messages] 

1140 has_flattened_params = ( 

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

1142 ) 

1143 if request is not None and has_flattened_params: 

1144 raise ValueError( 

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

1146 "the individual field arguments should be set." 

1147 ) 

1148 

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

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

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

1152 request = pubsub.PublishRequest(request) 

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

1154 # request, apply these. 

1155 if topic is not None: 

1156 request.topic = topic 

1157 if messages is not None: 

1158 request.messages = messages 

1159 

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

1161 # and friendly error handling. 

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

1163 

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

1165 # add these here. 

1166 metadata = tuple(metadata) + ( 

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

1168 ) 

1169 

1170 # Validate the universe domain. 

1171 self._validate_universe_domain() 

1172 

1173 # Send the request. 

1174 response = rpc( 

1175 request, 

1176 retry=retry, 

1177 timeout=timeout, 

1178 metadata=metadata, 

1179 ) 

1180 

1181 # Done; return the response. 

1182 return response 

1183 

1184 def get_topic( 

1185 self, 

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

1187 *, 

1188 topic: Optional[str] = None, 

1189 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1190 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1192 ) -> pubsub.Topic: 

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

1194 

1195 .. code-block:: python 

1196 

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

1198 # code template only. 

1199 # It will require modifications to work: 

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

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

1202 # client as shown in: 

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

1204 from google import pubsub_v1 

1205 

1206 def sample_get_topic(): 

1207 # Create a client 

1208 client = pubsub_v1.PublisherClient() 

1209 

1210 # Initialize request argument(s) 

1211 request = pubsub_v1.GetTopicRequest( 

1212 topic="topic_value", 

1213 ) 

1214 

1215 # Make the request 

1216 response = client.get_topic(request=request) 

1217 

1218 # Handle the response 

1219 print(response) 

1220 

1221 Args: 

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

1223 The request object. Request for the GetTopic method. 

1224 topic (str): 

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

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

1227 

1228 This corresponds to the ``topic`` field 

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

1230 should not be set. 

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

1232 should be retried. 

1233 timeout (TimeoutType): 

1234 The timeout for this request. 

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

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

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

1238 be of type `bytes`. 

1239 

1240 Returns: 

1241 google.pubsub_v1.types.Topic: 

1242 A topic resource. 

1243 """ 

1244 # Create or coerce a protobuf request object. 

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

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

1247 flattened_params = [topic] 

1248 has_flattened_params = ( 

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

1250 ) 

1251 if request is not None and has_flattened_params: 

1252 raise ValueError( 

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

1254 "the individual field arguments should be set." 

1255 ) 

1256 

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

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

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

1260 request = pubsub.GetTopicRequest(request) 

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

1262 # request, apply these. 

1263 if topic is not None: 

1264 request.topic = topic 

1265 

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

1267 # and friendly error handling. 

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

1269 

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

1271 # add these here. 

1272 metadata = tuple(metadata) + ( 

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

1274 ) 

1275 

1276 # Validate the universe domain. 

1277 self._validate_universe_domain() 

1278 

1279 # Send the request. 

1280 response = rpc( 

1281 request, 

1282 retry=retry, 

1283 timeout=timeout, 

1284 metadata=metadata, 

1285 ) 

1286 

1287 # Done; return the response. 

1288 return response 

1289 

1290 def list_topics( 

1291 self, 

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

1293 *, 

1294 project: Optional[str] = None, 

1295 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1296 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1298 ) -> pagers.ListTopicsPager: 

1299 r"""Lists matching topics. 

1300 

1301 .. code-block:: python 

1302 

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

1304 # code template only. 

1305 # It will require modifications to work: 

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

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

1308 # client as shown in: 

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

1310 from google import pubsub_v1 

1311 

1312 def sample_list_topics(): 

1313 # Create a client 

1314 client = pubsub_v1.PublisherClient() 

1315 

1316 # Initialize request argument(s) 

1317 request = pubsub_v1.ListTopicsRequest( 

1318 project="project_value", 

1319 ) 

1320 

1321 # Make the request 

1322 page_result = client.list_topics(request=request) 

1323 

1324 # Handle the response 

1325 for response in page_result: 

1326 print(response) 

1327 

1328 Args: 

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

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

1331 project (str): 

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

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

1334 

1335 This corresponds to the ``project`` field 

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

1337 should not be set. 

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

1339 should be retried. 

1340 timeout (TimeoutType): 

1341 The timeout for this request. 

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

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

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

1345 be of type `bytes`. 

1346 

1347 Returns: 

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

1349 Response for the ListTopics method. 

1350 

1351 Iterating over this object will yield results and 

1352 resolve additional pages automatically. 

1353 

1354 """ 

1355 # Create or coerce a protobuf request object. 

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

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

1358 flattened_params = [project] 

1359 has_flattened_params = ( 

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

1361 ) 

1362 if request is not None and has_flattened_params: 

1363 raise ValueError( 

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

1365 "the individual field arguments should be set." 

1366 ) 

1367 

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

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

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

1371 request = pubsub.ListTopicsRequest(request) 

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

1373 # request, apply these. 

1374 if project is not None: 

1375 request.project = project 

1376 

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

1378 # and friendly error handling. 

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

1380 

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

1382 # add these here. 

1383 metadata = tuple(metadata) + ( 

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

1385 ) 

1386 

1387 # Validate the universe domain. 

1388 self._validate_universe_domain() 

1389 

1390 # Send the request. 

1391 response = rpc( 

1392 request, 

1393 retry=retry, 

1394 timeout=timeout, 

1395 metadata=metadata, 

1396 ) 

1397 

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

1399 # an `__iter__` convenience method. 

1400 response = pagers.ListTopicsPager( 

1401 method=rpc, 

1402 request=request, 

1403 response=response, 

1404 retry=retry, 

1405 timeout=timeout, 

1406 metadata=metadata, 

1407 ) 

1408 

1409 # Done; return the response. 

1410 return response 

1411 

1412 def list_topic_subscriptions( 

1413 self, 

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

1415 *, 

1416 topic: Optional[str] = None, 

1417 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1418 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1420 ) -> pagers.ListTopicSubscriptionsPager: 

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

1422 topic. 

1423 

1424 .. code-block:: python 

1425 

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

1427 # code template only. 

1428 # It will require modifications to work: 

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

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

1431 # client as shown in: 

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

1433 from google import pubsub_v1 

1434 

1435 def sample_list_topic_subscriptions(): 

1436 # Create a client 

1437 client = pubsub_v1.PublisherClient() 

1438 

1439 # Initialize request argument(s) 

1440 request = pubsub_v1.ListTopicSubscriptionsRequest( 

1441 topic="topic_value", 

1442 ) 

1443 

1444 # Make the request 

1445 page_result = client.list_topic_subscriptions(request=request) 

1446 

1447 # Handle the response 

1448 for response in page_result: 

1449 print(response) 

1450 

1451 Args: 

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

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

1454 topic (str): 

1455 Required. The name of the topic that subscriptions are 

1456 attached to. Format is 

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

1458 

1459 This corresponds to the ``topic`` field 

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

1461 should not be set. 

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

1463 should be retried. 

1464 timeout (TimeoutType): 

1465 The timeout for this request. 

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

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

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

1469 be of type `bytes`. 

1470 

1471 Returns: 

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

1473 Response for the ListTopicSubscriptions method. 

1474 

1475 Iterating over this object will yield results and 

1476 resolve additional pages automatically. 

1477 

1478 """ 

1479 # Create or coerce a protobuf request object. 

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

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

1482 flattened_params = [topic] 

1483 has_flattened_params = ( 

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

1485 ) 

1486 if request is not None and has_flattened_params: 

1487 raise ValueError( 

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

1489 "the individual field arguments should be set." 

1490 ) 

1491 

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

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

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

1495 request = pubsub.ListTopicSubscriptionsRequest(request) 

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

1497 # request, apply these. 

1498 if topic is not None: 

1499 request.topic = topic 

1500 

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

1502 # and friendly error handling. 

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

1504 

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

1506 # add these here. 

1507 metadata = tuple(metadata) + ( 

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

1509 ) 

1510 

1511 # Validate the universe domain. 

1512 self._validate_universe_domain() 

1513 

1514 # Send the request. 

1515 response = rpc( 

1516 request, 

1517 retry=retry, 

1518 timeout=timeout, 

1519 metadata=metadata, 

1520 ) 

1521 

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

1523 # an `__iter__` convenience method. 

1524 response = pagers.ListTopicSubscriptionsPager( 

1525 method=rpc, 

1526 request=request, 

1527 response=response, 

1528 retry=retry, 

1529 timeout=timeout, 

1530 metadata=metadata, 

1531 ) 

1532 

1533 # Done; return the response. 

1534 return response 

1535 

1536 def list_topic_snapshots( 

1537 self, 

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

1539 *, 

1540 topic: Optional[str] = None, 

1541 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1542 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1544 ) -> pagers.ListTopicSnapshotsPager: 

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

1546 used in 

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

1548 operations, which allow you to manage message acknowledgments in 

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

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

1551 

1552 .. code-block:: python 

1553 

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

1555 # code template only. 

1556 # It will require modifications to work: 

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

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

1559 # client as shown in: 

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

1561 from google import pubsub_v1 

1562 

1563 def sample_list_topic_snapshots(): 

1564 # Create a client 

1565 client = pubsub_v1.PublisherClient() 

1566 

1567 # Initialize request argument(s) 

1568 request = pubsub_v1.ListTopicSnapshotsRequest( 

1569 topic="topic_value", 

1570 ) 

1571 

1572 # Make the request 

1573 page_result = client.list_topic_snapshots(request=request) 

1574 

1575 # Handle the response 

1576 for response in page_result: 

1577 print(response) 

1578 

1579 Args: 

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

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

1582 topic (str): 

1583 Required. The name of the topic that snapshots are 

1584 attached to. Format is 

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

1586 

1587 This corresponds to the ``topic`` field 

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

1589 should not be set. 

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

1591 should be retried. 

1592 timeout (TimeoutType): 

1593 The timeout for this request. 

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

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

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

1597 be of type `bytes`. 

1598 

1599 Returns: 

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

1601 Response for the ListTopicSnapshots method. 

1602 

1603 Iterating over this object will yield results and 

1604 resolve additional pages automatically. 

1605 

1606 """ 

1607 # Create or coerce a protobuf request object. 

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

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

1610 flattened_params = [topic] 

1611 has_flattened_params = ( 

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

1613 ) 

1614 if request is not None and has_flattened_params: 

1615 raise ValueError( 

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

1617 "the individual field arguments should be set." 

1618 ) 

1619 

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

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

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

1623 request = pubsub.ListTopicSnapshotsRequest(request) 

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

1625 # request, apply these. 

1626 if topic is not None: 

1627 request.topic = topic 

1628 

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

1630 # and friendly error handling. 

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

1632 

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

1634 # add these here. 

1635 metadata = tuple(metadata) + ( 

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

1637 ) 

1638 

1639 # Validate the universe domain. 

1640 self._validate_universe_domain() 

1641 

1642 # Send the request. 

1643 response = rpc( 

1644 request, 

1645 retry=retry, 

1646 timeout=timeout, 

1647 metadata=metadata, 

1648 ) 

1649 

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

1651 # an `__iter__` convenience method. 

1652 response = pagers.ListTopicSnapshotsPager( 

1653 method=rpc, 

1654 request=request, 

1655 response=response, 

1656 retry=retry, 

1657 timeout=timeout, 

1658 metadata=metadata, 

1659 ) 

1660 

1661 # Done; return the response. 

1662 return response 

1663 

1664 def delete_topic( 

1665 self, 

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

1667 *, 

1668 topic: Optional[str] = None, 

1669 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1670 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1672 ) -> None: 

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

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

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

1676 with none of the old configuration or subscriptions. Existing 

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

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

1679 

1680 .. code-block:: python 

1681 

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

1683 # code template only. 

1684 # It will require modifications to work: 

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

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

1687 # client as shown in: 

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

1689 from google import pubsub_v1 

1690 

1691 def sample_delete_topic(): 

1692 # Create a client 

1693 client = pubsub_v1.PublisherClient() 

1694 

1695 # Initialize request argument(s) 

1696 request = pubsub_v1.DeleteTopicRequest( 

1697 topic="topic_value", 

1698 ) 

1699 

1700 # Make the request 

1701 client.delete_topic(request=request) 

1702 

1703 Args: 

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

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

1706 topic (str): 

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

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

1709 

1710 This corresponds to the ``topic`` field 

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

1712 should not be set. 

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

1714 should be retried. 

1715 timeout (TimeoutType): 

1716 The timeout for this request. 

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

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

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

1720 be of type `bytes`. 

1721 """ 

1722 # Create or coerce a protobuf request object. 

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

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

1725 flattened_params = [topic] 

1726 has_flattened_params = ( 

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

1728 ) 

1729 if request is not None and has_flattened_params: 

1730 raise ValueError( 

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

1732 "the individual field arguments should be set." 

1733 ) 

1734 

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

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

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

1738 request = pubsub.DeleteTopicRequest(request) 

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

1740 # request, apply these. 

1741 if topic is not None: 

1742 request.topic = topic 

1743 

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

1745 # and friendly error handling. 

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

1747 

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

1749 # add these here. 

1750 metadata = tuple(metadata) + ( 

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

1752 ) 

1753 

1754 # Validate the universe domain. 

1755 self._validate_universe_domain() 

1756 

1757 # Send the request. 

1758 rpc( 

1759 request, 

1760 retry=retry, 

1761 timeout=timeout, 

1762 metadata=metadata, 

1763 ) 

1764 

1765 def detach_subscription( 

1766 self, 

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

1768 *, 

1769 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1770 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1772 ) -> pubsub.DetachSubscriptionResponse: 

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

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

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

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

1777 will stop. 

1778 

1779 .. code-block:: python 

1780 

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

1782 # code template only. 

1783 # It will require modifications to work: 

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

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

1786 # client as shown in: 

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

1788 from google import pubsub_v1 

1789 

1790 def sample_detach_subscription(): 

1791 # Create a client 

1792 client = pubsub_v1.PublisherClient() 

1793 

1794 # Initialize request argument(s) 

1795 request = pubsub_v1.DetachSubscriptionRequest( 

1796 subscription="subscription_value", 

1797 ) 

1798 

1799 # Make the request 

1800 response = client.detach_subscription(request=request) 

1801 

1802 # Handle the response 

1803 print(response) 

1804 

1805 Args: 

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

1807 The request object. Request for the DetachSubscription 

1808 method. 

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

1810 should be retried. 

1811 timeout (TimeoutType): 

1812 The timeout for this request. 

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

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

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

1816 be of type `bytes`. 

1817 

1818 Returns: 

1819 google.pubsub_v1.types.DetachSubscriptionResponse: 

1820 Response for the DetachSubscription 

1821 method. Reserved for future use. 

1822 

1823 """ 

1824 # Create or coerce a protobuf request object. 

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

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

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

1828 request = pubsub.DetachSubscriptionRequest(request) 

1829 

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

1831 # and friendly error handling. 

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

1833 

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

1835 # add these here. 

1836 metadata = tuple(metadata) + ( 

1837 gapic_v1.routing_header.to_grpc_metadata( 

1838 (("subscription", request.subscription),) 

1839 ), 

1840 ) 

1841 

1842 # Validate the universe domain. 

1843 self._validate_universe_domain() 

1844 

1845 # Send the request. 

1846 response = rpc( 

1847 request, 

1848 retry=retry, 

1849 timeout=timeout, 

1850 metadata=metadata, 

1851 ) 

1852 

1853 # Done; return the response. 

1854 return response 

1855 

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

1857 return self 

1858 

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

1860 """Releases underlying transport's resources. 

1861 

1862 .. warning:: 

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

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

1865 and may cause errors in other clients! 

1866 """ 

1867 self.transport.close() 

1868 

1869 def set_iam_policy( 

1870 self, 

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

1872 *, 

1873 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1874 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1876 ) -> policy_pb2.Policy: 

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

1878 

1879 Replaces any existing policy. 

1880 

1881 Args: 

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

1883 The request object. Request message for `SetIamPolicy` 

1884 method. 

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

1886 should be retried. 

1887 timeout (TimeoutType): 

1888 The timeout for this request. 

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

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

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

1892 be of type `bytes`. 

1893 Returns: 

1894 ~.policy_pb2.Policy: 

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

1896 It is used to specify access control policies for Cloud 

1897 Platform resources. 

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

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

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

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

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

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

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

1905 expression that further constrains the role binding 

1906 based on attributes about the request and/or target 

1907 resource. 

1908 

1909 **JSON Example** 

1910 

1911 :: 

1912 

1913 { 

1914 "bindings": [ 

1915 { 

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

1917 "members": [ 

1918 "user:mike@example.com", 

1919 "group:admins@example.com", 

1920 "domain:google.com", 

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

1922 ] 

1923 }, 

1924 { 

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

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

1927 "condition": { 

1928 "title": "expirable access", 

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

1930 "expression": "request.time < 

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

1932 } 

1933 } 

1934 ] 

1935 } 

1936 

1937 **YAML Example** 

1938 

1939 :: 

1940 

1941 bindings: 

1942 - members: 

1943 - user:mike@example.com 

1944 - group:admins@example.com 

1945 - domain:google.com 

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

1947 role: roles/resourcemanager.organizationAdmin 

1948 - members: 

1949 - user:eve@example.com 

1950 role: roles/resourcemanager.organizationViewer 

1951 condition: 

1952 title: expirable access 

1953 description: Does not grant access after Sep 2020 

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

1955 

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

1957 developer's 

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

1959 """ 

1960 # Create or coerce a protobuf request object. 

1961 

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

1963 # so it must be constructed via keyword expansion. 

1964 if isinstance(request, dict): 

1965 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

1966 

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

1968 # and friendly error handling. 

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

1970 

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

1972 # add these here. 

1973 metadata = tuple(metadata) + ( 

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

1975 ) 

1976 

1977 # Validate the universe domain. 

1978 self._validate_universe_domain() 

1979 

1980 try: 

1981 # Send the request. 

1982 response = rpc( 

1983 request, 

1984 retry=retry, 

1985 timeout=timeout, 

1986 metadata=metadata, 

1987 ) 

1988 

1989 # Done; return the response. 

1990 return response 

1991 except core_exceptions.GoogleAPICallError as e: 

1992 self._add_cred_info_for_auth_errors(e) 

1993 raise e 

1994 

1995 def get_iam_policy( 

1996 self, 

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

1998 *, 

1999 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2000 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

2002 ) -> policy_pb2.Policy: 

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

2004 

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

2006 policy set. 

2007 

2008 Args: 

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

2010 The request object. Request message for `GetIamPolicy` 

2011 method. 

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

2013 any, should be retried. 

2014 timeout (TimeoutType): 

2015 The timeout for this request. 

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

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

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

2019 be of type `bytes`. 

2020 Returns: 

2021 ~.policy_pb2.Policy: 

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

2023 It is used to specify access control policies for Cloud 

2024 Platform resources. 

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

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

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

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

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

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

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

2032 expression that further constrains the role binding 

2033 based on attributes about the request and/or target 

2034 resource. 

2035 

2036 **JSON Example** 

2037 

2038 :: 

2039 

2040 { 

2041 "bindings": [ 

2042 { 

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

2044 "members": [ 

2045 "user:mike@example.com", 

2046 "group:admins@example.com", 

2047 "domain:google.com", 

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

2049 ] 

2050 }, 

2051 { 

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

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

2054 "condition": { 

2055 "title": "expirable access", 

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

2057 "expression": "request.time < 

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

2059 } 

2060 } 

2061 ] 

2062 } 

2063 

2064 **YAML Example** 

2065 

2066 :: 

2067 

2068 bindings: 

2069 - members: 

2070 - user:mike@example.com 

2071 - group:admins@example.com 

2072 - domain:google.com 

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

2074 role: roles/resourcemanager.organizationAdmin 

2075 - members: 

2076 - user:eve@example.com 

2077 role: roles/resourcemanager.organizationViewer 

2078 condition: 

2079 title: expirable access 

2080 description: Does not grant access after Sep 2020 

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

2082 

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

2084 developer's 

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

2086 """ 

2087 # Create or coerce a protobuf request object. 

2088 

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

2090 # so it must be constructed via keyword expansion. 

2091 if isinstance(request, dict): 

2092 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

2093 

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

2095 # and friendly error handling. 

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

2097 

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

2099 # add these here. 

2100 metadata = tuple(metadata) + ( 

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

2102 ) 

2103 

2104 # Validate the universe domain. 

2105 self._validate_universe_domain() 

2106 

2107 try: 

2108 # Send the request. 

2109 response = rpc( 

2110 request, 

2111 retry=retry, 

2112 timeout=timeout, 

2113 metadata=metadata, 

2114 ) 

2115 

2116 # Done; return the response. 

2117 return response 

2118 except core_exceptions.GoogleAPICallError as e: 

2119 self._add_cred_info_for_auth_errors(e) 

2120 raise e 

2121 

2122 def test_iam_permissions( 

2123 self, 

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

2125 *, 

2126 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2127 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

2129 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

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

2131 policy for a function. 

2132 

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

2134 of permissions, not a NOT_FOUND error. 

2135 

2136 Args: 

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

2138 The request object. Request message for 

2139 `TestIamPermissions` method. 

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

2141 if any, should be retried. 

2142 timeout (TimeoutType): 

2143 The timeout for this request. 

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

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

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

2147 be of type `bytes`. 

2148 Returns: 

2149 ~.iam_policy_pb2.TestIamPermissionsResponse: 

2150 Response message for ``TestIamPermissions`` method. 

2151 """ 

2152 # Create or coerce a protobuf request object. 

2153 

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

2155 # so it must be constructed via keyword expansion. 

2156 if isinstance(request, dict): 

2157 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

2158 

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

2160 # and friendly error handling. 

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

2162 

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

2164 # add these here. 

2165 metadata = tuple(metadata) + ( 

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

2167 ) 

2168 

2169 # Validate the universe domain. 

2170 self._validate_universe_domain() 

2171 

2172 try: 

2173 # Send the request. 

2174 response = rpc( 

2175 request, 

2176 retry=retry, 

2177 timeout=timeout, 

2178 metadata=metadata, 

2179 ) 

2180 

2181 # Done; return the response. 

2182 return response 

2183 except core_exceptions.GoogleAPICallError as e: 

2184 self._add_cred_info_for_auth_errors(e) 

2185 raise e 

2186 

2187 

2188DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

2189 client_library_version=package_version.__version__ 

2190) 

2191 

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

2193 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

2194 

2195__all__ = ("PublisherClient",)