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

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

424 statements  

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

2# Copyright 2024 Google LLC 

3# 

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

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

6# You may obtain a copy of the License at 

7# 

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

9# 

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

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

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

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

14# limitations under the License. 

15# 

16from collections import OrderedDict 

17from http import HTTPStatus 

18import json 

19import logging as std_logging 

20import functools 

21import os 

22import re 

23from typing import ( 

24 Dict, 

25 Callable, 

26 Mapping, 

27 MutableMapping, 

28 MutableSequence, 

29 Optional, 

30 Sequence, 

31 Tuple, 

32 Type, 

33 Union, 

34 cast, 

35) 

36import warnings 

37 

38from google.pubsub_v1 import gapic_version as package_version 

39 

40from google.api_core import client_options as client_options_lib 

41from google.api_core import exceptions as core_exceptions 

42from google.api_core import gapic_v1 

43from google.api_core import retry as retries 

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

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

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

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

48from google.oauth2 import service_account # type: ignore 

49 

50try: 

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

52except AttributeError: # pragma: NO COVER 

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

54 

55try: 

56 from google.api_core import client_logging # type: ignore 

57 

58 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER 

59except ImportError: # pragma: NO COVER 

60 CLIENT_LOGGING_SUPPORTED = False 

61 

62_LOGGER = std_logging.getLogger(__name__) 

63 

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

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

66from google.protobuf import timestamp_pb2 # type: ignore 

67from google.pubsub_v1.services.schema_service import pagers 

68from google.pubsub_v1.types import schema 

69from google.pubsub_v1.types import schema as gp_schema 

70 

71import grpc 

72from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO 

73from .transports.grpc import SchemaServiceGrpcTransport 

74from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport 

75from .transports.rest import SchemaServiceRestTransport 

76 

77 

78class SchemaServiceClientMeta(type): 

79 """Metaclass for the SchemaService client. 

80 

81 This provides class-level methods for building and retrieving 

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

83 objects. 

84 """ 

85 

86 _transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]] 

87 _transport_registry["grpc"] = SchemaServiceGrpcTransport 

88 _transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport 

89 _transport_registry["rest"] = SchemaServiceRestTransport 

90 

91 def get_transport_class( 

92 cls, 

93 label: Optional[str] = None, 

94 ) -> Type[SchemaServiceTransport]: 

95 """Returns an appropriate transport class. 

96 

97 Args: 

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

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

100 

101 Returns: 

102 The transport class to use. 

103 """ 

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

105 if label: 

106 return cls._transport_registry[label] 

107 

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

109 # in the dictionary). 

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

111 

112 

113class SchemaServiceClient(metaclass=SchemaServiceClientMeta): 

114 """Service for doing schema-related operations.""" 

115 

116 @staticmethod 

117 def _get_default_mtls_endpoint(api_endpoint): 

118 """Converts api endpoint to mTLS endpoint. 

119 

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

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

122 Args: 

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

124 Returns: 

125 str: converted mTLS api endpoint. 

126 """ 

127 if not api_endpoint: 

128 return api_endpoint 

129 

130 mtls_endpoint_re = re.compile( 

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

132 ) 

133 

134 m = mtls_endpoint_re.match(api_endpoint) 

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

136 if mtls or not googledomain: 

137 return api_endpoint 

138 

139 if sandbox: 

140 return api_endpoint.replace( 

141 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com" 

142 ) 

143 

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

145 

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

147 DEFAULT_ENDPOINT = "pubsub.googleapis.com" 

148 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore 

149 DEFAULT_ENDPOINT 

150 ) 

151 

152 _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}" 

153 _DEFAULT_UNIVERSE = "googleapis.com" 

154 

155 @classmethod 

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

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

158 info. 

159 

160 Args: 

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

162 args: Additional arguments to pass to the constructor. 

163 kwargs: Additional arguments to pass to the constructor. 

164 

165 Returns: 

166 SchemaServiceClient: The constructed client. 

167 """ 

168 credentials = service_account.Credentials.from_service_account_info(info) 

169 kwargs["credentials"] = credentials 

170 return cls(*args, **kwargs) 

171 

172 @classmethod 

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

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

175 file. 

176 

177 Args: 

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

179 file. 

180 args: Additional arguments to pass to the constructor. 

181 kwargs: Additional arguments to pass to the constructor. 

182 

183 Returns: 

184 SchemaServiceClient: The constructed client. 

185 """ 

186 credentials = service_account.Credentials.from_service_account_file(filename) 

187 kwargs["credentials"] = credentials 

188 return cls(*args, **kwargs) 

189 

190 from_service_account_json = from_service_account_file 

191 

192 @property 

193 def transport(self) -> SchemaServiceTransport: 

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

195 

196 Returns: 

197 SchemaServiceTransport: The transport used by the client 

198 instance. 

199 """ 

200 return self._transport 

201 

202 @staticmethod 

203 def schema_path( 

204 project: str, 

205 schema: str, 

206 ) -> str: 

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

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

209 project=project, 

210 schema=schema, 

211 ) 

212 

213 @staticmethod 

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

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

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

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

218 

219 @staticmethod 

220 def common_billing_account_path( 

221 billing_account: str, 

222 ) -> str: 

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

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

225 billing_account=billing_account, 

226 ) 

227 

228 @staticmethod 

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

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

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

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

233 

234 @staticmethod 

235 def common_folder_path( 

236 folder: str, 

237 ) -> str: 

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

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

240 folder=folder, 

241 ) 

242 

243 @staticmethod 

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

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

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

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

248 

249 @staticmethod 

250 def common_organization_path( 

251 organization: str, 

252 ) -> str: 

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

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

255 organization=organization, 

256 ) 

257 

258 @staticmethod 

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

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

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

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

263 

264 @staticmethod 

265 def common_project_path( 

266 project: str, 

267 ) -> str: 

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

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

270 project=project, 

271 ) 

272 

273 @staticmethod 

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

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

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

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

278 

279 @staticmethod 

280 def common_location_path( 

281 project: str, 

282 location: str, 

283 ) -> str: 

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

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

286 project=project, 

287 location=location, 

288 ) 

289 

290 @staticmethod 

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

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

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

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

295 

296 @classmethod 

297 def get_mtls_endpoint_and_cert_source( 

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

299 ): 

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

301 

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

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

304 client cert source is None. 

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

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

307 source is None. 

308 

309 The API endpoint is determined in the following order: 

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

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

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

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

314 use the default API endpoint. 

315 

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

317 

318 Args: 

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

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

321 in this method. 

322 

323 Returns: 

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

325 client cert source to use. 

326 

327 Raises: 

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

329 """ 

330 

331 warnings.warn( 

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

333 DeprecationWarning, 

334 ) 

335 if client_options is None: 

336 client_options = client_options_lib.ClientOptions() 

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

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

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

340 raise ValueError( 

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

342 ) 

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

344 raise MutualTLSChannelError( 

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

346 ) 

347 

348 # Figure out the client cert source to use. 

349 client_cert_source = None 

350 if use_client_cert == "true": 

351 if client_options.client_cert_source: 

352 client_cert_source = client_options.client_cert_source 

353 elif mtls.has_default_client_cert_source(): 

354 client_cert_source = mtls.default_client_cert_source() 

355 

356 # Figure out which api endpoint to use. 

357 if client_options.api_endpoint is not None: 

358 api_endpoint = client_options.api_endpoint 

359 elif use_mtls_endpoint == "always" or ( 

360 use_mtls_endpoint == "auto" and client_cert_source 

361 ): 

362 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT 

363 else: 

364 api_endpoint = cls.DEFAULT_ENDPOINT 

365 

366 return api_endpoint, client_cert_source 

367 

368 @staticmethod 

369 def _read_environment_variables(): 

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

371 

372 Returns: 

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

374 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables. 

375 

376 Raises: 

377 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not 

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

379 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT 

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

381 """ 

382 use_client_cert = os.getenv( 

383 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false" 

384 ).lower() 

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

386 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN") 

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

388 raise ValueError( 

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

390 ) 

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

392 raise MutualTLSChannelError( 

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

394 ) 

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

396 

397 @staticmethod 

398 def _get_client_cert_source(provided_cert_source, use_cert_flag): 

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

400 

401 Args: 

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

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

404 

405 Returns: 

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

407 """ 

408 client_cert_source = None 

409 if use_cert_flag: 

410 if provided_cert_source: 

411 client_cert_source = provided_cert_source 

412 elif mtls.has_default_client_cert_source(): 

413 client_cert_source = mtls.default_client_cert_source() 

414 return client_cert_source 

415 

416 @staticmethod 

417 def _get_api_endpoint( 

418 api_override, client_cert_source, universe_domain, use_mtls_endpoint 

419 ): 

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

421 

422 Args: 

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

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

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

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

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

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

429 

430 Returns: 

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

432 """ 

433 if api_override is not None: 

434 api_endpoint = api_override 

435 elif use_mtls_endpoint == "always" or ( 

436 use_mtls_endpoint == "auto" and client_cert_source 

437 ): 

438 _default_universe = SchemaServiceClient._DEFAULT_UNIVERSE 

439 if universe_domain != _default_universe: 

440 raise MutualTLSChannelError( 

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

442 ) 

443 api_endpoint = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT 

444 else: 

445 api_endpoint = SchemaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format( 

446 UNIVERSE_DOMAIN=universe_domain 

447 ) 

448 return api_endpoint 

449 

450 @staticmethod 

451 def _get_universe_domain( 

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

453 ) -> str: 

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

455 

456 Args: 

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

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

459 

460 Returns: 

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

462 

463 Raises: 

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

465 """ 

466 universe_domain = SchemaServiceClient._DEFAULT_UNIVERSE 

467 if client_universe_domain is not None: 

468 universe_domain = client_universe_domain 

469 elif universe_domain_env is not None: 

470 universe_domain = universe_domain_env 

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

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

473 return universe_domain 

474 

475 def _validate_universe_domain(self): 

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

477 

478 Returns: 

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

480 

481 Raises: 

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

483 """ 

484 

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

486 return True 

487 

488 def _add_cred_info_for_auth_errors( 

489 self, error: core_exceptions.GoogleAPICallError 

490 ) -> None: 

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

492 

493 Args: 

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

495 """ 

496 if error.code not in [ 

497 HTTPStatus.UNAUTHORIZED, 

498 HTTPStatus.FORBIDDEN, 

499 HTTPStatus.NOT_FOUND, 

500 ]: 

501 return 

502 

503 cred = self._transport._credentials 

504 

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

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

507 return 

508 

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

510 # is not available 

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

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

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

514 

515 @property 

516 def api_endpoint(self): 

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

518 

519 Returns: 

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

521 """ 

522 return self._api_endpoint 

523 

524 @property 

525 def universe_domain(self) -> str: 

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

527 

528 Returns: 

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

530 """ 

531 return self._universe_domain 

532 

533 def __init__( 

534 self, 

535 *, 

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

537 transport: Optional[ 

538 Union[str, SchemaServiceTransport, Callable[..., SchemaServiceTransport]] 

539 ] = None, 

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

541 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO, 

542 ) -> None: 

543 """Instantiates the schema service client. 

544 

545 Args: 

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

547 authorization credentials to attach to requests. These 

548 credentials identify the application to the service; if none 

549 are specified, the client will attempt to ascertain the 

550 credentials from the environment. 

551 transport (Optional[Union[str,SchemaServiceTransport,Callable[..., SchemaServiceTransport]]]): 

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

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

554 arguments as used in the SchemaServiceTransport constructor. 

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

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

557 Custom options for the client. 

558 

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

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

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

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

563 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment 

564 variable, which have one of the following values: 

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

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

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

568 the default value). 

569 

570 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable 

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

572 to provide a client certificate for mTLS transport. If 

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

574 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not 

575 set, no client certificate will be used. 

576 

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

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

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

580 currently not supported for mTLS. 

581 

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

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

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

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

586 your own client library. 

587 

588 Raises: 

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

590 creation failed for any reason. 

591 """ 

592 self._client_options = client_options 

593 if isinstance(self._client_options, dict): 

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

595 if self._client_options is None: 

596 self._client_options = client_options_lib.ClientOptions() 

597 self._client_options = cast( 

598 client_options_lib.ClientOptions, self._client_options 

599 ) 

600 

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

602 

603 ( 

604 self._use_client_cert, 

605 self._use_mtls_endpoint, 

606 self._universe_domain_env, 

607 ) = SchemaServiceClient._read_environment_variables() 

608 self._client_cert_source = SchemaServiceClient._get_client_cert_source( 

609 self._client_options.client_cert_source, self._use_client_cert 

610 ) 

611 self._universe_domain = SchemaServiceClient._get_universe_domain( 

612 universe_domain_opt, self._universe_domain_env 

613 ) 

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

615 

616 # Initialize the universe domain validation. 

617 self._is_universe_domain_valid = False 

618 

619 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER 

620 # Setup logging. 

621 client_logging.initialize_logging() 

622 

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

624 if api_key_value and credentials: 

625 raise ValueError( 

626 "client_options.api_key and credentials are mutually exclusive" 

627 ) 

628 

629 # Save or instantiate the transport. 

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

631 # instance provides an extensibility point for unusual situations. 

632 transport_provided = isinstance(transport, SchemaServiceTransport) 

633 if transport_provided: 

634 # transport is a SchemaServiceTransport instance. 

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

636 raise ValueError( 

637 "When providing a transport instance, " 

638 "provide its credentials directly." 

639 ) 

640 if self._client_options.scopes: 

641 raise ValueError( 

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

643 "directly." 

644 ) 

645 self._transport = cast(SchemaServiceTransport, transport) 

646 self._api_endpoint = self._transport.host 

647 

648 self._api_endpoint = ( 

649 self._api_endpoint 

650 or SchemaServiceClient._get_api_endpoint( 

651 self._client_options.api_endpoint, 

652 self._client_cert_source, 

653 self._universe_domain, 

654 self._use_mtls_endpoint, 

655 ) 

656 ) 

657 

658 if not transport_provided: 

659 import google.auth._default # type: ignore 

660 

661 if api_key_value and hasattr( 

662 google.auth._default, "get_api_key_credentials" 

663 ): 

664 credentials = google.auth._default.get_api_key_credentials( 

665 api_key_value 

666 ) 

667 

668 transport_init: Union[ 

669 Type[SchemaServiceTransport], Callable[..., SchemaServiceTransport] 

670 ] = ( 

671 SchemaServiceClient.get_transport_class(transport) 

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

673 else cast(Callable[..., SchemaServiceTransport], transport) 

674 ) 

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

676 

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

678 if emulator_host: 

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

680 channel = grpc.insecure_channel(target=emulator_host) 

681 else: 

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

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

684 

685 self._transport = transport_init( 

686 credentials=credentials, 

687 credentials_file=self._client_options.credentials_file, 

688 host=self._api_endpoint, 

689 scopes=self._client_options.scopes, 

690 client_cert_source_for_mtls=self._client_cert_source, 

691 quota_project_id=self._client_options.quota_project_id, 

692 client_info=client_info, 

693 always_use_jwt_access=True, 

694 api_audience=self._client_options.api_audience, 

695 ) 

696 

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

698 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor( 

699 std_logging.DEBUG 

700 ): # pragma: NO COVER 

701 _LOGGER.debug( 

702 "Created client `google.pubsub_v1.SchemaServiceClient`.", 

703 extra={ 

704 "serviceName": "google.pubsub.v1.SchemaService", 

705 "universeDomain": getattr( 

706 self._transport._credentials, "universe_domain", "" 

707 ), 

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

709 "credentialsInfo": getattr( 

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

711 )(), 

712 } 

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

714 else { 

715 "serviceName": "google.pubsub.v1.SchemaService", 

716 "credentialsType": None, 

717 }, 

718 ) 

719 

720 def create_schema( 

721 self, 

722 request: Optional[Union[gp_schema.CreateSchemaRequest, dict]] = None, 

723 *, 

724 parent: Optional[str] = None, 

725 schema: Optional[gp_schema.Schema] = None, 

726 schema_id: Optional[str] = None, 

727 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

730 ) -> gp_schema.Schema: 

731 r"""Creates a schema. 

732 

733 .. code-block:: python 

734 

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

736 # code template only. 

737 # It will require modifications to work: 

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

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

740 # client as shown in: 

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

742 from google import pubsub_v1 

743 

744 def sample_create_schema(): 

745 # Create a client 

746 client = pubsub_v1.SchemaServiceClient() 

747 

748 # Initialize request argument(s) 

749 schema = pubsub_v1.Schema() 

750 schema.name = "name_value" 

751 

752 request = pubsub_v1.CreateSchemaRequest( 

753 parent="parent_value", 

754 schema=schema, 

755 ) 

756 

757 # Make the request 

758 response = client.create_schema(request=request) 

759 

760 # Handle the response 

761 print(response) 

762 

763 Args: 

764 request (Union[google.pubsub_v1.types.CreateSchemaRequest, dict]): 

765 The request object. Request for the CreateSchema method. 

766 parent (str): 

767 Required. The name of the project in which to create the 

768 schema. Format is ``projects/{project-id}``. 

769 

770 This corresponds to the ``parent`` field 

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

772 should not be set. 

773 schema (google.pubsub_v1.types.Schema): 

774 Required. The schema object to create. 

775 

776 This schema's ``name`` parameter is ignored. The schema 

777 object returned by CreateSchema will have a ``name`` 

778 made using the given ``parent`` and ``schema_id``. 

779 

780 This corresponds to the ``schema`` field 

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

782 should not be set. 

783 schema_id (str): 

784 The ID to use for the schema, which will become the 

785 final component of the schema's resource name. 

786 

787 See 

788 https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names 

789 for resource name constraints. 

790 

791 This corresponds to the ``schema_id`` field 

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

793 should not be set. 

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

795 should be retried. 

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

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

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

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

800 be of type `bytes`. 

801 

802 Returns: 

803 google.pubsub_v1.types.Schema: 

804 A schema resource. 

805 """ 

806 # Create or coerce a protobuf request object. 

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

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

809 flattened_params = [parent, schema, schema_id] 

810 has_flattened_params = ( 

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

812 ) 

813 if request is not None and has_flattened_params: 

814 raise ValueError( 

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

816 "the individual field arguments should be set." 

817 ) 

818 

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

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

821 if not isinstance(request, gp_schema.CreateSchemaRequest): 

822 request = gp_schema.CreateSchemaRequest(request) 

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

824 # request, apply these. 

825 if parent is not None: 

826 request.parent = parent 

827 if schema is not None: 

828 request.schema = schema 

829 if schema_id is not None: 

830 request.schema_id = schema_id 

831 

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

833 # and friendly error handling. 

834 rpc = self._transport._wrapped_methods[self._transport.create_schema] 

835 

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

837 # add these here. 

838 metadata = tuple(metadata) + ( 

839 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), 

840 ) 

841 

842 # Validate the universe domain. 

843 self._validate_universe_domain() 

844 

845 # Send the request. 

846 response = rpc( 

847 request, 

848 retry=retry, 

849 timeout=timeout, 

850 metadata=metadata, 

851 ) 

852 

853 # Done; return the response. 

854 return response 

855 

856 def get_schema( 

857 self, 

858 request: Optional[Union[schema.GetSchemaRequest, dict]] = None, 

859 *, 

860 name: Optional[str] = None, 

861 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

864 ) -> schema.Schema: 

865 r"""Gets a schema. 

866 

867 .. code-block:: python 

868 

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

870 # code template only. 

871 # It will require modifications to work: 

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

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

874 # client as shown in: 

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

876 from google import pubsub_v1 

877 

878 def sample_get_schema(): 

879 # Create a client 

880 client = pubsub_v1.SchemaServiceClient() 

881 

882 # Initialize request argument(s) 

883 request = pubsub_v1.GetSchemaRequest( 

884 name="name_value", 

885 ) 

886 

887 # Make the request 

888 response = client.get_schema(request=request) 

889 

890 # Handle the response 

891 print(response) 

892 

893 Args: 

894 request (Union[google.pubsub_v1.types.GetSchemaRequest, dict]): 

895 The request object. Request for the GetSchema method. 

896 name (str): 

897 Required. The name of the schema to get. Format is 

898 ``projects/{project}/schemas/{schema}``. 

899 

900 This corresponds to the ``name`` field 

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

902 should not be set. 

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

904 should be retried. 

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

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

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

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

909 be of type `bytes`. 

910 

911 Returns: 

912 google.pubsub_v1.types.Schema: 

913 A schema resource. 

914 """ 

915 # Create or coerce a protobuf request object. 

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

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

918 flattened_params = [name] 

919 has_flattened_params = ( 

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

921 ) 

922 if request is not None and has_flattened_params: 

923 raise ValueError( 

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

925 "the individual field arguments should be set." 

926 ) 

927 

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

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

930 if not isinstance(request, schema.GetSchemaRequest): 

931 request = schema.GetSchemaRequest(request) 

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

933 # request, apply these. 

934 if name is not None: 

935 request.name = name 

936 

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

938 # and friendly error handling. 

939 rpc = self._transport._wrapped_methods[self._transport.get_schema] 

940 

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

942 # add these here. 

943 metadata = tuple(metadata) + ( 

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

945 ) 

946 

947 # Validate the universe domain. 

948 self._validate_universe_domain() 

949 

950 # Send the request. 

951 response = rpc( 

952 request, 

953 retry=retry, 

954 timeout=timeout, 

955 metadata=metadata, 

956 ) 

957 

958 # Done; return the response. 

959 return response 

960 

961 def list_schemas( 

962 self, 

963 request: Optional[Union[schema.ListSchemasRequest, dict]] = None, 

964 *, 

965 parent: Optional[str] = None, 

966 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

969 ) -> pagers.ListSchemasPager: 

970 r"""Lists schemas in a project. 

971 

972 .. code-block:: python 

973 

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

975 # code template only. 

976 # It will require modifications to work: 

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

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

979 # client as shown in: 

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

981 from google import pubsub_v1 

982 

983 def sample_list_schemas(): 

984 # Create a client 

985 client = pubsub_v1.SchemaServiceClient() 

986 

987 # Initialize request argument(s) 

988 request = pubsub_v1.ListSchemasRequest( 

989 parent="parent_value", 

990 ) 

991 

992 # Make the request 

993 page_result = client.list_schemas(request=request) 

994 

995 # Handle the response 

996 for response in page_result: 

997 print(response) 

998 

999 Args: 

1000 request (Union[google.pubsub_v1.types.ListSchemasRequest, dict]): 

1001 The request object. Request for the ``ListSchemas`` method. 

1002 parent (str): 

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

1004 schemas. Format is ``projects/{project-id}``. 

1005 

1006 This corresponds to the ``parent`` field 

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

1008 should not be set. 

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

1010 should be retried. 

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

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

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

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

1015 be of type `bytes`. 

1016 

1017 Returns: 

1018 google.pubsub_v1.services.schema_service.pagers.ListSchemasPager: 

1019 Response for the ListSchemas method. 

1020 

1021 Iterating over this object will yield results and 

1022 resolve additional pages automatically. 

1023 

1024 """ 

1025 # Create or coerce a protobuf request object. 

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

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

1028 flattened_params = [parent] 

1029 has_flattened_params = ( 

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

1031 ) 

1032 if request is not None and has_flattened_params: 

1033 raise ValueError( 

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

1035 "the individual field arguments should be set." 

1036 ) 

1037 

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

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

1040 if not isinstance(request, schema.ListSchemasRequest): 

1041 request = schema.ListSchemasRequest(request) 

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

1043 # request, apply these. 

1044 if parent is not None: 

1045 request.parent = parent 

1046 

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

1048 # and friendly error handling. 

1049 rpc = self._transport._wrapped_methods[self._transport.list_schemas] 

1050 

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

1052 # add these here. 

1053 metadata = tuple(metadata) + ( 

1054 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), 

1055 ) 

1056 

1057 # Validate the universe domain. 

1058 self._validate_universe_domain() 

1059 

1060 # Send the request. 

1061 response = rpc( 

1062 request, 

1063 retry=retry, 

1064 timeout=timeout, 

1065 metadata=metadata, 

1066 ) 

1067 

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

1069 # an `__iter__` convenience method. 

1070 response = pagers.ListSchemasPager( 

1071 method=rpc, 

1072 request=request, 

1073 response=response, 

1074 retry=retry, 

1075 timeout=timeout, 

1076 metadata=metadata, 

1077 ) 

1078 

1079 # Done; return the response. 

1080 return response 

1081 

1082 def list_schema_revisions( 

1083 self, 

1084 request: Optional[Union[schema.ListSchemaRevisionsRequest, dict]] = None, 

1085 *, 

1086 name: Optional[str] = None, 

1087 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1090 ) -> pagers.ListSchemaRevisionsPager: 

1091 r"""Lists all schema revisions for the named schema. 

1092 

1093 .. code-block:: python 

1094 

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

1096 # code template only. 

1097 # It will require modifications to work: 

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

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

1100 # client as shown in: 

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

1102 from google import pubsub_v1 

1103 

1104 def sample_list_schema_revisions(): 

1105 # Create a client 

1106 client = pubsub_v1.SchemaServiceClient() 

1107 

1108 # Initialize request argument(s) 

1109 request = pubsub_v1.ListSchemaRevisionsRequest( 

1110 name="name_value", 

1111 ) 

1112 

1113 # Make the request 

1114 page_result = client.list_schema_revisions(request=request) 

1115 

1116 # Handle the response 

1117 for response in page_result: 

1118 print(response) 

1119 

1120 Args: 

1121 request (Union[google.pubsub_v1.types.ListSchemaRevisionsRequest, dict]): 

1122 The request object. Request for the ``ListSchemaRevisions`` method. 

1123 name (str): 

1124 Required. The name of the schema to 

1125 list revisions for. 

1126 

1127 This corresponds to the ``name`` field 

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

1129 should not be set. 

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

1131 should be retried. 

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

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

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

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

1136 be of type `bytes`. 

1137 

1138 Returns: 

1139 google.pubsub_v1.services.schema_service.pagers.ListSchemaRevisionsPager: 

1140 Response for the ListSchemaRevisions method. 

1141 

1142 Iterating over this object will yield results and 

1143 resolve additional pages automatically. 

1144 

1145 """ 

1146 # Create or coerce a protobuf request object. 

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

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

1149 flattened_params = [name] 

1150 has_flattened_params = ( 

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

1152 ) 

1153 if request is not None and has_flattened_params: 

1154 raise ValueError( 

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

1156 "the individual field arguments should be set." 

1157 ) 

1158 

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

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

1161 if not isinstance(request, schema.ListSchemaRevisionsRequest): 

1162 request = schema.ListSchemaRevisionsRequest(request) 

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

1164 # request, apply these. 

1165 if name is not None: 

1166 request.name = name 

1167 

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

1169 # and friendly error handling. 

1170 rpc = self._transport._wrapped_methods[self._transport.list_schema_revisions] 

1171 

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

1173 # add these here. 

1174 metadata = tuple(metadata) + ( 

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

1176 ) 

1177 

1178 # Validate the universe domain. 

1179 self._validate_universe_domain() 

1180 

1181 # Send the request. 

1182 response = rpc( 

1183 request, 

1184 retry=retry, 

1185 timeout=timeout, 

1186 metadata=metadata, 

1187 ) 

1188 

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

1190 # an `__iter__` convenience method. 

1191 response = pagers.ListSchemaRevisionsPager( 

1192 method=rpc, 

1193 request=request, 

1194 response=response, 

1195 retry=retry, 

1196 timeout=timeout, 

1197 metadata=metadata, 

1198 ) 

1199 

1200 # Done; return the response. 

1201 return response 

1202 

1203 def commit_schema( 

1204 self, 

1205 request: Optional[Union[gp_schema.CommitSchemaRequest, dict]] = None, 

1206 *, 

1207 name: Optional[str] = None, 

1208 schema: Optional[gp_schema.Schema] = None, 

1209 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1212 ) -> gp_schema.Schema: 

1213 r"""Commits a new schema revision to an existing schema. 

1214 

1215 .. code-block:: python 

1216 

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

1218 # code template only. 

1219 # It will require modifications to work: 

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

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

1222 # client as shown in: 

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

1224 from google import pubsub_v1 

1225 

1226 def sample_commit_schema(): 

1227 # Create a client 

1228 client = pubsub_v1.SchemaServiceClient() 

1229 

1230 # Initialize request argument(s) 

1231 schema = pubsub_v1.Schema() 

1232 schema.name = "name_value" 

1233 

1234 request = pubsub_v1.CommitSchemaRequest( 

1235 name="name_value", 

1236 schema=schema, 

1237 ) 

1238 

1239 # Make the request 

1240 response = client.commit_schema(request=request) 

1241 

1242 # Handle the response 

1243 print(response) 

1244 

1245 Args: 

1246 request (Union[google.pubsub_v1.types.CommitSchemaRequest, dict]): 

1247 The request object. Request for CommitSchema method. 

1248 name (str): 

1249 Required. The name of the schema we are revising. Format 

1250 is ``projects/{project}/schemas/{schema}``. 

1251 

1252 This corresponds to the ``name`` field 

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

1254 should not be set. 

1255 schema (google.pubsub_v1.types.Schema): 

1256 Required. The schema revision to 

1257 commit. 

1258 

1259 This corresponds to the ``schema`` field 

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

1261 should not be set. 

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

1263 should be retried. 

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

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

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

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

1268 be of type `bytes`. 

1269 

1270 Returns: 

1271 google.pubsub_v1.types.Schema: 

1272 A schema resource. 

1273 """ 

1274 # Create or coerce a protobuf request object. 

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

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

1277 flattened_params = [name, schema] 

1278 has_flattened_params = ( 

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

1280 ) 

1281 if request is not None and has_flattened_params: 

1282 raise ValueError( 

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

1284 "the individual field arguments should be set." 

1285 ) 

1286 

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

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

1289 if not isinstance(request, gp_schema.CommitSchemaRequest): 

1290 request = gp_schema.CommitSchemaRequest(request) 

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

1292 # request, apply these. 

1293 if name is not None: 

1294 request.name = name 

1295 if schema is not None: 

1296 request.schema = schema 

1297 

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

1299 # and friendly error handling. 

1300 rpc = self._transport._wrapped_methods[self._transport.commit_schema] 

1301 

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

1303 # add these here. 

1304 metadata = tuple(metadata) + ( 

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

1306 ) 

1307 

1308 # Validate the universe domain. 

1309 self._validate_universe_domain() 

1310 

1311 # Send the request. 

1312 response = rpc( 

1313 request, 

1314 retry=retry, 

1315 timeout=timeout, 

1316 metadata=metadata, 

1317 ) 

1318 

1319 # Done; return the response. 

1320 return response 

1321 

1322 def rollback_schema( 

1323 self, 

1324 request: Optional[Union[schema.RollbackSchemaRequest, dict]] = None, 

1325 *, 

1326 name: Optional[str] = None, 

1327 revision_id: Optional[str] = None, 

1328 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1331 ) -> schema.Schema: 

1332 r"""Creates a new schema revision that is a copy of the provided 

1333 revision_id. 

1334 

1335 .. code-block:: python 

1336 

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

1338 # code template only. 

1339 # It will require modifications to work: 

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

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

1342 # client as shown in: 

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

1344 from google import pubsub_v1 

1345 

1346 def sample_rollback_schema(): 

1347 # Create a client 

1348 client = pubsub_v1.SchemaServiceClient() 

1349 

1350 # Initialize request argument(s) 

1351 request = pubsub_v1.RollbackSchemaRequest( 

1352 name="name_value", 

1353 revision_id="revision_id_value", 

1354 ) 

1355 

1356 # Make the request 

1357 response = client.rollback_schema(request=request) 

1358 

1359 # Handle the response 

1360 print(response) 

1361 

1362 Args: 

1363 request (Union[google.pubsub_v1.types.RollbackSchemaRequest, dict]): 

1364 The request object. Request for the ``RollbackSchema`` method. 

1365 name (str): 

1366 Required. The schema being rolled 

1367 back with revision id. 

1368 

1369 This corresponds to the ``name`` field 

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

1371 should not be set. 

1372 revision_id (str): 

1373 Required. The revision ID to roll 

1374 back to. It must be a revision of the 

1375 same schema. 

1376 

1377 Example: c7cfa2a8 

1378 

1379 This corresponds to the ``revision_id`` field 

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

1381 should not be set. 

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

1383 should be retried. 

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

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

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

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

1388 be of type `bytes`. 

1389 

1390 Returns: 

1391 google.pubsub_v1.types.Schema: 

1392 A schema resource. 

1393 """ 

1394 # Create or coerce a protobuf request object. 

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

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

1397 flattened_params = [name, revision_id] 

1398 has_flattened_params = ( 

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

1400 ) 

1401 if request is not None and has_flattened_params: 

1402 raise ValueError( 

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

1404 "the individual field arguments should be set." 

1405 ) 

1406 

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

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

1409 if not isinstance(request, schema.RollbackSchemaRequest): 

1410 request = schema.RollbackSchemaRequest(request) 

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

1412 # request, apply these. 

1413 if name is not None: 

1414 request.name = name 

1415 if revision_id is not None: 

1416 request.revision_id = revision_id 

1417 

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

1419 # and friendly error handling. 

1420 rpc = self._transport._wrapped_methods[self._transport.rollback_schema] 

1421 

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

1423 # add these here. 

1424 metadata = tuple(metadata) + ( 

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

1426 ) 

1427 

1428 # Validate the universe domain. 

1429 self._validate_universe_domain() 

1430 

1431 # Send the request. 

1432 response = rpc( 

1433 request, 

1434 retry=retry, 

1435 timeout=timeout, 

1436 metadata=metadata, 

1437 ) 

1438 

1439 # Done; return the response. 

1440 return response 

1441 

1442 def delete_schema_revision( 

1443 self, 

1444 request: Optional[Union[schema.DeleteSchemaRevisionRequest, dict]] = None, 

1445 *, 

1446 name: Optional[str] = None, 

1447 revision_id: Optional[str] = None, 

1448 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1451 ) -> schema.Schema: 

1452 r"""Deletes a specific schema revision. 

1453 

1454 .. code-block:: python 

1455 

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

1457 # code template only. 

1458 # It will require modifications to work: 

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

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

1461 # client as shown in: 

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

1463 from google import pubsub_v1 

1464 

1465 def sample_delete_schema_revision(): 

1466 # Create a client 

1467 client = pubsub_v1.SchemaServiceClient() 

1468 

1469 # Initialize request argument(s) 

1470 request = pubsub_v1.DeleteSchemaRevisionRequest( 

1471 name="name_value", 

1472 ) 

1473 

1474 # Make the request 

1475 response = client.delete_schema_revision(request=request) 

1476 

1477 # Handle the response 

1478 print(response) 

1479 

1480 Args: 

1481 request (Union[google.pubsub_v1.types.DeleteSchemaRevisionRequest, dict]): 

1482 The request object. Request for the ``DeleteSchemaRevision`` method. 

1483 name (str): 

1484 Required. The name of the schema revision to be deleted, 

1485 with a revision ID explicitly included. 

1486 

1487 Example: ``projects/123/schemas/my-schema@c7cfa2a8`` 

1488 

1489 This corresponds to the ``name`` field 

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

1491 should not be set. 

1492 revision_id (str): 

1493 Optional. This field is deprecated and should not be 

1494 used for specifying the revision ID. The revision ID 

1495 should be specified via the ``name`` parameter. 

1496 

1497 This corresponds to the ``revision_id`` field 

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

1499 should not be set. 

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

1501 should be retried. 

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

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

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

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

1506 be of type `bytes`. 

1507 

1508 Returns: 

1509 google.pubsub_v1.types.Schema: 

1510 A schema resource. 

1511 """ 

1512 # Create or coerce a protobuf request object. 

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

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

1515 flattened_params = [name, revision_id] 

1516 has_flattened_params = ( 

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

1518 ) 

1519 if request is not None and has_flattened_params: 

1520 raise ValueError( 

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

1522 "the individual field arguments should be set." 

1523 ) 

1524 

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

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

1527 if not isinstance(request, schema.DeleteSchemaRevisionRequest): 

1528 request = schema.DeleteSchemaRevisionRequest(request) 

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

1530 # request, apply these. 

1531 if name is not None: 

1532 request.name = name 

1533 if revision_id is not None: 

1534 request.revision_id = revision_id 

1535 

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

1537 # and friendly error handling. 

1538 rpc = self._transport._wrapped_methods[self._transport.delete_schema_revision] 

1539 

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

1541 # add these here. 

1542 metadata = tuple(metadata) + ( 

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

1544 ) 

1545 

1546 # Validate the universe domain. 

1547 self._validate_universe_domain() 

1548 

1549 # Send the request. 

1550 response = rpc( 

1551 request, 

1552 retry=retry, 

1553 timeout=timeout, 

1554 metadata=metadata, 

1555 ) 

1556 

1557 # Done; return the response. 

1558 return response 

1559 

1560 def delete_schema( 

1561 self, 

1562 request: Optional[Union[schema.DeleteSchemaRequest, dict]] = None, 

1563 *, 

1564 name: Optional[str] = None, 

1565 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1568 ) -> None: 

1569 r"""Deletes a schema. 

1570 

1571 .. code-block:: python 

1572 

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

1574 # code template only. 

1575 # It will require modifications to work: 

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

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

1578 # client as shown in: 

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

1580 from google import pubsub_v1 

1581 

1582 def sample_delete_schema(): 

1583 # Create a client 

1584 client = pubsub_v1.SchemaServiceClient() 

1585 

1586 # Initialize request argument(s) 

1587 request = pubsub_v1.DeleteSchemaRequest( 

1588 name="name_value", 

1589 ) 

1590 

1591 # Make the request 

1592 client.delete_schema(request=request) 

1593 

1594 Args: 

1595 request (Union[google.pubsub_v1.types.DeleteSchemaRequest, dict]): 

1596 The request object. Request for the ``DeleteSchema`` method. 

1597 name (str): 

1598 Required. Name of the schema to delete. Format is 

1599 ``projects/{project}/schemas/{schema}``. 

1600 

1601 This corresponds to the ``name`` field 

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

1603 should not be set. 

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

1605 should be retried. 

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

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

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

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

1610 be of type `bytes`. 

1611 """ 

1612 # Create or coerce a protobuf request object. 

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

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

1615 flattened_params = [name] 

1616 has_flattened_params = ( 

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

1618 ) 

1619 if request is not None and has_flattened_params: 

1620 raise ValueError( 

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

1622 "the individual field arguments should be set." 

1623 ) 

1624 

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

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

1627 if not isinstance(request, schema.DeleteSchemaRequest): 

1628 request = schema.DeleteSchemaRequest(request) 

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

1630 # request, apply these. 

1631 if name is not None: 

1632 request.name = name 

1633 

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

1635 # and friendly error handling. 

1636 rpc = self._transport._wrapped_methods[self._transport.delete_schema] 

1637 

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

1639 # add these here. 

1640 metadata = tuple(metadata) + ( 

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

1642 ) 

1643 

1644 # Validate the universe domain. 

1645 self._validate_universe_domain() 

1646 

1647 # Send the request. 

1648 rpc( 

1649 request, 

1650 retry=retry, 

1651 timeout=timeout, 

1652 metadata=metadata, 

1653 ) 

1654 

1655 def validate_schema( 

1656 self, 

1657 request: Optional[Union[gp_schema.ValidateSchemaRequest, dict]] = None, 

1658 *, 

1659 parent: Optional[str] = None, 

1660 schema: Optional[gp_schema.Schema] = None, 

1661 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1664 ) -> gp_schema.ValidateSchemaResponse: 

1665 r"""Validates a schema. 

1666 

1667 .. code-block:: python 

1668 

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

1670 # code template only. 

1671 # It will require modifications to work: 

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

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

1674 # client as shown in: 

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

1676 from google import pubsub_v1 

1677 

1678 def sample_validate_schema(): 

1679 # Create a client 

1680 client = pubsub_v1.SchemaServiceClient() 

1681 

1682 # Initialize request argument(s) 

1683 schema = pubsub_v1.Schema() 

1684 schema.name = "name_value" 

1685 

1686 request = pubsub_v1.ValidateSchemaRequest( 

1687 parent="parent_value", 

1688 schema=schema, 

1689 ) 

1690 

1691 # Make the request 

1692 response = client.validate_schema(request=request) 

1693 

1694 # Handle the response 

1695 print(response) 

1696 

1697 Args: 

1698 request (Union[google.pubsub_v1.types.ValidateSchemaRequest, dict]): 

1699 The request object. Request for the ``ValidateSchema`` method. 

1700 parent (str): 

1701 Required. The name of the project in which to validate 

1702 schemas. Format is ``projects/{project-id}``. 

1703 

1704 This corresponds to the ``parent`` field 

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

1706 should not be set. 

1707 schema (google.pubsub_v1.types.Schema): 

1708 Required. The schema object to 

1709 validate. 

1710 

1711 This corresponds to the ``schema`` field 

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

1713 should not be set. 

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

1715 should be retried. 

1716 timeout (float): 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 Returns: 

1723 google.pubsub_v1.types.ValidateSchemaResponse: 

1724 Response for the ValidateSchema method. 

1725 Empty for now. 

1726 

1727 """ 

1728 # Create or coerce a protobuf request object. 

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

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

1731 flattened_params = [parent, schema] 

1732 has_flattened_params = ( 

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

1734 ) 

1735 if request is not None and has_flattened_params: 

1736 raise ValueError( 

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

1738 "the individual field arguments should be set." 

1739 ) 

1740 

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

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

1743 if not isinstance(request, gp_schema.ValidateSchemaRequest): 

1744 request = gp_schema.ValidateSchemaRequest(request) 

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

1746 # request, apply these. 

1747 if parent is not None: 

1748 request.parent = parent 

1749 if schema is not None: 

1750 request.schema = schema 

1751 

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

1753 # and friendly error handling. 

1754 rpc = self._transport._wrapped_methods[self._transport.validate_schema] 

1755 

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

1757 # add these here. 

1758 metadata = tuple(metadata) + ( 

1759 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), 

1760 ) 

1761 

1762 # Validate the universe domain. 

1763 self._validate_universe_domain() 

1764 

1765 # Send the request. 

1766 response = rpc( 

1767 request, 

1768 retry=retry, 

1769 timeout=timeout, 

1770 metadata=metadata, 

1771 ) 

1772 

1773 # Done; return the response. 

1774 return response 

1775 

1776 def validate_message( 

1777 self, 

1778 request: Optional[Union[schema.ValidateMessageRequest, dict]] = None, 

1779 *, 

1780 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1783 ) -> schema.ValidateMessageResponse: 

1784 r"""Validates a message against a schema. 

1785 

1786 .. code-block:: python 

1787 

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

1789 # code template only. 

1790 # It will require modifications to work: 

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

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

1793 # client as shown in: 

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

1795 from google import pubsub_v1 

1796 

1797 def sample_validate_message(): 

1798 # Create a client 

1799 client = pubsub_v1.SchemaServiceClient() 

1800 

1801 # Initialize request argument(s) 

1802 request = pubsub_v1.ValidateMessageRequest( 

1803 name="name_value", 

1804 parent="parent_value", 

1805 ) 

1806 

1807 # Make the request 

1808 response = client.validate_message(request=request) 

1809 

1810 # Handle the response 

1811 print(response) 

1812 

1813 Args: 

1814 request (Union[google.pubsub_v1.types.ValidateMessageRequest, dict]): 

1815 The request object. Request for the ``ValidateMessage`` method. 

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

1817 should be retried. 

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

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

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

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

1822 be of type `bytes`. 

1823 

1824 Returns: 

1825 google.pubsub_v1.types.ValidateMessageResponse: 

1826 Response for the ValidateMessage method. 

1827 Empty for now. 

1828 

1829 """ 

1830 # Create or coerce a protobuf request object. 

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

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

1833 if not isinstance(request, schema.ValidateMessageRequest): 

1834 request = schema.ValidateMessageRequest(request) 

1835 

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

1837 # and friendly error handling. 

1838 rpc = self._transport._wrapped_methods[self._transport.validate_message] 

1839 

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

1841 # add these here. 

1842 metadata = tuple(metadata) + ( 

1843 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)), 

1844 ) 

1845 

1846 # Validate the universe domain. 

1847 self._validate_universe_domain() 

1848 

1849 # Send the request. 

1850 response = rpc( 

1851 request, 

1852 retry=retry, 

1853 timeout=timeout, 

1854 metadata=metadata, 

1855 ) 

1856 

1857 # Done; return the response. 

1858 return response 

1859 

1860 def __enter__(self) -> "SchemaServiceClient": 

1861 return self 

1862 

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

1864 """Releases underlying transport's resources. 

1865 

1866 .. warning:: 

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

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

1869 and may cause errors in other clients! 

1870 """ 

1871 self.transport.close() 

1872 

1873 def set_iam_policy( 

1874 self, 

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

1876 *, 

1877 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

1880 ) -> policy_pb2.Policy: 

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

1882 

1883 Replaces any existing policy. 

1884 

1885 Args: 

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

1887 The request object. Request message for `SetIamPolicy` 

1888 method. 

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

1890 should be retried. 

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

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

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

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

1895 be of type `bytes`. 

1896 Returns: 

1897 ~.policy_pb2.Policy: 

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

1899 It is used to specify access control policies for Cloud 

1900 Platform resources. 

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

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

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

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

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

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

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

1908 expression that further constrains the role binding 

1909 based on attributes about the request and/or target 

1910 resource. 

1911 

1912 **JSON Example** 

1913 

1914 :: 

1915 

1916 { 

1917 "bindings": [ 

1918 { 

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

1920 "members": [ 

1921 "user:mike@example.com", 

1922 "group:admins@example.com", 

1923 "domain:google.com", 

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

1925 ] 

1926 }, 

1927 { 

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

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

1930 "condition": { 

1931 "title": "expirable access", 

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

1933 "expression": "request.time < 

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

1935 } 

1936 } 

1937 ] 

1938 } 

1939 

1940 **YAML Example** 

1941 

1942 :: 

1943 

1944 bindings: 

1945 - members: 

1946 - user:mike@example.com 

1947 - group:admins@example.com 

1948 - domain:google.com 

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

1950 role: roles/resourcemanager.organizationAdmin 

1951 - members: 

1952 - user:eve@example.com 

1953 role: roles/resourcemanager.organizationViewer 

1954 condition: 

1955 title: expirable access 

1956 description: Does not grant access after Sep 2020 

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

1958 

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

1960 developer's 

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

1962 """ 

1963 # Create or coerce a protobuf request object. 

1964 

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

1966 # so it must be constructed via keyword expansion. 

1967 if isinstance(request, dict): 

1968 request = iam_policy_pb2.SetIamPolicyRequest(**request) 

1969 

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

1971 # and friendly error handling. 

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

1973 

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

1975 # add these here. 

1976 metadata = tuple(metadata) + ( 

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

1978 ) 

1979 

1980 # Validate the universe domain. 

1981 self._validate_universe_domain() 

1982 

1983 try: 

1984 # Send the request. 

1985 response = rpc( 

1986 request, 

1987 retry=retry, 

1988 timeout=timeout, 

1989 metadata=metadata, 

1990 ) 

1991 

1992 # Done; return the response. 

1993 return response 

1994 except core_exceptions.GoogleAPICallError as e: 

1995 self._add_cred_info_for_auth_errors(e) 

1996 raise e 

1997 

1998 def get_iam_policy( 

1999 self, 

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

2001 *, 

2002 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

2005 ) -> policy_pb2.Policy: 

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

2007 

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

2009 policy set. 

2010 

2011 Args: 

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

2013 The request object. Request message for `GetIamPolicy` 

2014 method. 

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

2016 any, should be retried. 

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

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

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

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

2021 be of type `bytes`. 

2022 Returns: 

2023 ~.policy_pb2.Policy: 

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

2025 It is used to specify access control policies for Cloud 

2026 Platform resources. 

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

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

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

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

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

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

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

2034 expression that further constrains the role binding 

2035 based on attributes about the request and/or target 

2036 resource. 

2037 

2038 **JSON Example** 

2039 

2040 :: 

2041 

2042 { 

2043 "bindings": [ 

2044 { 

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

2046 "members": [ 

2047 "user:mike@example.com", 

2048 "group:admins@example.com", 

2049 "domain:google.com", 

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

2051 ] 

2052 }, 

2053 { 

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

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

2056 "condition": { 

2057 "title": "expirable access", 

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

2059 "expression": "request.time < 

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

2061 } 

2062 } 

2063 ] 

2064 } 

2065 

2066 **YAML Example** 

2067 

2068 :: 

2069 

2070 bindings: 

2071 - members: 

2072 - user:mike@example.com 

2073 - group:admins@example.com 

2074 - domain:google.com 

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

2076 role: roles/resourcemanager.organizationAdmin 

2077 - members: 

2078 - user:eve@example.com 

2079 role: roles/resourcemanager.organizationViewer 

2080 condition: 

2081 title: expirable access 

2082 description: Does not grant access after Sep 2020 

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

2084 

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

2086 developer's 

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

2088 """ 

2089 # Create or coerce a protobuf request object. 

2090 

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

2092 # so it must be constructed via keyword expansion. 

2093 if isinstance(request, dict): 

2094 request = iam_policy_pb2.GetIamPolicyRequest(**request) 

2095 

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

2097 # and friendly error handling. 

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

2099 

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

2101 # add these here. 

2102 metadata = tuple(metadata) + ( 

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

2104 ) 

2105 

2106 # Validate the universe domain. 

2107 self._validate_universe_domain() 

2108 

2109 try: 

2110 # Send the request. 

2111 response = rpc( 

2112 request, 

2113 retry=retry, 

2114 timeout=timeout, 

2115 metadata=metadata, 

2116 ) 

2117 

2118 # Done; return the response. 

2119 return response 

2120 except core_exceptions.GoogleAPICallError as e: 

2121 self._add_cred_info_for_auth_errors(e) 

2122 raise e 

2123 

2124 def test_iam_permissions( 

2125 self, 

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

2127 *, 

2128 retry: OptionalRetry = gapic_v1.method.DEFAULT, 

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

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

2131 ) -> iam_policy_pb2.TestIamPermissionsResponse: 

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

2133 policy for a function. 

2134 

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

2136 of permissions, not a NOT_FOUND error. 

2137 

2138 Args: 

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

2140 The request object. Request message for 

2141 `TestIamPermissions` method. 

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

2143 if any, should be retried. 

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

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

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

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

2148 be of type `bytes`. 

2149 Returns: 

2150 ~.iam_policy_pb2.TestIamPermissionsResponse: 

2151 Response message for ``TestIamPermissions`` method. 

2152 """ 

2153 # Create or coerce a protobuf request object. 

2154 

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

2156 # so it must be constructed via keyword expansion. 

2157 if isinstance(request, dict): 

2158 request = iam_policy_pb2.TestIamPermissionsRequest(**request) 

2159 

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

2161 # and friendly error handling. 

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

2163 

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

2165 # add these here. 

2166 metadata = tuple(metadata) + ( 

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

2168 ) 

2169 

2170 # Validate the universe domain. 

2171 self._validate_universe_domain() 

2172 

2173 try: 

2174 # Send the request. 

2175 response = rpc( 

2176 request, 

2177 retry=retry, 

2178 timeout=timeout, 

2179 metadata=metadata, 

2180 ) 

2181 

2182 # Done; return the response. 

2183 return response 

2184 except core_exceptions.GoogleAPICallError as e: 

2185 self._add_cred_info_for_auth_errors(e) 

2186 raise e 

2187 

2188 

2189DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo( 

2190 client_library_version=package_version.__version__ 

2191) 

2192 

2193 

2194__all__ = ("SchemaServiceClient",)