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.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
49import google.protobuf
50
51try:
52 OptionalRetry = Union[retries.Retry, gapic_v1.method._MethodDefault, None]
53except AttributeError: # pragma: NO COVER
54 OptionalRetry = Union[retries.Retry, object, None] # type: ignore
55
56try:
57 from google.api_core import client_logging # type: ignore
58
59 CLIENT_LOGGING_SUPPORTED = True # pragma: NO COVER
60except ImportError: # pragma: NO COVER
61 CLIENT_LOGGING_SUPPORTED = False
62
63_LOGGER = std_logging.getLogger(__name__)
64
65from google.iam.v1 import iam_policy_pb2 # type: ignore
66from google.iam.v1 import policy_pb2 # type: ignore
67from google.protobuf import timestamp_pb2 # type: ignore
68from google.pubsub_v1.services.schema_service import pagers
69from google.pubsub_v1.types import schema
70from google.pubsub_v1.types import schema as gp_schema
71
72import grpc
73from .transports.base import SchemaServiceTransport, DEFAULT_CLIENT_INFO
74from .transports.grpc import SchemaServiceGrpcTransport
75from .transports.grpc_asyncio import SchemaServiceGrpcAsyncIOTransport
76from .transports.rest import SchemaServiceRestTransport
77
78
79class SchemaServiceClientMeta(type):
80 """Metaclass for the SchemaService client.
81
82 This provides class-level methods for building and retrieving
83 support objects (e.g. transport) without polluting the client instance
84 objects.
85 """
86
87 _transport_registry = OrderedDict() # type: Dict[str, Type[SchemaServiceTransport]]
88 _transport_registry["grpc"] = SchemaServiceGrpcTransport
89 _transport_registry["grpc_asyncio"] = SchemaServiceGrpcAsyncIOTransport
90 _transport_registry["rest"] = SchemaServiceRestTransport
91
92 def get_transport_class(
93 cls,
94 label: Optional[str] = None,
95 ) -> Type[SchemaServiceTransport]:
96 """Returns an appropriate transport class.
97
98 Args:
99 label: The name of the desired transport. If none is
100 provided, then the first transport in the registry is used.
101
102 Returns:
103 The transport class to use.
104 """
105 # If a specific transport is requested, return that one.
106 if label:
107 return cls._transport_registry[label]
108
109 # No transport is requested; return the default (that is, the first one
110 # in the dictionary).
111 return next(iter(cls._transport_registry.values()))
112
113
114class SchemaServiceClient(metaclass=SchemaServiceClientMeta):
115 """Service for doing schema-related operations."""
116
117 @staticmethod
118 def _get_default_mtls_endpoint(api_endpoint):
119 """Converts api endpoint to mTLS endpoint.
120
121 Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
122 "*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
123 Args:
124 api_endpoint (Optional[str]): the api endpoint to convert.
125 Returns:
126 str: converted mTLS api endpoint.
127 """
128 if not api_endpoint:
129 return api_endpoint
130
131 mtls_endpoint_re = re.compile(
132 r"(?P<name>[^.]+)(?P<mtls>\.mtls)?(?P<sandbox>\.sandbox)?(?P<googledomain>\.googleapis\.com)?"
133 )
134
135 m = mtls_endpoint_re.match(api_endpoint)
136 name, mtls, sandbox, googledomain = m.groups()
137 if mtls or not googledomain:
138 return api_endpoint
139
140 if sandbox:
141 return api_endpoint.replace(
142 "sandbox.googleapis.com", "mtls.sandbox.googleapis.com"
143 )
144
145 return api_endpoint.replace(".googleapis.com", ".mtls.googleapis.com")
146
147 # Note: DEFAULT_ENDPOINT is deprecated. Use _DEFAULT_ENDPOINT_TEMPLATE instead.
148 DEFAULT_ENDPOINT = "pubsub.googleapis.com"
149 DEFAULT_MTLS_ENDPOINT = _get_default_mtls_endpoint.__func__( # type: ignore
150 DEFAULT_ENDPOINT
151 )
152
153 _DEFAULT_ENDPOINT_TEMPLATE = "pubsub.{UNIVERSE_DOMAIN}"
154 _DEFAULT_UNIVERSE = "googleapis.com"
155
156 @classmethod
157 def from_service_account_info(cls, info: dict, *args, **kwargs):
158 """Creates an instance of this client using the provided credentials
159 info.
160
161 Args:
162 info (dict): The service account private key info.
163 args: Additional arguments to pass to the constructor.
164 kwargs: Additional arguments to pass to the constructor.
165
166 Returns:
167 SchemaServiceClient: The constructed client.
168 """
169 credentials = service_account.Credentials.from_service_account_info(info)
170 kwargs["credentials"] = credentials
171 return cls(*args, **kwargs)
172
173 @classmethod
174 def from_service_account_file(cls, filename: str, *args, **kwargs):
175 """Creates an instance of this client using the provided credentials
176 file.
177
178 Args:
179 filename (str): The path to the service account private key json
180 file.
181 args: Additional arguments to pass to the constructor.
182 kwargs: Additional arguments to pass to the constructor.
183
184 Returns:
185 SchemaServiceClient: The constructed client.
186 """
187 credentials = service_account.Credentials.from_service_account_file(filename)
188 kwargs["credentials"] = credentials
189 return cls(*args, **kwargs)
190
191 from_service_account_json = from_service_account_file
192
193 @property
194 def transport(self) -> SchemaServiceTransport:
195 """Returns the transport used by the client instance.
196
197 Returns:
198 SchemaServiceTransport: The transport used by the client
199 instance.
200 """
201 return self._transport
202
203 @staticmethod
204 def schema_path(
205 project: str,
206 schema: str,
207 ) -> str:
208 """Returns a fully-qualified schema string."""
209 return "projects/{project}/schemas/{schema}".format(
210 project=project,
211 schema=schema,
212 )
213
214 @staticmethod
215 def parse_schema_path(path: str) -> Dict[str, str]:
216 """Parses a schema path into its component segments."""
217 m = re.match(r"^projects/(?P<project>.+?)/schemas/(?P<schema>.+?)$", path)
218 return m.groupdict() if m else {}
219
220 @staticmethod
221 def common_billing_account_path(
222 billing_account: str,
223 ) -> str:
224 """Returns a fully-qualified billing_account string."""
225 return "billingAccounts/{billing_account}".format(
226 billing_account=billing_account,
227 )
228
229 @staticmethod
230 def parse_common_billing_account_path(path: str) -> Dict[str, str]:
231 """Parse a billing_account path into its component segments."""
232 m = re.match(r"^billingAccounts/(?P<billing_account>.+?)$", path)
233 return m.groupdict() if m else {}
234
235 @staticmethod
236 def common_folder_path(
237 folder: str,
238 ) -> str:
239 """Returns a fully-qualified folder string."""
240 return "folders/{folder}".format(
241 folder=folder,
242 )
243
244 @staticmethod
245 def parse_common_folder_path(path: str) -> Dict[str, str]:
246 """Parse a folder path into its component segments."""
247 m = re.match(r"^folders/(?P<folder>.+?)$", path)
248 return m.groupdict() if m else {}
249
250 @staticmethod
251 def common_organization_path(
252 organization: str,
253 ) -> str:
254 """Returns a fully-qualified organization string."""
255 return "organizations/{organization}".format(
256 organization=organization,
257 )
258
259 @staticmethod
260 def parse_common_organization_path(path: str) -> Dict[str, str]:
261 """Parse a organization path into its component segments."""
262 m = re.match(r"^organizations/(?P<organization>.+?)$", path)
263 return m.groupdict() if m else {}
264
265 @staticmethod
266 def common_project_path(
267 project: str,
268 ) -> str:
269 """Returns a fully-qualified project string."""
270 return "projects/{project}".format(
271 project=project,
272 )
273
274 @staticmethod
275 def parse_common_project_path(path: str) -> Dict[str, str]:
276 """Parse a project path into its component segments."""
277 m = re.match(r"^projects/(?P<project>.+?)$", path)
278 return m.groupdict() if m else {}
279
280 @staticmethod
281 def common_location_path(
282 project: str,
283 location: str,
284 ) -> str:
285 """Returns a fully-qualified location string."""
286 return "projects/{project}/locations/{location}".format(
287 project=project,
288 location=location,
289 )
290
291 @staticmethod
292 def parse_common_location_path(path: str) -> Dict[str, str]:
293 """Parse a location path into its component segments."""
294 m = re.match(r"^projects/(?P<project>.+?)/locations/(?P<location>.+?)$", path)
295 return m.groupdict() if m else {}
296
297 @classmethod
298 def get_mtls_endpoint_and_cert_source(
299 cls, client_options: Optional[client_options_lib.ClientOptions] = None
300 ):
301 """Deprecated. Return the API endpoint and client cert source for mutual TLS.
302
303 The client cert source is determined in the following order:
304 (1) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is not "true", the
305 client cert source is None.
306 (2) if `client_options.client_cert_source` is provided, use the provided one; if the
307 default client cert source exists, use the default one; otherwise the client cert
308 source is None.
309
310 The API endpoint is determined in the following order:
311 (1) if `client_options.api_endpoint` if provided, use the provided one.
312 (2) if `GOOGLE_API_USE_CLIENT_CERTIFICATE` environment variable is "always", use the
313 default mTLS endpoint; if the environment variable is "never", use the default API
314 endpoint; otherwise if client cert source exists, use the default mTLS endpoint, otherwise
315 use the default API endpoint.
316
317 More details can be found at https://google.aip.dev/auth/4114.
318
319 Args:
320 client_options (google.api_core.client_options.ClientOptions): Custom options for the
321 client. Only the `api_endpoint` and `client_cert_source` properties may be used
322 in this method.
323
324 Returns:
325 Tuple[str, Callable[[], Tuple[bytes, bytes]]]: returns the API endpoint and the
326 client cert source to use.
327
328 Raises:
329 google.auth.exceptions.MutualTLSChannelError: If any errors happen.
330 """
331
332 warnings.warn(
333 "get_mtls_endpoint_and_cert_source is deprecated. Use the api_endpoint property instead.",
334 DeprecationWarning,
335 )
336 if client_options is None:
337 client_options = client_options_lib.ClientOptions()
338 use_client_cert = os.getenv("GOOGLE_API_USE_CLIENT_CERTIFICATE", "false")
339 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto")
340 if use_client_cert not in ("true", "false"):
341 raise ValueError(
342 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
343 )
344 if use_mtls_endpoint not in ("auto", "never", "always"):
345 raise MutualTLSChannelError(
346 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
347 )
348
349 # Figure out the client cert source to use.
350 client_cert_source = None
351 if use_client_cert == "true":
352 if client_options.client_cert_source:
353 client_cert_source = client_options.client_cert_source
354 elif mtls.has_default_client_cert_source():
355 client_cert_source = mtls.default_client_cert_source()
356
357 # Figure out which api endpoint to use.
358 if client_options.api_endpoint is not None:
359 api_endpoint = client_options.api_endpoint
360 elif use_mtls_endpoint == "always" or (
361 use_mtls_endpoint == "auto" and client_cert_source
362 ):
363 api_endpoint = cls.DEFAULT_MTLS_ENDPOINT
364 else:
365 api_endpoint = cls.DEFAULT_ENDPOINT
366
367 return api_endpoint, client_cert_source
368
369 @staticmethod
370 def _read_environment_variables():
371 """Returns the environment variables used by the client.
372
373 Returns:
374 Tuple[bool, str, str]: returns the GOOGLE_API_USE_CLIENT_CERTIFICATE,
375 GOOGLE_API_USE_MTLS_ENDPOINT, and GOOGLE_CLOUD_UNIVERSE_DOMAIN environment variables.
376
377 Raises:
378 ValueError: If GOOGLE_API_USE_CLIENT_CERTIFICATE is not
379 any of ["true", "false"].
380 google.auth.exceptions.MutualTLSChannelError: If GOOGLE_API_USE_MTLS_ENDPOINT
381 is not any of ["auto", "never", "always"].
382 """
383 use_client_cert = os.getenv(
384 "GOOGLE_API_USE_CLIENT_CERTIFICATE", "false"
385 ).lower()
386 use_mtls_endpoint = os.getenv("GOOGLE_API_USE_MTLS_ENDPOINT", "auto").lower()
387 universe_domain_env = os.getenv("GOOGLE_CLOUD_UNIVERSE_DOMAIN")
388 if use_client_cert not in ("true", "false"):
389 raise ValueError(
390 "Environment variable `GOOGLE_API_USE_CLIENT_CERTIFICATE` must be either `true` or `false`"
391 )
392 if use_mtls_endpoint not in ("auto", "never", "always"):
393 raise MutualTLSChannelError(
394 "Environment variable `GOOGLE_API_USE_MTLS_ENDPOINT` must be `never`, `auto` or `always`"
395 )
396 return use_client_cert == "true", use_mtls_endpoint, universe_domain_env
397
398 @staticmethod
399 def _get_client_cert_source(provided_cert_source, use_cert_flag):
400 """Return the client cert source to be used by the client.
401
402 Args:
403 provided_cert_source (bytes): The client certificate source provided.
404 use_cert_flag (bool): A flag indicating whether to use the client certificate.
405
406 Returns:
407 bytes or None: The client cert source to be used by the client.
408 """
409 client_cert_source = None
410 if use_cert_flag:
411 if provided_cert_source:
412 client_cert_source = provided_cert_source
413 elif mtls.has_default_client_cert_source():
414 client_cert_source = mtls.default_client_cert_source()
415 return client_cert_source
416
417 @staticmethod
418 def _get_api_endpoint(
419 api_override, client_cert_source, universe_domain, use_mtls_endpoint
420 ):
421 """Return the API endpoint used by the client.
422
423 Args:
424 api_override (str): The API endpoint override. If specified, this is always
425 the return value of this function and the other arguments are not used.
426 client_cert_source (bytes): The client certificate source used by the client.
427 universe_domain (str): The universe domain used by the client.
428 use_mtls_endpoint (str): How to use the mTLS endpoint, which depends also on the other parameters.
429 Possible values are "always", "auto", or "never".
430
431 Returns:
432 str: The API endpoint to be used by the client.
433 """
434 if api_override is not None:
435 api_endpoint = api_override
436 elif use_mtls_endpoint == "always" or (
437 use_mtls_endpoint == "auto" and client_cert_source
438 ):
439 _default_universe = SchemaServiceClient._DEFAULT_UNIVERSE
440 if universe_domain != _default_universe:
441 raise MutualTLSChannelError(
442 f"mTLS is not supported in any universe other than {_default_universe}."
443 )
444 api_endpoint = SchemaServiceClient.DEFAULT_MTLS_ENDPOINT
445 else:
446 api_endpoint = SchemaServiceClient._DEFAULT_ENDPOINT_TEMPLATE.format(
447 UNIVERSE_DOMAIN=universe_domain
448 )
449 return api_endpoint
450
451 @staticmethod
452 def _get_universe_domain(
453 client_universe_domain: Optional[str], universe_domain_env: Optional[str]
454 ) -> str:
455 """Return the universe domain used by the client.
456
457 Args:
458 client_universe_domain (Optional[str]): The universe domain configured via the client options.
459 universe_domain_env (Optional[str]): The universe domain configured via the "GOOGLE_CLOUD_UNIVERSE_DOMAIN" environment variable.
460
461 Returns:
462 str: The universe domain to be used by the client.
463
464 Raises:
465 ValueError: If the universe domain is an empty string.
466 """
467 universe_domain = SchemaServiceClient._DEFAULT_UNIVERSE
468 if client_universe_domain is not None:
469 universe_domain = client_universe_domain
470 elif universe_domain_env is not None:
471 universe_domain = universe_domain_env
472 if len(universe_domain.strip()) == 0:
473 raise ValueError("Universe Domain cannot be an empty string.")
474 return universe_domain
475
476 def _validate_universe_domain(self):
477 """Validates client's and credentials' universe domains are consistent.
478
479 Returns:
480 bool: True iff the configured universe domain is valid.
481
482 Raises:
483 ValueError: If the configured universe domain is not valid.
484 """
485
486 # NOTE (b/349488459): universe validation is disabled until further notice.
487 return True
488
489 def _add_cred_info_for_auth_errors(
490 self, error: core_exceptions.GoogleAPICallError
491 ) -> None:
492 """Adds credential info string to error details for 401/403/404 errors.
493
494 Args:
495 error (google.api_core.exceptions.GoogleAPICallError): The error to add the cred info.
496 """
497 if error.code not in [
498 HTTPStatus.UNAUTHORIZED,
499 HTTPStatus.FORBIDDEN,
500 HTTPStatus.NOT_FOUND,
501 ]:
502 return
503
504 cred = self._transport._credentials
505
506 # get_cred_info is only available in google-auth>=2.35.0
507 if not hasattr(cred, "get_cred_info"):
508 return
509
510 # ignore the type check since pypy test fails when get_cred_info
511 # is not available
512 cred_info = cred.get_cred_info() # type: ignore
513 if cred_info and hasattr(error._details, "append"):
514 error._details.append(json.dumps(cred_info))
515
516 @property
517 def api_endpoint(self):
518 """Return the API endpoint used by the client instance.
519
520 Returns:
521 str: The API endpoint used by the client instance.
522 """
523 return self._api_endpoint
524
525 @property
526 def universe_domain(self) -> str:
527 """Return the universe domain used by the client instance.
528
529 Returns:
530 str: The universe domain used by the client instance.
531 """
532 return self._universe_domain
533
534 def __init__(
535 self,
536 *,
537 credentials: Optional[ga_credentials.Credentials] = None,
538 transport: Optional[
539 Union[str, SchemaServiceTransport, Callable[..., SchemaServiceTransport]]
540 ] = None,
541 client_options: Optional[Union[client_options_lib.ClientOptions, dict]] = None,
542 client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
543 ) -> None:
544 """Instantiates the schema service client.
545
546 Args:
547 credentials (Optional[google.auth.credentials.Credentials]): The
548 authorization credentials to attach to requests. These
549 credentials identify the application to the service; if none
550 are specified, the client will attempt to ascertain the
551 credentials from the environment.
552 transport (Optional[Union[str,SchemaServiceTransport,Callable[..., SchemaServiceTransport]]]):
553 The transport to use, or a Callable that constructs and returns a new transport.
554 If a Callable is given, it will be called with the same set of initialization
555 arguments as used in the SchemaServiceTransport constructor.
556 If set to None, a transport is chosen automatically.
557 client_options (Optional[Union[google.api_core.client_options.ClientOptions, dict]]):
558 Custom options for the client.
559
560 1. The ``api_endpoint`` property can be used to override the
561 default endpoint provided by the client when ``transport`` is
562 not explicitly provided. Only if this property is not set and
563 ``transport`` was not explicitly provided, the endpoint is
564 determined by the GOOGLE_API_USE_MTLS_ENDPOINT environment
565 variable, which have one of the following values:
566 "always" (always use the default mTLS endpoint), "never" (always
567 use the default regular endpoint) and "auto" (auto-switch to the
568 default mTLS endpoint if client certificate is present; this is
569 the default value).
570
571 2. If the GOOGLE_API_USE_CLIENT_CERTIFICATE environment variable
572 is "true", then the ``client_cert_source`` property can be used
573 to provide a client certificate for mTLS transport. If
574 not provided, the default SSL client certificate will be used if
575 present. If GOOGLE_API_USE_CLIENT_CERTIFICATE is "false" or not
576 set, no client certificate will be used.
577
578 3. The ``universe_domain`` property can be used to override the
579 default "googleapis.com" universe. Note that the ``api_endpoint``
580 property still takes precedence; and ``universe_domain`` is
581 currently not supported for mTLS.
582
583 client_info (google.api_core.gapic_v1.client_info.ClientInfo):
584 The client info used to send a user-agent string along with
585 API requests. If ``None``, then default info will be used.
586 Generally, you only need to set this if you're developing
587 your own client library.
588
589 Raises:
590 google.auth.exceptions.MutualTLSChannelError: If mutual TLS transport
591 creation failed for any reason.
592 """
593 self._client_options = client_options
594 if isinstance(self._client_options, dict):
595 self._client_options = client_options_lib.from_dict(self._client_options)
596 if self._client_options is None:
597 self._client_options = client_options_lib.ClientOptions()
598 self._client_options = cast(
599 client_options_lib.ClientOptions, self._client_options
600 )
601
602 universe_domain_opt = getattr(self._client_options, "universe_domain", None)
603
604 (
605 self._use_client_cert,
606 self._use_mtls_endpoint,
607 self._universe_domain_env,
608 ) = SchemaServiceClient._read_environment_variables()
609 self._client_cert_source = SchemaServiceClient._get_client_cert_source(
610 self._client_options.client_cert_source, self._use_client_cert
611 )
612 self._universe_domain = SchemaServiceClient._get_universe_domain(
613 universe_domain_opt, self._universe_domain_env
614 )
615 self._api_endpoint = None # updated below, depending on `transport`
616
617 # Initialize the universe domain validation.
618 self._is_universe_domain_valid = False
619
620 if CLIENT_LOGGING_SUPPORTED: # pragma: NO COVER
621 # Setup logging.
622 client_logging.initialize_logging()
623
624 api_key_value = getattr(self._client_options, "api_key", None)
625 if api_key_value and credentials:
626 raise ValueError(
627 "client_options.api_key and credentials are mutually exclusive"
628 )
629
630 # Save or instantiate the transport.
631 # Ordinarily, we provide the transport, but allowing a custom transport
632 # instance provides an extensibility point for unusual situations.
633 transport_provided = isinstance(transport, SchemaServiceTransport)
634 if transport_provided:
635 # transport is a SchemaServiceTransport instance.
636 if credentials or self._client_options.credentials_file or api_key_value:
637 raise ValueError(
638 "When providing a transport instance, "
639 "provide its credentials directly."
640 )
641 if self._client_options.scopes:
642 raise ValueError(
643 "When providing a transport instance, provide its scopes "
644 "directly."
645 )
646 self._transport = cast(SchemaServiceTransport, transport)
647 self._api_endpoint = self._transport.host
648
649 self._api_endpoint = (
650 self._api_endpoint
651 or SchemaServiceClient._get_api_endpoint(
652 self._client_options.api_endpoint,
653 self._client_cert_source,
654 self._universe_domain,
655 self._use_mtls_endpoint,
656 )
657 )
658
659 if not transport_provided:
660 import google.auth._default # type: ignore
661
662 if api_key_value and hasattr(
663 google.auth._default, "get_api_key_credentials"
664 ):
665 credentials = google.auth._default.get_api_key_credentials(
666 api_key_value
667 )
668
669 transport_init: Union[
670 Type[SchemaServiceTransport], Callable[..., SchemaServiceTransport]
671 ] = (
672 SchemaServiceClient.get_transport_class(transport)
673 if isinstance(transport, str) or transport is None
674 else cast(Callable[..., SchemaServiceTransport], transport)
675 )
676 # initialize with the provided callable or the passed in class
677
678 emulator_host = os.environ.get("PUBSUB_EMULATOR_HOST")
679 if emulator_host:
680 if issubclass(transport_init, type(self)._transport_registry["grpc"]):
681 channel = grpc.insecure_channel(target=emulator_host)
682 else:
683 channel = grpc.aio.insecure_channel(target=emulator_host)
684 transport_init = functools.partial(transport_init, channel=channel)
685
686 self._transport = transport_init(
687 credentials=credentials,
688 credentials_file=self._client_options.credentials_file,
689 host=self._api_endpoint,
690 scopes=self._client_options.scopes,
691 client_cert_source_for_mtls=self._client_cert_source,
692 quota_project_id=self._client_options.quota_project_id,
693 client_info=client_info,
694 always_use_jwt_access=True,
695 api_audience=self._client_options.api_audience,
696 )
697
698 if "async" not in str(self._transport):
699 if CLIENT_LOGGING_SUPPORTED and _LOGGER.isEnabledFor(
700 std_logging.DEBUG
701 ): # pragma: NO COVER
702 _LOGGER.debug(
703 "Created client `google.pubsub_v1.SchemaServiceClient`.",
704 extra={
705 "serviceName": "google.pubsub.v1.SchemaService",
706 "universeDomain": getattr(
707 self._transport._credentials, "universe_domain", ""
708 ),
709 "credentialsType": f"{type(self._transport._credentials).__module__}.{type(self._transport._credentials).__qualname__}",
710 "credentialsInfo": getattr(
711 self.transport._credentials, "get_cred_info", lambda: None
712 )(),
713 }
714 if hasattr(self._transport, "_credentials")
715 else {
716 "serviceName": "google.pubsub.v1.SchemaService",
717 "credentialsType": None,
718 },
719 )
720
721 def create_schema(
722 self,
723 request: Optional[Union[gp_schema.CreateSchemaRequest, dict]] = None,
724 *,
725 parent: Optional[str] = None,
726 schema: Optional[gp_schema.Schema] = None,
727 schema_id: Optional[str] = None,
728 retry: OptionalRetry = gapic_v1.method.DEFAULT,
729 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
730 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
731 ) -> gp_schema.Schema:
732 r"""Creates a schema.
733
734 .. code-block:: python
735
736 # This snippet has been automatically generated and should be regarded as a
737 # code template only.
738 # It will require modifications to work:
739 # - It may require correct/in-range values for request initialization.
740 # - It may require specifying regional endpoints when creating the service
741 # client as shown in:
742 # https://googleapis.dev/python/google-api-core/latest/client_options.html
743 from google import pubsub_v1
744
745 def sample_create_schema():
746 # Create a client
747 client = pubsub_v1.SchemaServiceClient()
748
749 # Initialize request argument(s)
750 schema = pubsub_v1.Schema()
751 schema.name = "name_value"
752
753 request = pubsub_v1.CreateSchemaRequest(
754 parent="parent_value",
755 schema=schema,
756 )
757
758 # Make the request
759 response = client.create_schema(request=request)
760
761 # Handle the response
762 print(response)
763
764 Args:
765 request (Union[google.pubsub_v1.types.CreateSchemaRequest, dict]):
766 The request object. Request for the CreateSchema method.
767 parent (str):
768 Required. The name of the project in which to create the
769 schema. Format is ``projects/{project-id}``.
770
771 This corresponds to the ``parent`` field
772 on the ``request`` instance; if ``request`` is provided, this
773 should not be set.
774 schema (google.pubsub_v1.types.Schema):
775 Required. The schema object to create.
776
777 This schema's ``name`` parameter is ignored. The schema
778 object returned by CreateSchema will have a ``name``
779 made using the given ``parent`` and ``schema_id``.
780
781 This corresponds to the ``schema`` field
782 on the ``request`` instance; if ``request`` is provided, this
783 should not be set.
784 schema_id (str):
785 The ID to use for the schema, which will become the
786 final component of the schema's resource name.
787
788 See
789 https://cloud.google.com/pubsub/docs/pubsub-basics#resource_names
790 for resource name constraints.
791
792 This corresponds to the ``schema_id`` field
793 on the ``request`` instance; if ``request`` is provided, this
794 should not be set.
795 retry (google.api_core.retry.Retry): Designation of what errors, if any,
796 should be retried.
797 timeout (float): The timeout for this request.
798 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
799 sent along with the request as metadata. Normally, each value must be of type `str`,
800 but for metadata keys ending with the suffix `-bin`, the corresponding values must
801 be of type `bytes`.
802
803 Returns:
804 google.pubsub_v1.types.Schema:
805 A schema resource.
806 """
807 # Create or coerce a protobuf request object.
808 # - Quick check: If we got a request object, we should *not* have
809 # gotten any keyword arguments that map to the request.
810 flattened_params = [parent, schema, schema_id]
811 has_flattened_params = (
812 len([param for param in flattened_params if param is not None]) > 0
813 )
814 if request is not None and has_flattened_params:
815 raise ValueError(
816 "If the `request` argument is set, then none of "
817 "the individual field arguments should be set."
818 )
819
820 # - Use the request object if provided (there's no risk of modifying the input as
821 # there are no flattened fields), or create one.
822 if not isinstance(request, gp_schema.CreateSchemaRequest):
823 request = gp_schema.CreateSchemaRequest(request)
824 # If we have keyword arguments corresponding to fields on the
825 # request, apply these.
826 if parent is not None:
827 request.parent = parent
828 if schema is not None:
829 request.schema = schema
830 if schema_id is not None:
831 request.schema_id = schema_id
832
833 # Wrap the RPC method; this adds retry and timeout information,
834 # and friendly error handling.
835 rpc = self._transport._wrapped_methods[self._transport.create_schema]
836
837 # Certain fields should be provided within the metadata header;
838 # add these here.
839 metadata = tuple(metadata) + (
840 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
841 )
842
843 # Validate the universe domain.
844 self._validate_universe_domain()
845
846 # Send the request.
847 response = rpc(
848 request,
849 retry=retry,
850 timeout=timeout,
851 metadata=metadata,
852 )
853
854 # Done; return the response.
855 return response
856
857 def get_schema(
858 self,
859 request: Optional[Union[schema.GetSchemaRequest, dict]] = None,
860 *,
861 name: Optional[str] = None,
862 retry: OptionalRetry = gapic_v1.method.DEFAULT,
863 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
864 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
865 ) -> schema.Schema:
866 r"""Gets a schema.
867
868 .. code-block:: python
869
870 # This snippet has been automatically generated and should be regarded as a
871 # code template only.
872 # It will require modifications to work:
873 # - It may require correct/in-range values for request initialization.
874 # - It may require specifying regional endpoints when creating the service
875 # client as shown in:
876 # https://googleapis.dev/python/google-api-core/latest/client_options.html
877 from google import pubsub_v1
878
879 def sample_get_schema():
880 # Create a client
881 client = pubsub_v1.SchemaServiceClient()
882
883 # Initialize request argument(s)
884 request = pubsub_v1.GetSchemaRequest(
885 name="name_value",
886 )
887
888 # Make the request
889 response = client.get_schema(request=request)
890
891 # Handle the response
892 print(response)
893
894 Args:
895 request (Union[google.pubsub_v1.types.GetSchemaRequest, dict]):
896 The request object. Request for the GetSchema method.
897 name (str):
898 Required. The name of the schema to get. Format is
899 ``projects/{project}/schemas/{schema}``.
900
901 This corresponds to the ``name`` field
902 on the ``request`` instance; if ``request`` is provided, this
903 should not be set.
904 retry (google.api_core.retry.Retry): Designation of what errors, if any,
905 should be retried.
906 timeout (float): The timeout for this request.
907 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
908 sent along with the request as metadata. Normally, each value must be of type `str`,
909 but for metadata keys ending with the suffix `-bin`, the corresponding values must
910 be of type `bytes`.
911
912 Returns:
913 google.pubsub_v1.types.Schema:
914 A schema resource.
915 """
916 # Create or coerce a protobuf request object.
917 # - Quick check: If we got a request object, we should *not* have
918 # gotten any keyword arguments that map to the request.
919 flattened_params = [name]
920 has_flattened_params = (
921 len([param for param in flattened_params if param is not None]) > 0
922 )
923 if request is not None and has_flattened_params:
924 raise ValueError(
925 "If the `request` argument is set, then none of "
926 "the individual field arguments should be set."
927 )
928
929 # - Use the request object if provided (there's no risk of modifying the input as
930 # there are no flattened fields), or create one.
931 if not isinstance(request, schema.GetSchemaRequest):
932 request = schema.GetSchemaRequest(request)
933 # If we have keyword arguments corresponding to fields on the
934 # request, apply these.
935 if name is not None:
936 request.name = name
937
938 # Wrap the RPC method; this adds retry and timeout information,
939 # and friendly error handling.
940 rpc = self._transport._wrapped_methods[self._transport.get_schema]
941
942 # Certain fields should be provided within the metadata header;
943 # add these here.
944 metadata = tuple(metadata) + (
945 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
946 )
947
948 # Validate the universe domain.
949 self._validate_universe_domain()
950
951 # Send the request.
952 response = rpc(
953 request,
954 retry=retry,
955 timeout=timeout,
956 metadata=metadata,
957 )
958
959 # Done; return the response.
960 return response
961
962 def list_schemas(
963 self,
964 request: Optional[Union[schema.ListSchemasRequest, dict]] = None,
965 *,
966 parent: Optional[str] = None,
967 retry: OptionalRetry = gapic_v1.method.DEFAULT,
968 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
969 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
970 ) -> pagers.ListSchemasPager:
971 r"""Lists schemas in a project.
972
973 .. code-block:: python
974
975 # This snippet has been automatically generated and should be regarded as a
976 # code template only.
977 # It will require modifications to work:
978 # - It may require correct/in-range values for request initialization.
979 # - It may require specifying regional endpoints when creating the service
980 # client as shown in:
981 # https://googleapis.dev/python/google-api-core/latest/client_options.html
982 from google import pubsub_v1
983
984 def sample_list_schemas():
985 # Create a client
986 client = pubsub_v1.SchemaServiceClient()
987
988 # Initialize request argument(s)
989 request = pubsub_v1.ListSchemasRequest(
990 parent="parent_value",
991 )
992
993 # Make the request
994 page_result = client.list_schemas(request=request)
995
996 # Handle the response
997 for response in page_result:
998 print(response)
999
1000 Args:
1001 request (Union[google.pubsub_v1.types.ListSchemasRequest, dict]):
1002 The request object. Request for the ``ListSchemas`` method.
1003 parent (str):
1004 Required. The name of the project in which to list
1005 schemas. Format is ``projects/{project-id}``.
1006
1007 This corresponds to the ``parent`` field
1008 on the ``request`` instance; if ``request`` is provided, this
1009 should not be set.
1010 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1011 should be retried.
1012 timeout (float): The timeout for this request.
1013 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1014 sent along with the request as metadata. Normally, each value must be of type `str`,
1015 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1016 be of type `bytes`.
1017
1018 Returns:
1019 google.pubsub_v1.services.schema_service.pagers.ListSchemasPager:
1020 Response for the ListSchemas method.
1021
1022 Iterating over this object will yield results and
1023 resolve additional pages automatically.
1024
1025 """
1026 # Create or coerce a protobuf request object.
1027 # - Quick check: If we got a request object, we should *not* have
1028 # gotten any keyword arguments that map to the request.
1029 flattened_params = [parent]
1030 has_flattened_params = (
1031 len([param for param in flattened_params if param is not None]) > 0
1032 )
1033 if request is not None and has_flattened_params:
1034 raise ValueError(
1035 "If the `request` argument is set, then none of "
1036 "the individual field arguments should be set."
1037 )
1038
1039 # - Use the request object if provided (there's no risk of modifying the input as
1040 # there are no flattened fields), or create one.
1041 if not isinstance(request, schema.ListSchemasRequest):
1042 request = schema.ListSchemasRequest(request)
1043 # If we have keyword arguments corresponding to fields on the
1044 # request, apply these.
1045 if parent is not None:
1046 request.parent = parent
1047
1048 # Wrap the RPC method; this adds retry and timeout information,
1049 # and friendly error handling.
1050 rpc = self._transport._wrapped_methods[self._transport.list_schemas]
1051
1052 # Certain fields should be provided within the metadata header;
1053 # add these here.
1054 metadata = tuple(metadata) + (
1055 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
1056 )
1057
1058 # Validate the universe domain.
1059 self._validate_universe_domain()
1060
1061 # Send the request.
1062 response = rpc(
1063 request,
1064 retry=retry,
1065 timeout=timeout,
1066 metadata=metadata,
1067 )
1068
1069 # This method is paged; wrap the response in a pager, which provides
1070 # an `__iter__` convenience method.
1071 response = pagers.ListSchemasPager(
1072 method=rpc,
1073 request=request,
1074 response=response,
1075 retry=retry,
1076 timeout=timeout,
1077 metadata=metadata,
1078 )
1079
1080 # Done; return the response.
1081 return response
1082
1083 def list_schema_revisions(
1084 self,
1085 request: Optional[Union[schema.ListSchemaRevisionsRequest, dict]] = None,
1086 *,
1087 name: Optional[str] = None,
1088 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1089 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1090 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1091 ) -> pagers.ListSchemaRevisionsPager:
1092 r"""Lists all schema revisions for the named schema.
1093
1094 .. code-block:: python
1095
1096 # This snippet has been automatically generated and should be regarded as a
1097 # code template only.
1098 # It will require modifications to work:
1099 # - It may require correct/in-range values for request initialization.
1100 # - It may require specifying regional endpoints when creating the service
1101 # client as shown in:
1102 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1103 from google import pubsub_v1
1104
1105 def sample_list_schema_revisions():
1106 # Create a client
1107 client = pubsub_v1.SchemaServiceClient()
1108
1109 # Initialize request argument(s)
1110 request = pubsub_v1.ListSchemaRevisionsRequest(
1111 name="name_value",
1112 )
1113
1114 # Make the request
1115 page_result = client.list_schema_revisions(request=request)
1116
1117 # Handle the response
1118 for response in page_result:
1119 print(response)
1120
1121 Args:
1122 request (Union[google.pubsub_v1.types.ListSchemaRevisionsRequest, dict]):
1123 The request object. Request for the ``ListSchemaRevisions`` method.
1124 name (str):
1125 Required. The name of the schema to
1126 list revisions for.
1127
1128 This corresponds to the ``name`` field
1129 on the ``request`` instance; if ``request`` is provided, this
1130 should not be set.
1131 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1132 should be retried.
1133 timeout (float): The timeout for this request.
1134 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1135 sent along with the request as metadata. Normally, each value must be of type `str`,
1136 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1137 be of type `bytes`.
1138
1139 Returns:
1140 google.pubsub_v1.services.schema_service.pagers.ListSchemaRevisionsPager:
1141 Response for the ListSchemaRevisions method.
1142
1143 Iterating over this object will yield results and
1144 resolve additional pages automatically.
1145
1146 """
1147 # Create or coerce a protobuf request object.
1148 # - Quick check: If we got a request object, we should *not* have
1149 # gotten any keyword arguments that map to the request.
1150 flattened_params = [name]
1151 has_flattened_params = (
1152 len([param for param in flattened_params if param is not None]) > 0
1153 )
1154 if request is not None and has_flattened_params:
1155 raise ValueError(
1156 "If the `request` argument is set, then none of "
1157 "the individual field arguments should be set."
1158 )
1159
1160 # - Use the request object if provided (there's no risk of modifying the input as
1161 # there are no flattened fields), or create one.
1162 if not isinstance(request, schema.ListSchemaRevisionsRequest):
1163 request = schema.ListSchemaRevisionsRequest(request)
1164 # If we have keyword arguments corresponding to fields on the
1165 # request, apply these.
1166 if name is not None:
1167 request.name = name
1168
1169 # Wrap the RPC method; this adds retry and timeout information,
1170 # and friendly error handling.
1171 rpc = self._transport._wrapped_methods[self._transport.list_schema_revisions]
1172
1173 # Certain fields should be provided within the metadata header;
1174 # add these here.
1175 metadata = tuple(metadata) + (
1176 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1177 )
1178
1179 # Validate the universe domain.
1180 self._validate_universe_domain()
1181
1182 # Send the request.
1183 response = rpc(
1184 request,
1185 retry=retry,
1186 timeout=timeout,
1187 metadata=metadata,
1188 )
1189
1190 # This method is paged; wrap the response in a pager, which provides
1191 # an `__iter__` convenience method.
1192 response = pagers.ListSchemaRevisionsPager(
1193 method=rpc,
1194 request=request,
1195 response=response,
1196 retry=retry,
1197 timeout=timeout,
1198 metadata=metadata,
1199 )
1200
1201 # Done; return the response.
1202 return response
1203
1204 def commit_schema(
1205 self,
1206 request: Optional[Union[gp_schema.CommitSchemaRequest, dict]] = None,
1207 *,
1208 name: Optional[str] = None,
1209 schema: Optional[gp_schema.Schema] = None,
1210 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1211 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1212 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1213 ) -> gp_schema.Schema:
1214 r"""Commits a new schema revision to an existing schema.
1215
1216 .. code-block:: python
1217
1218 # This snippet has been automatically generated and should be regarded as a
1219 # code template only.
1220 # It will require modifications to work:
1221 # - It may require correct/in-range values for request initialization.
1222 # - It may require specifying regional endpoints when creating the service
1223 # client as shown in:
1224 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1225 from google import pubsub_v1
1226
1227 def sample_commit_schema():
1228 # Create a client
1229 client = pubsub_v1.SchemaServiceClient()
1230
1231 # Initialize request argument(s)
1232 schema = pubsub_v1.Schema()
1233 schema.name = "name_value"
1234
1235 request = pubsub_v1.CommitSchemaRequest(
1236 name="name_value",
1237 schema=schema,
1238 )
1239
1240 # Make the request
1241 response = client.commit_schema(request=request)
1242
1243 # Handle the response
1244 print(response)
1245
1246 Args:
1247 request (Union[google.pubsub_v1.types.CommitSchemaRequest, dict]):
1248 The request object. Request for CommitSchema method.
1249 name (str):
1250 Required. The name of the schema we are revising. Format
1251 is ``projects/{project}/schemas/{schema}``.
1252
1253 This corresponds to the ``name`` field
1254 on the ``request`` instance; if ``request`` is provided, this
1255 should not be set.
1256 schema (google.pubsub_v1.types.Schema):
1257 Required. The schema revision to
1258 commit.
1259
1260 This corresponds to the ``schema`` field
1261 on the ``request`` instance; if ``request`` is provided, this
1262 should not be set.
1263 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1264 should be retried.
1265 timeout (float): The timeout for this request.
1266 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1267 sent along with the request as metadata. Normally, each value must be of type `str`,
1268 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1269 be of type `bytes`.
1270
1271 Returns:
1272 google.pubsub_v1.types.Schema:
1273 A schema resource.
1274 """
1275 # Create or coerce a protobuf request object.
1276 # - Quick check: If we got a request object, we should *not* have
1277 # gotten any keyword arguments that map to the request.
1278 flattened_params = [name, schema]
1279 has_flattened_params = (
1280 len([param for param in flattened_params if param is not None]) > 0
1281 )
1282 if request is not None and has_flattened_params:
1283 raise ValueError(
1284 "If the `request` argument is set, then none of "
1285 "the individual field arguments should be set."
1286 )
1287
1288 # - Use the request object if provided (there's no risk of modifying the input as
1289 # there are no flattened fields), or create one.
1290 if not isinstance(request, gp_schema.CommitSchemaRequest):
1291 request = gp_schema.CommitSchemaRequest(request)
1292 # If we have keyword arguments corresponding to fields on the
1293 # request, apply these.
1294 if name is not None:
1295 request.name = name
1296 if schema is not None:
1297 request.schema = schema
1298
1299 # Wrap the RPC method; this adds retry and timeout information,
1300 # and friendly error handling.
1301 rpc = self._transport._wrapped_methods[self._transport.commit_schema]
1302
1303 # Certain fields should be provided within the metadata header;
1304 # add these here.
1305 metadata = tuple(metadata) + (
1306 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1307 )
1308
1309 # Validate the universe domain.
1310 self._validate_universe_domain()
1311
1312 # Send the request.
1313 response = rpc(
1314 request,
1315 retry=retry,
1316 timeout=timeout,
1317 metadata=metadata,
1318 )
1319
1320 # Done; return the response.
1321 return response
1322
1323 def rollback_schema(
1324 self,
1325 request: Optional[Union[schema.RollbackSchemaRequest, dict]] = None,
1326 *,
1327 name: Optional[str] = None,
1328 revision_id: Optional[str] = None,
1329 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1330 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1331 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1332 ) -> schema.Schema:
1333 r"""Creates a new schema revision that is a copy of the provided
1334 revision_id.
1335
1336 .. code-block:: python
1337
1338 # This snippet has been automatically generated and should be regarded as a
1339 # code template only.
1340 # It will require modifications to work:
1341 # - It may require correct/in-range values for request initialization.
1342 # - It may require specifying regional endpoints when creating the service
1343 # client as shown in:
1344 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1345 from google import pubsub_v1
1346
1347 def sample_rollback_schema():
1348 # Create a client
1349 client = pubsub_v1.SchemaServiceClient()
1350
1351 # Initialize request argument(s)
1352 request = pubsub_v1.RollbackSchemaRequest(
1353 name="name_value",
1354 revision_id="revision_id_value",
1355 )
1356
1357 # Make the request
1358 response = client.rollback_schema(request=request)
1359
1360 # Handle the response
1361 print(response)
1362
1363 Args:
1364 request (Union[google.pubsub_v1.types.RollbackSchemaRequest, dict]):
1365 The request object. Request for the ``RollbackSchema`` method.
1366 name (str):
1367 Required. The schema being rolled
1368 back with revision id.
1369
1370 This corresponds to the ``name`` field
1371 on the ``request`` instance; if ``request`` is provided, this
1372 should not be set.
1373 revision_id (str):
1374 Required. The revision ID to roll
1375 back to. It must be a revision of the
1376 same schema.
1377
1378 Example: c7cfa2a8
1379
1380 This corresponds to the ``revision_id`` field
1381 on the ``request`` instance; if ``request`` is provided, this
1382 should not be set.
1383 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1384 should be retried.
1385 timeout (float): The timeout for this request.
1386 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1387 sent along with the request as metadata. Normally, each value must be of type `str`,
1388 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1389 be of type `bytes`.
1390
1391 Returns:
1392 google.pubsub_v1.types.Schema:
1393 A schema resource.
1394 """
1395 # Create or coerce a protobuf request object.
1396 # - Quick check: If we got a request object, we should *not* have
1397 # gotten any keyword arguments that map to the request.
1398 flattened_params = [name, revision_id]
1399 has_flattened_params = (
1400 len([param for param in flattened_params if param is not None]) > 0
1401 )
1402 if request is not None and has_flattened_params:
1403 raise ValueError(
1404 "If the `request` argument is set, then none of "
1405 "the individual field arguments should be set."
1406 )
1407
1408 # - Use the request object if provided (there's no risk of modifying the input as
1409 # there are no flattened fields), or create one.
1410 if not isinstance(request, schema.RollbackSchemaRequest):
1411 request = schema.RollbackSchemaRequest(request)
1412 # If we have keyword arguments corresponding to fields on the
1413 # request, apply these.
1414 if name is not None:
1415 request.name = name
1416 if revision_id is not None:
1417 request.revision_id = revision_id
1418
1419 # Wrap the RPC method; this adds retry and timeout information,
1420 # and friendly error handling.
1421 rpc = self._transport._wrapped_methods[self._transport.rollback_schema]
1422
1423 # Certain fields should be provided within the metadata header;
1424 # add these here.
1425 metadata = tuple(metadata) + (
1426 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1427 )
1428
1429 # Validate the universe domain.
1430 self._validate_universe_domain()
1431
1432 # Send the request.
1433 response = rpc(
1434 request,
1435 retry=retry,
1436 timeout=timeout,
1437 metadata=metadata,
1438 )
1439
1440 # Done; return the response.
1441 return response
1442
1443 def delete_schema_revision(
1444 self,
1445 request: Optional[Union[schema.DeleteSchemaRevisionRequest, dict]] = None,
1446 *,
1447 name: Optional[str] = None,
1448 revision_id: Optional[str] = None,
1449 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1450 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1451 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1452 ) -> schema.Schema:
1453 r"""Deletes a specific schema revision.
1454
1455 .. code-block:: python
1456
1457 # This snippet has been automatically generated and should be regarded as a
1458 # code template only.
1459 # It will require modifications to work:
1460 # - It may require correct/in-range values for request initialization.
1461 # - It may require specifying regional endpoints when creating the service
1462 # client as shown in:
1463 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1464 from google import pubsub_v1
1465
1466 def sample_delete_schema_revision():
1467 # Create a client
1468 client = pubsub_v1.SchemaServiceClient()
1469
1470 # Initialize request argument(s)
1471 request = pubsub_v1.DeleteSchemaRevisionRequest(
1472 name="name_value",
1473 )
1474
1475 # Make the request
1476 response = client.delete_schema_revision(request=request)
1477
1478 # Handle the response
1479 print(response)
1480
1481 Args:
1482 request (Union[google.pubsub_v1.types.DeleteSchemaRevisionRequest, dict]):
1483 The request object. Request for the ``DeleteSchemaRevision`` method.
1484 name (str):
1485 Required. The name of the schema revision to be deleted,
1486 with a revision ID explicitly included.
1487
1488 Example: ``projects/123/schemas/my-schema@c7cfa2a8``
1489
1490 This corresponds to the ``name`` field
1491 on the ``request`` instance; if ``request`` is provided, this
1492 should not be set.
1493 revision_id (str):
1494 Optional. This field is deprecated and should not be
1495 used for specifying the revision ID. The revision ID
1496 should be specified via the ``name`` parameter.
1497
1498 This corresponds to the ``revision_id`` field
1499 on the ``request`` instance; if ``request`` is provided, this
1500 should not be set.
1501 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1502 should be retried.
1503 timeout (float): The timeout for this request.
1504 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1505 sent along with the request as metadata. Normally, each value must be of type `str`,
1506 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1507 be of type `bytes`.
1508
1509 Returns:
1510 google.pubsub_v1.types.Schema:
1511 A schema resource.
1512 """
1513 # Create or coerce a protobuf request object.
1514 # - Quick check: If we got a request object, we should *not* have
1515 # gotten any keyword arguments that map to the request.
1516 flattened_params = [name, revision_id]
1517 has_flattened_params = (
1518 len([param for param in flattened_params if param is not None]) > 0
1519 )
1520 if request is not None and has_flattened_params:
1521 raise ValueError(
1522 "If the `request` argument is set, then none of "
1523 "the individual field arguments should be set."
1524 )
1525
1526 # - Use the request object if provided (there's no risk of modifying the input as
1527 # there are no flattened fields), or create one.
1528 if not isinstance(request, schema.DeleteSchemaRevisionRequest):
1529 request = schema.DeleteSchemaRevisionRequest(request)
1530 # If we have keyword arguments corresponding to fields on the
1531 # request, apply these.
1532 if name is not None:
1533 request.name = name
1534 if revision_id is not None:
1535 request.revision_id = revision_id
1536
1537 # Wrap the RPC method; this adds retry and timeout information,
1538 # and friendly error handling.
1539 rpc = self._transport._wrapped_methods[self._transport.delete_schema_revision]
1540
1541 # Certain fields should be provided within the metadata header;
1542 # add these here.
1543 metadata = tuple(metadata) + (
1544 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1545 )
1546
1547 # Validate the universe domain.
1548 self._validate_universe_domain()
1549
1550 # Send the request.
1551 response = rpc(
1552 request,
1553 retry=retry,
1554 timeout=timeout,
1555 metadata=metadata,
1556 )
1557
1558 # Done; return the response.
1559 return response
1560
1561 def delete_schema(
1562 self,
1563 request: Optional[Union[schema.DeleteSchemaRequest, dict]] = None,
1564 *,
1565 name: Optional[str] = None,
1566 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1567 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1568 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1569 ) -> None:
1570 r"""Deletes a schema.
1571
1572 .. code-block:: python
1573
1574 # This snippet has been automatically generated and should be regarded as a
1575 # code template only.
1576 # It will require modifications to work:
1577 # - It may require correct/in-range values for request initialization.
1578 # - It may require specifying regional endpoints when creating the service
1579 # client as shown in:
1580 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1581 from google import pubsub_v1
1582
1583 def sample_delete_schema():
1584 # Create a client
1585 client = pubsub_v1.SchemaServiceClient()
1586
1587 # Initialize request argument(s)
1588 request = pubsub_v1.DeleteSchemaRequest(
1589 name="name_value",
1590 )
1591
1592 # Make the request
1593 client.delete_schema(request=request)
1594
1595 Args:
1596 request (Union[google.pubsub_v1.types.DeleteSchemaRequest, dict]):
1597 The request object. Request for the ``DeleteSchema`` method.
1598 name (str):
1599 Required. Name of the schema to delete. Format is
1600 ``projects/{project}/schemas/{schema}``.
1601
1602 This corresponds to the ``name`` field
1603 on the ``request`` instance; if ``request`` is provided, this
1604 should not be set.
1605 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1606 should be retried.
1607 timeout (float): The timeout for this request.
1608 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1609 sent along with the request as metadata. Normally, each value must be of type `str`,
1610 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1611 be of type `bytes`.
1612 """
1613 # Create or coerce a protobuf request object.
1614 # - Quick check: If we got a request object, we should *not* have
1615 # gotten any keyword arguments that map to the request.
1616 flattened_params = [name]
1617 has_flattened_params = (
1618 len([param for param in flattened_params if param is not None]) > 0
1619 )
1620 if request is not None and has_flattened_params:
1621 raise ValueError(
1622 "If the `request` argument is set, then none of "
1623 "the individual field arguments should be set."
1624 )
1625
1626 # - Use the request object if provided (there's no risk of modifying the input as
1627 # there are no flattened fields), or create one.
1628 if not isinstance(request, schema.DeleteSchemaRequest):
1629 request = schema.DeleteSchemaRequest(request)
1630 # If we have keyword arguments corresponding to fields on the
1631 # request, apply these.
1632 if name is not None:
1633 request.name = name
1634
1635 # Wrap the RPC method; this adds retry and timeout information,
1636 # and friendly error handling.
1637 rpc = self._transport._wrapped_methods[self._transport.delete_schema]
1638
1639 # Certain fields should be provided within the metadata header;
1640 # add these here.
1641 metadata = tuple(metadata) + (
1642 gapic_v1.routing_header.to_grpc_metadata((("name", request.name),)),
1643 )
1644
1645 # Validate the universe domain.
1646 self._validate_universe_domain()
1647
1648 # Send the request.
1649 rpc(
1650 request,
1651 retry=retry,
1652 timeout=timeout,
1653 metadata=metadata,
1654 )
1655
1656 def validate_schema(
1657 self,
1658 request: Optional[Union[gp_schema.ValidateSchemaRequest, dict]] = None,
1659 *,
1660 parent: Optional[str] = None,
1661 schema: Optional[gp_schema.Schema] = None,
1662 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1663 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1664 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1665 ) -> gp_schema.ValidateSchemaResponse:
1666 r"""Validates a schema.
1667
1668 .. code-block:: python
1669
1670 # This snippet has been automatically generated and should be regarded as a
1671 # code template only.
1672 # It will require modifications to work:
1673 # - It may require correct/in-range values for request initialization.
1674 # - It may require specifying regional endpoints when creating the service
1675 # client as shown in:
1676 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1677 from google import pubsub_v1
1678
1679 def sample_validate_schema():
1680 # Create a client
1681 client = pubsub_v1.SchemaServiceClient()
1682
1683 # Initialize request argument(s)
1684 schema = pubsub_v1.Schema()
1685 schema.name = "name_value"
1686
1687 request = pubsub_v1.ValidateSchemaRequest(
1688 parent="parent_value",
1689 schema=schema,
1690 )
1691
1692 # Make the request
1693 response = client.validate_schema(request=request)
1694
1695 # Handle the response
1696 print(response)
1697
1698 Args:
1699 request (Union[google.pubsub_v1.types.ValidateSchemaRequest, dict]):
1700 The request object. Request for the ``ValidateSchema`` method.
1701 parent (str):
1702 Required. The name of the project in which to validate
1703 schemas. Format is ``projects/{project-id}``.
1704
1705 This corresponds to the ``parent`` field
1706 on the ``request`` instance; if ``request`` is provided, this
1707 should not be set.
1708 schema (google.pubsub_v1.types.Schema):
1709 Required. The schema object to
1710 validate.
1711
1712 This corresponds to the ``schema`` field
1713 on the ``request`` instance; if ``request`` is provided, this
1714 should not be set.
1715 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1716 should be retried.
1717 timeout (float): The timeout for this request.
1718 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1719 sent along with the request as metadata. Normally, each value must be of type `str`,
1720 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1721 be of type `bytes`.
1722
1723 Returns:
1724 google.pubsub_v1.types.ValidateSchemaResponse:
1725 Response for the ValidateSchema method.
1726 Empty for now.
1727
1728 """
1729 # Create or coerce a protobuf request object.
1730 # - Quick check: If we got a request object, we should *not* have
1731 # gotten any keyword arguments that map to the request.
1732 flattened_params = [parent, schema]
1733 has_flattened_params = (
1734 len([param for param in flattened_params if param is not None]) > 0
1735 )
1736 if request is not None and has_flattened_params:
1737 raise ValueError(
1738 "If the `request` argument is set, then none of "
1739 "the individual field arguments should be set."
1740 )
1741
1742 # - Use the request object if provided (there's no risk of modifying the input as
1743 # there are no flattened fields), or create one.
1744 if not isinstance(request, gp_schema.ValidateSchemaRequest):
1745 request = gp_schema.ValidateSchemaRequest(request)
1746 # If we have keyword arguments corresponding to fields on the
1747 # request, apply these.
1748 if parent is not None:
1749 request.parent = parent
1750 if schema is not None:
1751 request.schema = schema
1752
1753 # Wrap the RPC method; this adds retry and timeout information,
1754 # and friendly error handling.
1755 rpc = self._transport._wrapped_methods[self._transport.validate_schema]
1756
1757 # Certain fields should be provided within the metadata header;
1758 # add these here.
1759 metadata = tuple(metadata) + (
1760 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
1761 )
1762
1763 # Validate the universe domain.
1764 self._validate_universe_domain()
1765
1766 # Send the request.
1767 response = rpc(
1768 request,
1769 retry=retry,
1770 timeout=timeout,
1771 metadata=metadata,
1772 )
1773
1774 # Done; return the response.
1775 return response
1776
1777 def validate_message(
1778 self,
1779 request: Optional[Union[schema.ValidateMessageRequest, dict]] = None,
1780 *,
1781 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1782 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1783 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1784 ) -> schema.ValidateMessageResponse:
1785 r"""Validates a message against a schema.
1786
1787 .. code-block:: python
1788
1789 # This snippet has been automatically generated and should be regarded as a
1790 # code template only.
1791 # It will require modifications to work:
1792 # - It may require correct/in-range values for request initialization.
1793 # - It may require specifying regional endpoints when creating the service
1794 # client as shown in:
1795 # https://googleapis.dev/python/google-api-core/latest/client_options.html
1796 from google import pubsub_v1
1797
1798 def sample_validate_message():
1799 # Create a client
1800 client = pubsub_v1.SchemaServiceClient()
1801
1802 # Initialize request argument(s)
1803 request = pubsub_v1.ValidateMessageRequest(
1804 name="name_value",
1805 parent="parent_value",
1806 )
1807
1808 # Make the request
1809 response = client.validate_message(request=request)
1810
1811 # Handle the response
1812 print(response)
1813
1814 Args:
1815 request (Union[google.pubsub_v1.types.ValidateMessageRequest, dict]):
1816 The request object. Request for the ``ValidateMessage`` method.
1817 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1818 should be retried.
1819 timeout (float): The timeout for this request.
1820 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1821 sent along with the request as metadata. Normally, each value must be of type `str`,
1822 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1823 be of type `bytes`.
1824
1825 Returns:
1826 google.pubsub_v1.types.ValidateMessageResponse:
1827 Response for the ValidateMessage method.
1828 Empty for now.
1829
1830 """
1831 # Create or coerce a protobuf request object.
1832 # - Use the request object if provided (there's no risk of modifying the input as
1833 # there are no flattened fields), or create one.
1834 if not isinstance(request, schema.ValidateMessageRequest):
1835 request = schema.ValidateMessageRequest(request)
1836
1837 # Wrap the RPC method; this adds retry and timeout information,
1838 # and friendly error handling.
1839 rpc = self._transport._wrapped_methods[self._transport.validate_message]
1840
1841 # Certain fields should be provided within the metadata header;
1842 # add these here.
1843 metadata = tuple(metadata) + (
1844 gapic_v1.routing_header.to_grpc_metadata((("parent", request.parent),)),
1845 )
1846
1847 # Validate the universe domain.
1848 self._validate_universe_domain()
1849
1850 # Send the request.
1851 response = rpc(
1852 request,
1853 retry=retry,
1854 timeout=timeout,
1855 metadata=metadata,
1856 )
1857
1858 # Done; return the response.
1859 return response
1860
1861 def __enter__(self) -> "SchemaServiceClient":
1862 return self
1863
1864 def __exit__(self, type, value, traceback):
1865 """Releases underlying transport's resources.
1866
1867 .. warning::
1868 ONLY use as a context manager if the transport is NOT shared
1869 with other clients! Exiting the with block will CLOSE the transport
1870 and may cause errors in other clients!
1871 """
1872 self.transport.close()
1873
1874 def set_iam_policy(
1875 self,
1876 request: Optional[iam_policy_pb2.SetIamPolicyRequest] = None,
1877 *,
1878 retry: OptionalRetry = gapic_v1.method.DEFAULT,
1879 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
1880 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
1881 ) -> policy_pb2.Policy:
1882 r"""Sets the IAM access control policy on the specified function.
1883
1884 Replaces any existing policy.
1885
1886 Args:
1887 request (:class:`~.iam_policy_pb2.SetIamPolicyRequest`):
1888 The request object. Request message for `SetIamPolicy`
1889 method.
1890 retry (google.api_core.retry.Retry): Designation of what errors, if any,
1891 should be retried.
1892 timeout (float): The timeout for this request.
1893 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
1894 sent along with the request as metadata. Normally, each value must be of type `str`,
1895 but for metadata keys ending with the suffix `-bin`, the corresponding values must
1896 be of type `bytes`.
1897 Returns:
1898 ~.policy_pb2.Policy:
1899 Defines an Identity and Access Management (IAM) policy.
1900 It is used to specify access control policies for Cloud
1901 Platform resources.
1902 A ``Policy`` is a collection of ``bindings``. A
1903 ``binding`` binds one or more ``members`` to a single
1904 ``role``. Members can be user accounts, service
1905 accounts, Google groups, and domains (such as G Suite).
1906 A ``role`` is a named list of permissions (defined by
1907 IAM or configured by users). A ``binding`` can
1908 optionally specify a ``condition``, which is a logic
1909 expression that further constrains the role binding
1910 based on attributes about the request and/or target
1911 resource.
1912
1913 **JSON Example**
1914
1915 ::
1916
1917 {
1918 "bindings": [
1919 {
1920 "role": "roles/resourcemanager.organizationAdmin",
1921 "members": [
1922 "user:mike@example.com",
1923 "group:admins@example.com",
1924 "domain:google.com",
1925 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
1926 ]
1927 },
1928 {
1929 "role": "roles/resourcemanager.organizationViewer",
1930 "members": ["user:eve@example.com"],
1931 "condition": {
1932 "title": "expirable access",
1933 "description": "Does not grant access after Sep 2020",
1934 "expression": "request.time <
1935 timestamp('2020-10-01T00:00:00.000Z')",
1936 }
1937 }
1938 ]
1939 }
1940
1941 **YAML Example**
1942
1943 ::
1944
1945 bindings:
1946 - members:
1947 - user:mike@example.com
1948 - group:admins@example.com
1949 - domain:google.com
1950 - serviceAccount:my-project-id@appspot.gserviceaccount.com
1951 role: roles/resourcemanager.organizationAdmin
1952 - members:
1953 - user:eve@example.com
1954 role: roles/resourcemanager.organizationViewer
1955 condition:
1956 title: expirable access
1957 description: Does not grant access after Sep 2020
1958 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
1959
1960 For a description of IAM and its features, see the `IAM
1961 developer's
1962 guide <https://cloud.google.com/iam/docs>`__.
1963 """
1964 # Create or coerce a protobuf request object.
1965
1966 # The request isn't a proto-plus wrapped type,
1967 # so it must be constructed via keyword expansion.
1968 if isinstance(request, dict):
1969 request = iam_policy_pb2.SetIamPolicyRequest(**request)
1970
1971 # Wrap the RPC method; this adds retry and timeout information,
1972 # and friendly error handling.
1973 rpc = self._transport._wrapped_methods[self._transport.set_iam_policy]
1974
1975 # Certain fields should be provided within the metadata header;
1976 # add these here.
1977 metadata = tuple(metadata) + (
1978 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
1979 )
1980
1981 # Validate the universe domain.
1982 self._validate_universe_domain()
1983
1984 try:
1985 # Send the request.
1986 response = rpc(
1987 request,
1988 retry=retry,
1989 timeout=timeout,
1990 metadata=metadata,
1991 )
1992
1993 # Done; return the response.
1994 return response
1995 except core_exceptions.GoogleAPICallError as e:
1996 self._add_cred_info_for_auth_errors(e)
1997 raise e
1998
1999 def get_iam_policy(
2000 self,
2001 request: Optional[iam_policy_pb2.GetIamPolicyRequest] = None,
2002 *,
2003 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2004 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2005 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2006 ) -> policy_pb2.Policy:
2007 r"""Gets the IAM access control policy for a function.
2008
2009 Returns an empty policy if the function exists and does not have a
2010 policy set.
2011
2012 Args:
2013 request (:class:`~.iam_policy_pb2.GetIamPolicyRequest`):
2014 The request object. Request message for `GetIamPolicy`
2015 method.
2016 retry (google.api_core.retry.Retry): Designation of what errors, if
2017 any, should be retried.
2018 timeout (float): The timeout for this request.
2019 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2020 sent along with the request as metadata. Normally, each value must be of type `str`,
2021 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2022 be of type `bytes`.
2023 Returns:
2024 ~.policy_pb2.Policy:
2025 Defines an Identity and Access Management (IAM) policy.
2026 It is used to specify access control policies for Cloud
2027 Platform resources.
2028 A ``Policy`` is a collection of ``bindings``. A
2029 ``binding`` binds one or more ``members`` to a single
2030 ``role``. Members can be user accounts, service
2031 accounts, Google groups, and domains (such as G Suite).
2032 A ``role`` is a named list of permissions (defined by
2033 IAM or configured by users). A ``binding`` can
2034 optionally specify a ``condition``, which is a logic
2035 expression that further constrains the role binding
2036 based on attributes about the request and/or target
2037 resource.
2038
2039 **JSON Example**
2040
2041 ::
2042
2043 {
2044 "bindings": [
2045 {
2046 "role": "roles/resourcemanager.organizationAdmin",
2047 "members": [
2048 "user:mike@example.com",
2049 "group:admins@example.com",
2050 "domain:google.com",
2051 "serviceAccount:my-project-id@appspot.gserviceaccount.com"
2052 ]
2053 },
2054 {
2055 "role": "roles/resourcemanager.organizationViewer",
2056 "members": ["user:eve@example.com"],
2057 "condition": {
2058 "title": "expirable access",
2059 "description": "Does not grant access after Sep 2020",
2060 "expression": "request.time <
2061 timestamp('2020-10-01T00:00:00.000Z')",
2062 }
2063 }
2064 ]
2065 }
2066
2067 **YAML Example**
2068
2069 ::
2070
2071 bindings:
2072 - members:
2073 - user:mike@example.com
2074 - group:admins@example.com
2075 - domain:google.com
2076 - serviceAccount:my-project-id@appspot.gserviceaccount.com
2077 role: roles/resourcemanager.organizationAdmin
2078 - members:
2079 - user:eve@example.com
2080 role: roles/resourcemanager.organizationViewer
2081 condition:
2082 title: expirable access
2083 description: Does not grant access after Sep 2020
2084 expression: request.time < timestamp('2020-10-01T00:00:00.000Z')
2085
2086 For a description of IAM and its features, see the `IAM
2087 developer's
2088 guide <https://cloud.google.com/iam/docs>`__.
2089 """
2090 # Create or coerce a protobuf request object.
2091
2092 # The request isn't a proto-plus wrapped type,
2093 # so it must be constructed via keyword expansion.
2094 if isinstance(request, dict):
2095 request = iam_policy_pb2.GetIamPolicyRequest(**request)
2096
2097 # Wrap the RPC method; this adds retry and timeout information,
2098 # and friendly error handling.
2099 rpc = self._transport._wrapped_methods[self._transport.get_iam_policy]
2100
2101 # Certain fields should be provided within the metadata header;
2102 # add these here.
2103 metadata = tuple(metadata) + (
2104 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2105 )
2106
2107 # Validate the universe domain.
2108 self._validate_universe_domain()
2109
2110 try:
2111 # Send the request.
2112 response = rpc(
2113 request,
2114 retry=retry,
2115 timeout=timeout,
2116 metadata=metadata,
2117 )
2118
2119 # Done; return the response.
2120 return response
2121 except core_exceptions.GoogleAPICallError as e:
2122 self._add_cred_info_for_auth_errors(e)
2123 raise e
2124
2125 def test_iam_permissions(
2126 self,
2127 request: Optional[iam_policy_pb2.TestIamPermissionsRequest] = None,
2128 *,
2129 retry: OptionalRetry = gapic_v1.method.DEFAULT,
2130 timeout: Union[float, object] = gapic_v1.method.DEFAULT,
2131 metadata: Sequence[Tuple[str, Union[str, bytes]]] = (),
2132 ) -> iam_policy_pb2.TestIamPermissionsResponse:
2133 r"""Tests the specified IAM permissions against the IAM access control
2134 policy for a function.
2135
2136 If the function does not exist, this will return an empty set
2137 of permissions, not a NOT_FOUND error.
2138
2139 Args:
2140 request (:class:`~.iam_policy_pb2.TestIamPermissionsRequest`):
2141 The request object. Request message for
2142 `TestIamPermissions` method.
2143 retry (google.api_core.retry.Retry): Designation of what errors,
2144 if any, should be retried.
2145 timeout (float): The timeout for this request.
2146 metadata (Sequence[Tuple[str, Union[str, bytes]]]): Key/value pairs which should be
2147 sent along with the request as metadata. Normally, each value must be of type `str`,
2148 but for metadata keys ending with the suffix `-bin`, the corresponding values must
2149 be of type `bytes`.
2150 Returns:
2151 ~.iam_policy_pb2.TestIamPermissionsResponse:
2152 Response message for ``TestIamPermissions`` method.
2153 """
2154 # Create or coerce a protobuf request object.
2155
2156 # The request isn't a proto-plus wrapped type,
2157 # so it must be constructed via keyword expansion.
2158 if isinstance(request, dict):
2159 request = iam_policy_pb2.TestIamPermissionsRequest(**request)
2160
2161 # Wrap the RPC method; this adds retry and timeout information,
2162 # and friendly error handling.
2163 rpc = self._transport._wrapped_methods[self._transport.test_iam_permissions]
2164
2165 # Certain fields should be provided within the metadata header;
2166 # add these here.
2167 metadata = tuple(metadata) + (
2168 gapic_v1.routing_header.to_grpc_metadata((("resource", request.resource),)),
2169 )
2170
2171 # Validate the universe domain.
2172 self._validate_universe_domain()
2173
2174 try:
2175 # Send the request.
2176 response = rpc(
2177 request,
2178 retry=retry,
2179 timeout=timeout,
2180 metadata=metadata,
2181 )
2182
2183 # Done; return the response.
2184 return response
2185 except core_exceptions.GoogleAPICallError as e:
2186 self._add_cred_info_for_auth_errors(e)
2187 raise e
2188
2189
2190DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
2191 client_library_version=package_version.__version__
2192)
2193
2194if hasattr(DEFAULT_CLIENT_INFO, "protobuf_runtime_version"): # pragma: NO COVER
2195 DEFAULT_CLIENT_INFO.protobuf_runtime_version = google.protobuf.__version__
2196
2197__all__ = ("SchemaServiceClient",)