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

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

438 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 crypto_key_path( 

220 project: str, 

221 location: str, 

222 key_ring: str, 

223 crypto_key: str, 

224 ) -> str: 

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

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

227 project=project, 

228 location=location, 

229 key_ring=key_ring, 

230 crypto_key=crypto_key, 

231 ) 

232 

233 @staticmethod 

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

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

236 m = re.match( 

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

238 path, 

239 ) 

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

241 

242 @staticmethod 

243 def schema_path( 

244 project: str, 

245 schema: str, 

246 ) -> str: 

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

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

249 project=project, 

250 schema=schema, 

251 ) 

252 

253 @staticmethod 

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

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

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

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

258 

259 @staticmethod 

260 def snapshot_path( 

261 project: str, 

262 snapshot: str, 

263 ) -> str: 

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

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

266 project=project, 

267 snapshot=snapshot, 

268 ) 

269 

270 @staticmethod 

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

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

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

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

275 

276 @staticmethod 

277 def subscription_path( 

278 project: str, 

279 subscription: str, 

280 ) -> str: 

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

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

283 project=project, 

284 subscription=subscription, 

285 ) 

286 

287 @staticmethod 

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

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

290 m = re.match( 

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

292 ) 

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

294 

295 @staticmethod 

296 def topic_path( 

297 project: str, 

298 topic: str, 

299 ) -> str: 

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

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

302 project=project, 

303 topic=topic, 

304 ) 

305 

306 @staticmethod 

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

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

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

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

311 

312 @staticmethod 

313 def common_billing_account_path( 

314 billing_account: str, 

315 ) -> str: 

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

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

318 billing_account=billing_account, 

319 ) 

320 

321 @staticmethod 

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

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

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

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

326 

327 @staticmethod 

328 def common_folder_path( 

329 folder: str, 

330 ) -> str: 

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

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

333 folder=folder, 

334 ) 

335 

336 @staticmethod 

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

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

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

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

341 

342 @staticmethod 

343 def common_organization_path( 

344 organization: str, 

345 ) -> str: 

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

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

348 organization=organization, 

349 ) 

350 

351 @staticmethod 

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

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

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

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

356 

357 @staticmethod 

358 def common_project_path( 

359 project: str, 

360 ) -> str: 

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

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

363 project=project, 

364 ) 

365 

366 @staticmethod 

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

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

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

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

371 

372 @staticmethod 

373 def common_location_path( 

374 project: str, 

375 location: str, 

376 ) -> str: 

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

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

379 project=project, 

380 location=location, 

381 ) 

382 

383 @staticmethod 

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

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

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

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

388 

389 @classmethod 

390 def get_mtls_endpoint_and_cert_source( 

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

392 ): 

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

394 

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

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

397 client cert source is None. 

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

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

400 source is None. 

401 

402 The API endpoint is determined in the following order: 

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

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

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

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

407 use the default API endpoint. 

408 

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

410 

411 Args: 

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

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

414 in this method. 

415 

416 Returns: 

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

418 client cert source to use. 

419 

420 Raises: 

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

422 """ 

423 

424 warnings.warn( 

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

426 DeprecationWarning, 

427 ) 

428 if client_options is None: 

429 client_options = client_options_lib.ClientOptions() 

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

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

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

433 raise ValueError( 

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

435 ) 

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

437 raise MutualTLSChannelError( 

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

439 ) 

440 

441 # Figure out the client cert source to use. 

442 client_cert_source = None 

443 if use_client_cert == "true": 

444 if client_options.client_cert_source: 

445 client_cert_source = client_options.client_cert_source 

446 elif mtls.has_default_client_cert_source(): 

447 client_cert_source = mtls.default_client_cert_source() 

448 

449 # Figure out which api endpoint to use. 

450 if client_options.api_endpoint is not None: 

451 api_endpoint = client_options.api_endpoint 

452 elif use_mtls_endpoint == "always" or ( 

453 use_mtls_endpoint == "auto" and client_cert_source 

454 ): 

455 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

456 else: 

457 api_endpoint = cls.DEFAULT_ENDPOINT 

458 

459 return api_endpoint, client_cert_source 

460 

461 @staticmethod 

462 def _read_environment_variables(): 

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

464 

465 Returns: 

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

467 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. 

468 

469 Raises: 

470 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not 

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

472 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT 

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

474 """ 

475 use_client_cert = os.getenv( 

476 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" 

477 ).lower() 

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

479 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") 

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

481 raise ValueError( 

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

483 ) 

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

485 raise MutualTLSChannelError( 

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

487 ) 

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

489 

490 @staticmethod 

491 def _get_client_cert_source(provided_cert_source, use_cert_flag): 

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

493 

494 Args: 

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

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

497 

498 Returns: 

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

500 """ 

501 client_cert_source = None 

502 if use_cert_flag: 

503 if provided_cert_source: 

504 client_cert_source = provided_cert_source 

505 elif mtls.has_default_client_cert_source(): 

506 client_cert_source = mtls.default_client_cert_source() 

507 return client_cert_source 

508 

509 @staticmethod 

510 def _get_api_endpoint( 

511 api_override, client_cert_source, universe_domain, use_mtls_endpoint 

512 ): 

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

514 

515 Args: 

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

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

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

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

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

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

522 

523 Returns: 

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

525 """ 

526 if api_override is not None: 

527 api_endpoint = api_override 

528 elif use_mtls_endpoint == "always" or ( 

529 use_mtls_endpoint == "auto" and client_cert_source 

530 ): 

531 _default_universe = PublisherClient._DEFAULT_UNIVERSE 

532 if universe_domain != _default_universe: 

533 raise MutualTLSChannelError( 

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

535 ) 

536 api_endpoint = PublisherClient.DEFAULT_MTLS_ENDPOINT 

537 else: 

538 api_endpoint = PublisherClient._DEFAULT_ENDPOINT_TEMPLATE.format( 

539 UNIVERSE_DOMAIN=universe_domain 

540 ) 

541 return api_endpoint 

542 

543 @staticmethod 

544 def _get_universe_domain( 

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

546 ) -> str: 

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

548 

549 Args: 

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

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

552 

553 Returns: 

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

555 

556 Raises: 

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

558 """ 

559 universe_domain = PublisherClient._DEFAULT_UNIVERSE 

560 if client_universe_domain is not None: 

561 universe_domain = client_universe_domain 

562 elif universe_domain_env is not None: 

563 universe_domain = universe_domain_env 

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

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

566 return universe_domain 

567 

568 def _validate_universe_domain(self): 

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

570 

571 Returns: 

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

573 

574 Raises: 

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

576 """ 

577 

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

579 return True 

580 

581 def _add_cred_info_for_auth_errors( 

582 self, error: core_exceptions.GoogleAPICallError 

583 ) -> None: 

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

585 

586 Args: 

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

588 """ 

589 if error.code not in [ 

590 HTTPStatus.UNAUTHORIZED, 

591 HTTPStatus.FORBIDDEN, 

592 HTTPStatus.NOT_FOUND, 

593 ]: 

594 return 

595 

596 cred = self._transport._credentials 

597 

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

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

600 return 

601 

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

603 # is not available 

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

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

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

607 

608 @property 

609 def api_endpoint(self): 

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

611 

612 Returns: 

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

614 """ 

615 return self._api_endpoint 

616 

617 @property 

618 def universe_domain(self) -> str: 

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

620 

621 Returns: 

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

623 """ 

624 return self._universe_domain 

625 

626 def __init__( 

627 self, 

628 *, 

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

630 transport: Optional[ 

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

632 ] = None, 

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

634 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

635 ) -> None: 

636 """Instantiates the publisher client. 

637 

638 Args: 

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

640 authorization credentials to attach to requests. These 

641 credentials identify the application to the service; if none 

642 are specified, the client will attempt to ascertain the 

643 credentials from the environment. 

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

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

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

647 arguments as used in the PublisherTransport constructor. 

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

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

650 Custom options for the client. 

651 

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

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

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

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

656 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

657 variable, which have one of the following values: 

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

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

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

661 the default value). 

662 

663 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

665 to provide a client certificate for mTLS transport. If 

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

667 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

668 set, no client certificate will be used. 

669 

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

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

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

673 currently not supported for mTLS. 

674 

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

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

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

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

679 your own client library. 

680 

681 Raises: 

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

683 creation failed for any reason. 

684 """ 

685 self._client_options = client_options 

686 if isinstance(self._client_options, dict): 

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

688 if self._client_options is None: 

689 self._client_options = client_options_lib.ClientOptions() 

690 self._client_options = cast( 

691 client_options_lib.ClientOptions, self._client_options 

692 ) 

693 

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

695 

696 ( 

697 self._use_client_cert, 

698 self._use_mtls_endpoint, 

699 self._universe_domain_env, 

700 ) = PublisherClient._read_environment_variables() 

701 self._client_cert_source = PublisherClient._get_client_cert_source( 

702 self._client_options.client_cert_source, self._use_client_cert 

703 ) 

704 self._universe_domain = PublisherClient._get_universe_domain( 

705 universe_domain_opt, self._universe_domain_env 

706 ) 

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

708 

709 # Initialize the universe domain validation. 

710 self._is_universe_domain_valid = False 

711 

712 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER 

713 # Setup logging. 

714 client_logging.initialize_logging() 

715 

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

717 if api_key_value and credentials: 

718 raise ValueError( 

719 "client_options.api_key and credentials are mutually exclusive" 

720 ) 

721 

722 # Save or instantiate the transport. 

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

724 # instance provides an extensibility point for unusual situations. 

725 transport_provided = isinstance(transport, PublisherTransport) 

726 if transport_provided: 

727 # transport is a PublisherTransport instance. 

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

729 raise ValueError( 

730 "When providing a transport instance, " 

731 "provide its credentials directly." 

732 ) 

733 if self._client_options.scopes: 

734 raise ValueError( 

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

736 "directly." 

737 ) 

738 self._transport = cast(PublisherTransport, transport) 

739 self._api_endpoint = self._transport.host 

740 

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

742 self._client_options.api_endpoint, 

743 self._client_cert_source, 

744 self._universe_domain, 

745 self._use_mtls_endpoint, 

746 ) 

747 

748 if not transport_provided: 

749 import google.auth._default # type: ignore 

750 

751 if api_key_value and hasattr( 

752 google.auth._default, "get_api_key_credentials" 

753 ): 

754 credentials = google.auth._default.get_api_key_credentials( 

755 api_key_value 

756 ) 

757 

758 transport_init: Union[ 

759 Type[PublisherTransport], Callable[..., PublisherTransport] 

760 ] = ( 

761 PublisherClient.get_transport_class(transport) 

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

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

764 ) 

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

766 

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

768 if emulator_host: 

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

770 channel = grpc.insecure_channel(target=emulator_host) 

771 else: 

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

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

774 

775 self._transport = transport_init( 

776 credentials=credentials, 

777 credentials_file=self._client_options.credentials_file, 

778 host=self._api_endpoint, 

779 scopes=self._client_options.scopes, 

780 client_cert_source_for_mtls=self._client_cert_source, 

781 quota_project_id=self._client_options.quota_project_id, 

782 client_info=client_info, 

783 always_use_jwt_access=True, 

784 api_audience=self._client_options.api_audience, 

785 ) 

786 

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

788 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

789 std_logging.DEBUG 

790 ): # pragma: NO COVER 

791 _LOGGER.debug( 

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

793 extra={ 

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

795 "universeDomain": getattr( 

796 self._transport._credentials, "universe_domain", "" 

797 ), 

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

799 "credentialsInfo": getattr( 

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

801 )(), 

802 } 

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

804 else { 

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

806 "credentialsType": None, 

807 }, 

808 ) 

809 

810 def create_topic( 

811 self, 

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

813 *, 

814 name: Optional[str] = None, 

815 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

816 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

818 ) -> pubsub.Topic: 

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

820 name rules] 

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

822 

823 .. code-block:: python 

824 

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

826 # code template only. 

827 # It will require modifications to work: 

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

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

830 # client as shown in: 

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

832 from google import pubsub_v1 

833 

834 def sample_create_topic(): 

835 # Create a client 

836 client = pubsub_v1.PublisherClient() 

837 

838 # Initialize request argument(s) 

839 request = pubsub_v1.Topic( 

840 name="name_value", 

841 ) 

842 

843 # Make the request 

844 response = client.create_topic(request=request) 

845 

846 # Handle the response 

847 print(response) 

848 

849 Args: 

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

851 The request object. A topic resource. 

852 name (str): 

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

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

855 must start with a letter, and contain only letters 

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

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

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

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

860 start with ``"goog"``. 

861 

862 This corresponds to the ``name`` field 

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

864 should not be set. 

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

866 should be retried. 

867 timeout (TimeoutType): 

868 The timeout for this request. 

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

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

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

872 be of type `bytes`. 

873 

874 Returns: 

875 google.pubsub_v1.types.Topic: 

876 A topic resource. 

877 """ 

878 # Create or coerce a protobuf request object. 

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

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

881 flattened_params = [name] 

882 has_flattened_params = ( 

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

884 ) 

885 if request is not None and has_flattened_params: 

886 raise ValueError( 

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

888 "the individual field arguments should be set." 

889 ) 

890 

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

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

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

894 request = pubsub.Topic(request) 

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

896 # request, apply these. 

897 if name is not None: 

898 request.name = name 

899 

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

901 # and friendly error handling. 

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

903 

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

905 # add these here. 

906 metadata = tuple(metadata) + ( 

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

908 ) 

909 

910 # Validate the universe domain. 

911 self._validate_universe_domain() 

912 

913 # Send the request. 

914 response = rpc( 

915 request, 

916 retry=retry, 

917 timeout=timeout, 

918 metadata=metadata, 

919 ) 

920 

921 # Done; return the response. 

922 return response 

923 

924 def update_topic( 

925 self, 

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

927 *, 

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

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

930 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

931 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

933 ) -> pubsub.Topic: 

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

935 specified in the update mask. Note that certain 

936 properties of a topic are not modifiable. 

937 

938 .. code-block:: python 

939 

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

941 # code template only. 

942 # It will require modifications to work: 

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

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

945 # client as shown in: 

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

947 from google import pubsub_v1 

948 

949 def sample_update_topic(): 

950 # Create a client 

951 client = pubsub_v1.PublisherClient() 

952 

953 # Initialize request argument(s) 

954 topic = pubsub_v1.Topic() 

955 topic.name = "name_value" 

956 

957 request = pubsub_v1.UpdateTopicRequest( 

958 topic=topic, 

959 ) 

960 

961 # Make the request 

962 response = client.update_topic(request=request) 

963 

964 # Handle the response 

965 print(response) 

966 

967 Args: 

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

969 The request object. Request for the UpdateTopic method. 

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

971 Required. The updated topic object. 

972 This corresponds to the ``topic`` field 

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

974 should not be set. 

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

976 Required. Indicates which fields in the provided topic 

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

978 ``update_mask`` contains "message_storage_policy" but 

979 the ``message_storage_policy`` is not set in the 

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

981 determined by the policy configured at the project or 

982 organization level. 

983 

984 This corresponds to the ``update_mask`` field 

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

986 should not be set. 

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

988 should be retried. 

989 timeout (TimeoutType): 

990 The timeout for this request. 

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

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

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

994 be of type `bytes`. 

995 

996 Returns: 

997 google.pubsub_v1.types.Topic: 

998 A topic resource. 

999 """ 

1000 # Create or coerce a protobuf request object. 

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

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

1003 flattened_params = [topic, update_mask] 

1004 has_flattened_params = ( 

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

1006 ) 

1007 if request is not None and has_flattened_params: 

1008 raise ValueError( 

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

1010 "the individual field arguments should be set." 

1011 ) 

1012 

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

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

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

1016 request = pubsub.UpdateTopicRequest(request) 

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

1018 # request, apply these. 

1019 if topic is not None: 

1020 request.topic = topic 

1021 if update_mask is not None: 

1022 request.update_mask = update_mask 

1023 

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

1025 # and friendly error handling. 

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

1027 

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

1029 # add these here. 

1030 metadata = tuple(metadata) + ( 

1031 gapic_v1.routing_header.to_grpc_metadata( 

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

1033 ), 

1034 ) 

1035 

1036 # Validate the universe domain. 

1037 self._validate_universe_domain() 

1038 

1039 # Send the request. 

1040 response = rpc( 

1041 request, 

1042 retry=retry, 

1043 timeout=timeout, 

1044 metadata=metadata, 

1045 ) 

1046 

1047 # Done; return the response. 

1048 return response 

1049 

1050 def publish( 

1051 self, 

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

1053 *, 

1054 topic: Optional[str] = None, 

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

1056 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1057 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1059 ) -> pubsub.PublishResponse: 

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

1061 the topic does not exist. 

1062 

1063 .. code-block:: python 

1064 

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

1066 # code template only. 

1067 # It will require modifications to work: 

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

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

1070 # client as shown in: 

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

1072 from google import pubsub_v1 

1073 

1074 def sample_publish(): 

1075 # Create a client 

1076 client = pubsub_v1.PublisherClient() 

1077 

1078 # Initialize request argument(s) 

1079 request = pubsub_v1.PublishRequest( 

1080 topic="topic_value", 

1081 ) 

1082 

1083 # Make the request 

1084 response = client.publish(request=request) 

1085 

1086 # Handle the response 

1087 print(response) 

1088 

1089 Args: 

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

1091 The request object. Request for the Publish method. 

1092 topic (str): 

1093 Required. The messages in the request will be published 

1094 on this topic. Format is 

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

1096 

1097 This corresponds to the ``topic`` field 

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

1099 should not be set. 

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

1101 Required. The messages to publish. 

1102 This corresponds to the ``messages`` field 

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

1104 should not be set. 

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

1106 should be retried. 

1107 timeout (TimeoutType): 

1108 The timeout for this request. 

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

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

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

1112 be of type `bytes`. 

1113 

1114 Returns: 

1115 google.pubsub_v1.types.PublishResponse: 

1116 Response for the Publish method. 

1117 """ 

1118 # Create or coerce a protobuf request object. 

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

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

1121 flattened_params = [topic, messages] 

1122 has_flattened_params = ( 

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

1124 ) 

1125 if request is not None and has_flattened_params: 

1126 raise ValueError( 

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

1128 "the individual field arguments should be set." 

1129 ) 

1130 

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

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

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

1134 request = pubsub.PublishRequest(request) 

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

1136 # request, apply these. 

1137 if topic is not None: 

1138 request.topic = topic 

1139 if messages is not None: 

1140 request.messages = messages 

1141 

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

1143 # and friendly error handling. 

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

1145 

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

1147 # add these here. 

1148 metadata = tuple(metadata) + ( 

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

1150 ) 

1151 

1152 # Validate the universe domain. 

1153 self._validate_universe_domain() 

1154 

1155 # Send the request. 

1156 response = rpc( 

1157 request, 

1158 retry=retry, 

1159 timeout=timeout, 

1160 metadata=metadata, 

1161 ) 

1162 

1163 # Done; return the response. 

1164 return response 

1165 

1166 def get_topic( 

1167 self, 

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

1169 *, 

1170 topic: Optional[str] = None, 

1171 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1172 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1174 ) -> pubsub.Topic: 

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

1176 

1177 .. code-block:: python 

1178 

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

1180 # code template only. 

1181 # It will require modifications to work: 

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

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

1184 # client as shown in: 

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

1186 from google import pubsub_v1 

1187 

1188 def sample_get_topic(): 

1189 # Create a client 

1190 client = pubsub_v1.PublisherClient() 

1191 

1192 # Initialize request argument(s) 

1193 request = pubsub_v1.GetTopicRequest( 

1194 topic="topic_value", 

1195 ) 

1196 

1197 # Make the request 

1198 response = client.get_topic(request=request) 

1199 

1200 # Handle the response 

1201 print(response) 

1202 

1203 Args: 

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

1205 The request object. Request for the GetTopic method. 

1206 topic (str): 

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

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

1209 

1210 This corresponds to the ``topic`` field 

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

1212 should not be set. 

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

1214 should be retried. 

1215 timeout (TimeoutType): 

1216 The timeout for this request. 

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

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

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

1220 be of type `bytes`. 

1221 

1222 Returns: 

1223 google.pubsub_v1.types.Topic: 

1224 A topic resource. 

1225 """ 

1226 # Create or coerce a protobuf request object. 

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

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

1229 flattened_params = [topic] 

1230 has_flattened_params = ( 

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

1232 ) 

1233 if request is not None and has_flattened_params: 

1234 raise ValueError( 

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

1236 "the individual field arguments should be set." 

1237 ) 

1238 

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

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

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

1242 request = pubsub.GetTopicRequest(request) 

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

1244 # request, apply these. 

1245 if topic is not None: 

1246 request.topic = topic 

1247 

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

1249 # and friendly error handling. 

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

1251 

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

1253 # add these here. 

1254 metadata = tuple(metadata) + ( 

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

1256 ) 

1257 

1258 # Validate the universe domain. 

1259 self._validate_universe_domain() 

1260 

1261 # Send the request. 

1262 response = rpc( 

1263 request, 

1264 retry=retry, 

1265 timeout=timeout, 

1266 metadata=metadata, 

1267 ) 

1268 

1269 # Done; return the response. 

1270 return response 

1271 

1272 def list_topics( 

1273 self, 

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

1275 *, 

1276 project: Optional[str] = None, 

1277 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1278 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1280 ) -> pagers.ListTopicsPager: 

1281 r"""Lists matching topics. 

1282 

1283 .. code-block:: python 

1284 

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

1286 # code template only. 

1287 # It will require modifications to work: 

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

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

1290 # client as shown in: 

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

1292 from google import pubsub_v1 

1293 

1294 def sample_list_topics(): 

1295 # Create a client 

1296 client = pubsub_v1.PublisherClient() 

1297 

1298 # Initialize request argument(s) 

1299 request = pubsub_v1.ListTopicsRequest( 

1300 project="project_value", 

1301 ) 

1302 

1303 # Make the request 

1304 page_result = client.list_topics(request=request) 

1305 

1306 # Handle the response 

1307 for response in page_result: 

1308 print(response) 

1309 

1310 Args: 

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

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

1313 project (str): 

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

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

1316 

1317 This corresponds to the ``project`` field 

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

1319 should not be set. 

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

1321 should be retried. 

1322 timeout (TimeoutType): 

1323 The timeout for this request. 

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

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

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

1327 be of type `bytes`. 

1328 

1329 Returns: 

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

1331 Response for the ListTopics method. 

1332 

1333 Iterating over this object will yield results and 

1334 resolve additional pages automatically. 

1335 

1336 """ 

1337 # Create or coerce a protobuf request object. 

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

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

1340 flattened_params = [project] 

1341 has_flattened_params = ( 

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

1343 ) 

1344 if request is not None and has_flattened_params: 

1345 raise ValueError( 

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

1347 "the individual field arguments should be set." 

1348 ) 

1349 

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

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

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

1353 request = pubsub.ListTopicsRequest(request) 

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

1355 # request, apply these. 

1356 if project is not None: 

1357 request.project = project 

1358 

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

1360 # and friendly error handling. 

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

1362 

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

1364 # add these here. 

1365 metadata = tuple(metadata) + ( 

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

1367 ) 

1368 

1369 # Validate the universe domain. 

1370 self._validate_universe_domain() 

1371 

1372 # Send the request. 

1373 response = rpc( 

1374 request, 

1375 retry=retry, 

1376 timeout=timeout, 

1377 metadata=metadata, 

1378 ) 

1379 

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

1381 # an `__iter__` convenience method. 

1382 response = pagers.ListTopicsPager( 

1383 method=rpc, 

1384 request=request, 

1385 response=response, 

1386 retry=retry, 

1387 timeout=timeout, 

1388 metadata=metadata, 

1389 ) 

1390 

1391 # Done; return the response. 

1392 return response 

1393 

1394 def list_topic_subscriptions( 

1395 self, 

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

1397 *, 

1398 topic: Optional[str] = None, 

1399 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1400 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1402 ) -> pagers.ListTopicSubscriptionsPager: 

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

1404 topic. 

1405 

1406 .. code-block:: python 

1407 

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

1409 # code template only. 

1410 # It will require modifications to work: 

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

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

1413 # client as shown in: 

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

1415 from google import pubsub_v1 

1416 

1417 def sample_list_topic_subscriptions(): 

1418 # Create a client 

1419 client = pubsub_v1.PublisherClient() 

1420 

1421 # Initialize request argument(s) 

1422 request = pubsub_v1.ListTopicSubscriptionsRequest( 

1423 topic="topic_value", 

1424 ) 

1425 

1426 # Make the request 

1427 page_result = client.list_topic_subscriptions(request=request) 

1428 

1429 # Handle the response 

1430 for response in page_result: 

1431 print(response) 

1432 

1433 Args: 

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

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

1436 topic (str): 

1437 Required. The name of the topic that subscriptions are 

1438 attached to. Format is 

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

1440 

1441 This corresponds to the ``topic`` field 

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

1443 should not be set. 

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

1445 should be retried. 

1446 timeout (TimeoutType): 

1447 The timeout for this request. 

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

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

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

1451 be of type `bytes`. 

1452 

1453 Returns: 

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

1455 Response for the ListTopicSubscriptions method. 

1456 

1457 Iterating over this object will yield results and 

1458 resolve additional pages automatically. 

1459 

1460 """ 

1461 # Create or coerce a protobuf request object. 

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

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

1464 flattened_params = [topic] 

1465 has_flattened_params = ( 

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

1467 ) 

1468 if request is not None and has_flattened_params: 

1469 raise ValueError( 

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

1471 "the individual field arguments should be set." 

1472 ) 

1473 

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

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

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

1477 request = pubsub.ListTopicSubscriptionsRequest(request) 

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

1479 # request, apply these. 

1480 if topic is not None: 

1481 request.topic = topic 

1482 

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

1484 # and friendly error handling. 

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

1486 

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

1488 # add these here. 

1489 metadata = tuple(metadata) + ( 

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

1491 ) 

1492 

1493 # Validate the universe domain. 

1494 self._validate_universe_domain() 

1495 

1496 # Send the request. 

1497 response = rpc( 

1498 request, 

1499 retry=retry, 

1500 timeout=timeout, 

1501 metadata=metadata, 

1502 ) 

1503 

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

1505 # an `__iter__` convenience method. 

1506 response = pagers.ListTopicSubscriptionsPager( 

1507 method=rpc, 

1508 request=request, 

1509 response=response, 

1510 retry=retry, 

1511 timeout=timeout, 

1512 metadata=metadata, 

1513 ) 

1514 

1515 # Done; return the response. 

1516 return response 

1517 

1518 def list_topic_snapshots( 

1519 self, 

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

1521 *, 

1522 topic: Optional[str] = None, 

1523 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1524 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1526 ) -> pagers.ListTopicSnapshotsPager: 

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

1528 used in 

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

1530 operations, which allow you to manage message acknowledgments in 

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

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

1533 

1534 .. code-block:: python 

1535 

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

1537 # code template only. 

1538 # It will require modifications to work: 

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

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

1541 # client as shown in: 

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

1543 from google import pubsub_v1 

1544 

1545 def sample_list_topic_snapshots(): 

1546 # Create a client 

1547 client = pubsub_v1.PublisherClient() 

1548 

1549 # Initialize request argument(s) 

1550 request = pubsub_v1.ListTopicSnapshotsRequest( 

1551 topic="topic_value", 

1552 ) 

1553 

1554 # Make the request 

1555 page_result = client.list_topic_snapshots(request=request) 

1556 

1557 # Handle the response 

1558 for response in page_result: 

1559 print(response) 

1560 

1561 Args: 

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

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

1564 topic (str): 

1565 Required. The name of the topic that snapshots are 

1566 attached to. Format is 

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

1568 

1569 This corresponds to the ``topic`` field 

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

1571 should not be set. 

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

1573 should be retried. 

1574 timeout (TimeoutType): 

1575 The timeout for this request. 

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

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

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

1579 be of type `bytes`. 

1580 

1581 Returns: 

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

1583 Response for the ListTopicSnapshots method. 

1584 

1585 Iterating over this object will yield results and 

1586 resolve additional pages automatically. 

1587 

1588 """ 

1589 # Create or coerce a protobuf request object. 

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

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

1592 flattened_params = [topic] 

1593 has_flattened_params = ( 

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

1595 ) 

1596 if request is not None and has_flattened_params: 

1597 raise ValueError( 

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

1599 "the individual field arguments should be set." 

1600 ) 

1601 

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

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

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

1605 request = pubsub.ListTopicSnapshotsRequest(request) 

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

1607 # request, apply these. 

1608 if topic is not None: 

1609 request.topic = topic 

1610 

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

1612 # and friendly error handling. 

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

1614 

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

1616 # add these here. 

1617 metadata = tuple(metadata) + ( 

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

1619 ) 

1620 

1621 # Validate the universe domain. 

1622 self._validate_universe_domain() 

1623 

1624 # Send the request. 

1625 response = rpc( 

1626 request, 

1627 retry=retry, 

1628 timeout=timeout, 

1629 metadata=metadata, 

1630 ) 

1631 

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

1633 # an `__iter__` convenience method. 

1634 response = pagers.ListTopicSnapshotsPager( 

1635 method=rpc, 

1636 request=request, 

1637 response=response, 

1638 retry=retry, 

1639 timeout=timeout, 

1640 metadata=metadata, 

1641 ) 

1642 

1643 # Done; return the response. 

1644 return response 

1645 

1646 def delete_topic( 

1647 self, 

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

1649 *, 

1650 topic: Optional[str] = None, 

1651 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1652 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1654 ) -> None: 

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

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

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

1658 with none of the old configuration or subscriptions. Existing 

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

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

1661 

1662 .. code-block:: python 

1663 

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

1665 # code template only. 

1666 # It will require modifications to work: 

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

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

1669 # client as shown in: 

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

1671 from google import pubsub_v1 

1672 

1673 def sample_delete_topic(): 

1674 # Create a client 

1675 client = pubsub_v1.PublisherClient() 

1676 

1677 # Initialize request argument(s) 

1678 request = pubsub_v1.DeleteTopicRequest( 

1679 topic="topic_value", 

1680 ) 

1681 

1682 # Make the request 

1683 client.delete_topic(request=request) 

1684 

1685 Args: 

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

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

1688 topic (str): 

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

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

1691 

1692 This corresponds to the ``topic`` field 

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

1694 should not be set. 

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

1696 should be retried. 

1697 timeout (TimeoutType): 

1698 The timeout for this request. 

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

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

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

1702 be of type `bytes`. 

1703 """ 

1704 # Create or coerce a protobuf request object. 

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

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

1707 flattened_params = [topic] 

1708 has_flattened_params = ( 

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

1710 ) 

1711 if request is not None and has_flattened_params: 

1712 raise ValueError( 

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

1714 "the individual field arguments should be set." 

1715 ) 

1716 

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

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

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

1720 request = pubsub.DeleteTopicRequest(request) 

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

1722 # request, apply these. 

1723 if topic is not None: 

1724 request.topic = topic 

1725 

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

1727 # and friendly error handling. 

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

1729 

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

1731 # add these here. 

1732 metadata = tuple(metadata) + ( 

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

1734 ) 

1735 

1736 # Validate the universe domain. 

1737 self._validate_universe_domain() 

1738 

1739 # Send the request. 

1740 rpc( 

1741 request, 

1742 retry=retry, 

1743 timeout=timeout, 

1744 metadata=metadata, 

1745 ) 

1746 

1747 def detach_subscription( 

1748 self, 

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

1750 *, 

1751 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1752 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1754 ) -> pubsub.DetachSubscriptionResponse: 

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

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

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

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

1759 will stop. 

1760 

1761 .. code-block:: python 

1762 

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

1764 # code template only. 

1765 # It will require modifications to work: 

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

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

1768 # client as shown in: 

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

1770 from google import pubsub_v1 

1771 

1772 def sample_detach_subscription(): 

1773 # Create a client 

1774 client = pubsub_v1.PublisherClient() 

1775 

1776 # Initialize request argument(s) 

1777 request = pubsub_v1.DetachSubscriptionRequest( 

1778 subscription="subscription_value", 

1779 ) 

1780 

1781 # Make the request 

1782 response = client.detach_subscription(request=request) 

1783 

1784 # Handle the response 

1785 print(response) 

1786 

1787 Args: 

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

1789 The request object. Request for the DetachSubscription 

1790 method. 

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

1792 should be retried. 

1793 timeout (TimeoutType): 

1794 The timeout for this request. 

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

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

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

1798 be of type `bytes`. 

1799 

1800 Returns: 

1801 google.pubsub_v1.types.DetachSubscriptionResponse: 

1802 Response for the DetachSubscription 

1803 method. Reserved for future use. 

1804 

1805 """ 

1806 # Create or coerce a protobuf request object. 

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

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

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

1810 request = pubsub.DetachSubscriptionRequest(request) 

1811 

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

1813 # and friendly error handling. 

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

1815 

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

1817 # add these here. 

1818 metadata = tuple(metadata) + ( 

1819 gapic_v1.routing_header.to_grpc_metadata( 

1820 (("subscription", request.subscription),) 

1821 ), 

1822 ) 

1823 

1824 # Validate the universe domain. 

1825 self._validate_universe_domain() 

1826 

1827 # Send the request. 

1828 response = rpc( 

1829 request, 

1830 retry=retry, 

1831 timeout=timeout, 

1832 metadata=metadata, 

1833 ) 

1834 

1835 # Done; return the response. 

1836 return response 

1837 

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

1839 return self 

1840 

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

1842 """Releases underlying transport's resources. 

1843 

1844 .. warning:: 

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

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

1847 and may cause errors in other clients! 

1848 """ 

1849 self.transport.close() 

1850 

1851 def set_iam_policy( 

1852 self, 

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

1854 *, 

1855 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1856 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1858 ) -> policy_pb2.Policy: 

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

1860 

1861 Replaces any existing policy. 

1862 

1863 Args: 

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

1865 The request object. Request message for `SetIamPolicy` 

1866 method. 

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

1868 should be retried. 

1869 timeout (TimeoutType): 

1870 The timeout for this request. 

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

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

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

1874 be of type `bytes`. 

1875 Returns: 

1876 ~.policy_pb2.Policy: 

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

1878 It is used to specify access control policies for Cloud 

1879 Platform resources. 

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

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

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

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

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

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

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

1887 expression that further constrains the role binding 

1888 based on attributes about the request and/or target 

1889 resource. 

1890 

1891 **JSON Example** 

1892 

1893 :: 

1894 

1895 { 

1896 "bindings": [ 

1897 { 

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

1899 "members": [ 

1900 "user:mike@example.com", 

1901 "group:admins@example.com", 

1902 "domain:google.com", 

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

1904 ] 

1905 }, 

1906 { 

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

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

1909 "condition": { 

1910 "title": "expirable access", 

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

1912 "expression": "request.time < 

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

1914 } 

1915 } 

1916 ] 

1917 } 

1918 

1919 **YAML Example** 

1920 

1921 :: 

1922 

1923 bindings: 

1924 - members: 

1925 - user:mike@example.com 

1926 - group:admins@example.com 

1927 - domain:google.com 

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

1929 role: roles/resourcemanager.organizationAdmin 

1930 - members: 

1931 - user:eve@example.com 

1932 role: roles/resourcemanager.organizationViewer 

1933 condition: 

1934 title: expirable access 

1935 description: Does not grant access after Sep 2020 

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

1937 

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

1939 developer's 

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

1941 """ 

1942 # Create or coerce a protobuf request object. 

1943 

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

1945 # so it must be constructed via keyword expansion. 

1946 if isinstance(request, dict): 

1947 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

1948 

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

1950 # and friendly error handling. 

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

1952 

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

1954 # add these here. 

1955 metadata = tuple(metadata) + ( 

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

1957 ) 

1958 

1959 # Validate the universe domain. 

1960 self._validate_universe_domain() 

1961 

1962 try: 

1963 # Send the request. 

1964 response = rpc( 

1965 request, 

1966 retry=retry, 

1967 timeout=timeout, 

1968 metadata=metadata, 

1969 ) 

1970 

1971 # Done; return the response. 

1972 return response 

1973 except core_exceptions.GoogleAPICallError as e: 

1974 self._add_cred_info_for_auth_errors(e) 

1975 raise e 

1976 

1977 def get_iam_policy( 

1978 self, 

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

1980 *, 

1981 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

1982 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

1984 ) -> policy_pb2.Policy: 

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

1986 

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

1988 policy set. 

1989 

1990 Args: 

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

1992 The request object. Request message for `GetIamPolicy` 

1993 method. 

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

1995 any, should be retried. 

1996 timeout (TimeoutType): 

1997 The timeout for this request. 

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

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

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

2001 be of type `bytes`. 

2002 Returns: 

2003 ~.policy_pb2.Policy: 

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

2005 It is used to specify access control policies for Cloud 

2006 Platform resources. 

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

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

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

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

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

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

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

2014 expression that further constrains the role binding 

2015 based on attributes about the request and/or target 

2016 resource. 

2017 

2018 **JSON Example** 

2019 

2020 :: 

2021 

2022 { 

2023 "bindings": [ 

2024 { 

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

2026 "members": [ 

2027 "user:mike@example.com", 

2028 "group:admins@example.com", 

2029 "domain:google.com", 

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

2031 ] 

2032 }, 

2033 { 

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

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

2036 "condition": { 

2037 "title": "expirable access", 

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

2039 "expression": "request.time < 

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

2041 } 

2042 } 

2043 ] 

2044 } 

2045 

2046 **YAML Example** 

2047 

2048 :: 

2049 

2050 bindings: 

2051 - members: 

2052 - user:mike@example.com 

2053 - group:admins@example.com 

2054 - domain:google.com 

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

2056 role: roles/resourcemanager.organizationAdmin 

2057 - members: 

2058 - user:eve@example.com 

2059 role: roles/resourcemanager.organizationViewer 

2060 condition: 

2061 title: expirable access 

2062 description: Does not grant access after Sep 2020 

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

2064 

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

2066 developer's 

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

2068 """ 

2069 # Create or coerce a protobuf request object. 

2070 

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

2072 # so it must be constructed via keyword expansion. 

2073 if isinstance(request, dict): 

2074 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

2075 

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

2077 # and friendly error handling. 

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

2079 

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

2081 # add these here. 

2082 metadata = tuple(metadata) + ( 

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

2084 ) 

2085 

2086 # Validate the universe domain. 

2087 self._validate_universe_domain() 

2088 

2089 try: 

2090 # Send the request. 

2091 response = rpc( 

2092 request, 

2093 retry=retry, 

2094 timeout=timeout, 

2095 metadata=metadata, 

2096 ) 

2097 

2098 # Done; return the response. 

2099 return response 

2100 except core_exceptions.GoogleAPICallError as e: 

2101 self._add_cred_info_for_auth_errors(e) 

2102 raise e 

2103 

2104 def test_iam_permissions( 

2105 self, 

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

2107 *, 

2108 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

2109 timeout: TimeoutType = gapic_v1.method.DEFAULT, 

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

2111 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

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

2113 policy for a function. 

2114 

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

2116 of permissions, not a NOT_FOUND error. 

2117 

2118 Args: 

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

2120 The request object. Request message for 

2121 `TestIamPermissions` method. 

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

2123 if any, should be retried. 

2124 timeout (TimeoutType): 

2125 The timeout for this request. 

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

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

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

2129 be of type `bytes`. 

2130 Returns: 

2131 ~.iam_policy_pb2.TestIamPermissionsResponse: 

2132 Response message for ``TestIamPermissions`` method. 

2133 """ 

2134 # Create or coerce a protobuf request object. 

2135 

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

2137 # so it must be constructed via keyword expansion. 

2138 if isinstance(request, dict): 

2139 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

2140 

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

2142 # and friendly error handling. 

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

2144 

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

2146 # add these here. 

2147 metadata = tuple(metadata) + ( 

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

2149 ) 

2150 

2151 # Validate the universe domain. 

2152 self._validate_universe_domain() 

2153 

2154 try: 

2155 # Send the request. 

2156 response = rpc( 

2157 request, 

2158 retry=retry, 

2159 timeout=timeout, 

2160 metadata=metadata, 

2161 ) 

2162 

2163 # Done; return the response. 

2164 return response 

2165 except core_exceptions.GoogleAPICallError as e: 

2166 self._add_cred_info_for_auth_errors(e) 

2167 raise e 

2168 

2169 

2170DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

2171 client_library_version=package_version.__version__ 

2172) 

2173 

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

2175 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__ 

2176 

2177__all__ = ("PublisherClient",)